/* eslint-disable */
// MagazinesScreen — archive of past PDF magazines. State machine: archive → viewer.
// PDFs are self-hosted on R2; viewed in the browser's built-in PDF viewer via an
// <iframe>, with an "open in new tab" fallback for mobile (iOS won't render PDF in
// an iframe).

const MagazinesScreen = ({ setRoute }) => {
  const t = (window.useT && window.useT()) || ((k) => k);
  const [items, setItems] = React.useState(window.CBM_MAGAZINES || []);
  const [active, setActive] = React.useState(null); // a magazine object, or null
  const [status, setStatus] = React.useState((window.CBM_MAGAZINES || []).length ? 'ok' : 'loading');

  React.useEffect(() => {
    fetch('/data/magazines.json?_=' + Math.floor(Date.now() / 3600000))
      .then(r => r.ok ? r.json() : Promise.reject(r.status))
      .then(d => {
        if (Array.isArray(d)) { window.CBM_MAGAZINES = d; setItems(d); }
        setStatus('ok');
      })
      .catch(() => setStatus('error'));
  }, []);

  React.useEffect(() => {
    if (window.lucide && window.lucide.createIcons) window.lucide.createIcons();
  }, [active, items]);

  const list = items
    .filter(m => m.published !== false)
    .slice()
    .sort((a, b) => (b.year || 0) - (a.year || 0) || String(b.edition || '').localeCompare(String(a.edition || '')));

  // ── Viewer ────────────────────────────────────────────────────────────────
  if (active) {
    return (
      <div className="cbm-apply" data-screen-label="MagazineViewer">
        <button className="cbm-link-back" onClick={() => setActive(null)}>
          <i data-lucide="arrow-left"></i> {t('mag_back')}
        </button>
        <div style={{maxWidth: 1100, margin: '0 auto', padding: '0 20px 48px'}}>
          <div style={{display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: 16, flexWrap: 'wrap', margin: '8px 0 16px'}}>
            <h1 className="cbm-section__title" style={{color: 'var(--cbm-blue)', margin: 0}}>{active.title}</h1>
            <a className="cbm-btn cbm-btn--gold" href={active.pdf} target="_blank" rel="noopener noreferrer">
              {t('mag_open')} →
            </a>
          </div>
          <div style={{position: 'relative', width: '100%', height: '80vh', minHeight: 480, border: '1px solid var(--cbm-line, #d9dde3)', borderRadius: 6, overflow: 'hidden', background: '#525659'}}>
            <iframe
              src={active.pdf}
              title={active.title}
              style={{width: '100%', height: '100%', border: 0}}
            />
          </div>
          <p style={{fontSize: 13, color: 'var(--cbm-muted)', marginTop: 12}}>
            {t('mag_viewer_hint')}
          </p>
        </div>
      </div>
    );
  }

  // ── Archive grid ────────────────────────────────────────────────────────────
  return (
    <div data-screen-label="Magazines">
      <section className="cbm-section cbm-section--dark" style={{paddingTop: 72, paddingBottom: 48}}>
        <div className="cbm-section__inner">
          <span className="cbm-eyebrow">{t('mag_eyebrow')}</span>
          <div className="cbm-section-rule" />
          <h1 className="cbm-section__title">{t('mag_title')}</h1>
          <p className="cbm-section__lede" style={{marginTop: 14}}>{t('mag_lede')}</p>
        </div>
      </section>

      <section className="cbm-section" style={{paddingTop: 32}}>
        <div className="cbm-section__inner">
          {status === 'loading' ? (
            <div style={{padding: '48px 0', textAlign: 'center', color: 'var(--cbm-muted)'}}>
              {t('loading') || 'Loading…'}
            </div>
          ) : status === 'error' ? (
            <div style={{padding: '48px 0', textAlign: 'center', color: 'var(--cbm-muted)'}}>
              {t('mag_load_error') || 'Could not load magazines. Please try again later.'}
            </div>
          ) : list.length === 0 ? (
            <div style={{padding: '48px 0', textAlign: 'center', color: 'var(--cbm-muted)'}}>
              {t('mag_empty')}
            </div>
          ) : (
            <div className="cbm-magazines-grid" style={{display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(220px, 1fr))', gap: 28}}>
              {list.map(m => (
                <button
                  key={m.id}
                  onClick={() => setActive(m)}
                  style={{textAlign: 'left', background: 'none', border: 'none', padding: 0, cursor: 'pointer'}}
                >
                  <div style={{aspectRatio: '3 / 4', borderRadius: 6, overflow: 'hidden', background: 'var(--cbm-blue)', boxShadow: '0 6px 20px rgba(0,0,0,0.12)', display: 'flex', alignItems: 'center', justifyContent: 'center'}}>
                    {m.cover ? (
                      <img src={m.cover} alt={m.title} style={{width: '100%', height: '100%', objectFit: 'cover', display: 'block'}} />
                    ) : (
                      <i data-lucide="book-open" style={{color: 'rgba(255,255,255,0.6)', width: 40, height: 40}}></i>
                    )}
                  </div>
                  <h3 style={{fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 16, lineHeight: 1.3, margin: '12px 0 2px', color: 'var(--cbm-blue)'}}>
                    {m.title}
                  </h3>
                  <p style={{fontSize: 13, color: 'var(--cbm-muted)', margin: 0}}>
                    {[m.year, m.edition].filter(Boolean).join(' · ')}
                  </p>
                </button>
              ))}
            </div>
          )}
        </div>
      </section>
    </div>
  );
};

Object.assign(window, { MagazinesScreen });
