// El popup de descarga del launcher. Hasta ahora los tres botones que decían
// "descargar" llevaban a la guía: se explicaban los pasos con capturas, pero el
// fichero no estaba en ninguna parte. Aquí sí, y con las dos plataformas juntas
// para que nadie se lleve el binario equivocado.
//
// Los pesos y las fechas los pregunta a /download/meta.json, que a su vez se los
// pregunta a R2: así no hay números escritos a mano que envejezcan en cuanto se
// suba la siguiente build. Si esa petición falla, el popup sigue sirviendo —
// simplemente no enseña el peso; lo que no puede es dejar de dar la descarga.

const DESCARGA_EVENTO = 'ppl:download';

// Los botones de la portada no conocen el modal: piden la descarga y ya. Así
// Hero, Play y el área de mecenas no comparten estado con nadie.
function pedirDescarga(e) {
  if (e && e.preventDefault) e.preventDefault();
  window.dispatchEvent(new CustomEvent(DESCARGA_EVENTO));
}

const PLATAFORMAS = [
  { id: 'windows', Ic: () => Icon.Windows },
  { id: 'linux',   Ic: () => Icon.Linux },
];

// Para destacar la plataforma de quien mira, no para decidir por él: las dos
// descargas se ofrecen siempre. Android trae "Linux" en el userAgent y no es
// Linux para esto, así que se descarta aparte.
function sistemaProbable() {
  const ua = String(
    navigator.userAgentData?.platform || navigator.platform || navigator.userAgent || ''
  ).toLowerCase();
  if (ua.includes('android')) return null;
  if (ua.includes('win')) return 'windows';
  if (ua.includes('linux') || ua.includes('x11')) return 'linux';
  return null;
}

function DownloadModal() {
  const { t, lang } = useI18n();
  const [abierto, setAbierto] = React.useState(false);
  const [meta, setMeta] = React.useState(null);
  const mio = React.useMemo(sistemaProbable, []);
  const cerrar = React.useCallback(() => setAbierto(false), []);

  React.useEffect(() => {
    const abrir = () => setAbierto(true);
    window.addEventListener(DESCARGA_EVENTO, abrir);
    return () => window.removeEventListener(DESCARGA_EVENTO, abrir);
  }, []);

  // Los pesos se piden la primera vez que se abre, no al cargar la página: son
  // dos HEAD contra R2 y no hacen falta hasta que alguien quiere descargar.
  React.useEffect(() => {
    if (!abierto || meta) return;
    let vivo = true;
    fetch('/download/meta.json')
      .then(r => (r.ok ? r.json() : null))
      .then(d => { if (vivo && d) setMeta(d); })
      .catch(() => {});
    return () => { vivo = false; };
  }, [abierto, meta]);

  React.useEffect(() => {
    document.body.classList.toggle('locked', abierto);
    if (!abierto) return;
    const onKey = (e) => { if (e.key === 'Escape') cerrar(); };
    window.addEventListener('keydown', onKey);
    return () => {
      window.removeEventListener('keydown', onKey);
      document.body.classList.remove('locked');
    };
  }, [abierto, cerrar]);

  if (!abierto) return null;

  const fmtPeso = (bytes) =>
    new Intl.NumberFormat(lang, { maximumFractionDigits: 0 }).format(bytes / 1e6) + ' MB';

  const fmtCuando = (iso) => {
    const d = new Date(iso);
    if (isNaN(d)) return null;
    return new Intl.DateTimeFormat(lang, { day: 'numeric', month: 'long', year: 'numeric' }).format(d);
  };

  return (
    <div style={dlS.overlay} onClick={cerrar} role="dialog" aria-modal="true" aria-labelledby="dl-title">
      <div className="card reveal" style={dlS.modal} onClick={(e) => e.stopPropagation()}>
        <button className="btn btn-ghost btn-sm" onClick={cerrar} style={dlS.cerrar} aria-label={t('download.close')}>
          <Icon.X style={{ width: 13, height: 13 }} />
        </button>

        <Icon.Download style={{ width: 26, height: 26, color: 'var(--gold)' }} />
        <h2 id="dl-title" className="display" style={{ fontSize: 'clamp(24px, 3.4vw, 32px)', marginTop: 12 }}>
          {t('download.title')}
        </h2>
        <p style={dlS.lead}>{t('download.lead')}</p>

        <div className="grid-2" style={{ margin: '24px 0 20px' }}>
          {PLATAFORMAS.map(({ id, Ic }) => {
            const Marca = Ic();
            const datos = meta?.[id];
            const cuando = datos?.updated ? fmtCuando(datos.updated) : null;
            return (
              <div key={id} style={{ ...dlS.tarjeta, ...(mio === id ? dlS.tarjetaMia : null) }}>
                <div className="row" style={{ gap: 10, alignItems: 'center' }}>
                  <Marca style={{ width: 24, height: 24, color: 'var(--gold)' }} />
                  <h3 className="display" style={{ fontSize: 20, flex: 1 }}>{t(`download.${id}.name`)}</h3>
                  {mio === id && <span className="chip chip-ea">{t('download.suggested')}</span>}
                </div>

                <div className="mono" style={dlS.req}>{t(`download.${id}.req`)}</div>

                <a className="btn btn-gold" href={`/download/${id}`} download onClick={cerrar} style={{ marginTop: 4 }}>
                  <Icon.Download /> {t('download.cta')}
                </a>

                <div className="mono" style={dlS.ficha}>
                  {datos ? `${datos.file} · ${fmtPeso(datos.size)}` : ' '}
                </div>
                {cuando && <div style={dlS.cuando}>{t('download.updated', { date: cuando })}</div>}

                <p style={dlS.aviso}>{t(`download.${id}.warn`)}</p>
              </div>
            );
          })}
        </div>

        <div style={dlS.pie}>
          <p style={{ color: 'var(--tx-md)', fontSize: 13.5, lineHeight: 1.55, flex: '1 1 240px' }}>
            {t('download.foot')}
          </p>
          <a className="btn btn-ghost btn-sm" href="#guides" onClick={cerrar}>
            <Icon.Book style={{ width: 13, height: 13 }} /> {t('download.guide')}
          </a>
        </div>
      </div>
    </div>
  );
}

const dlS = {
  overlay: {
    position: 'fixed', inset: 0, zIndex: 150, background: 'rgba(12,8,3,.94)',
    backdropFilter: 'blur(8px)', WebkitBackdropFilter: 'blur(8px)',
    display: 'flex', alignItems: 'center', justifyContent: 'center',
    padding: 24, overflow: 'auto',
  },
  modal: {
    position: 'relative', maxWidth: 720, width: '100%', padding: '32px 34px 26px',
    background: 'linear-gradient(180deg, var(--bg2), var(--bg0))', borderColor: 'var(--gold)',
  },
  cerrar: { position: 'absolute', top: 16, right: 16, padding: '7px 9px' },
  lead: { color: 'var(--tx-md)', fontSize: 15, lineHeight: 1.6, marginTop: 10, maxWidth: '58ch' },
  tarjeta: {
    display: 'flex', flexDirection: 'column', gap: 10,
    background: 'var(--bg1)', border: '1px solid var(--line-soft)',
    borderRadius: 'var(--r)', padding: 20,
  },
  tarjetaMia: { borderColor: 'var(--gold)', background: 'rgba(192,138,43,.06)' },
  req: { fontSize: 11.5, color: 'var(--tx-lo)', letterSpacing: '.04em' },
  ficha: { fontSize: 11, color: 'var(--gold-hi)', wordBreak: 'break-all', minHeight: 16 },
  cuando: { fontSize: 11.5, color: 'var(--tx-lo)', marginTop: -4 },
  aviso: { fontSize: 12.5, color: 'var(--tx-lo)', lineHeight: 1.5, marginTop: 2 },
  pie: {
    display: 'flex', flexWrap: 'wrap', gap: 14, alignItems: 'center',
    justifyContent: 'space-between', paddingTop: 18, borderTop: '1px solid var(--line-soft)',
  },
};

Object.assign(window, { DownloadModal, pedirDescarga });
