// sections.jsx — landing page sections, composing the mock UI fragments.

function getShelfireSite() {
  const site = window.SHELDFIRE_SITE;
  if (site) return site;
  return {
    version: '0.0.0',
    windowsInstallerUrl: '#download',
    releasesPageUrl: '#download',
    supportApiBase: 'https://series-tracker-user-data-api.thgebarata.workers.dev',
  };
}

const NAV_LINKS = [
  { id: 'player', key: 'nav.player' },
  { id: 'tracking', key: 'nav.tracking' },
  { id: 'lists', key: 'nav.lists' },
  { id: 'themes', key: 'nav.themes' },
  { id: 'pricing', key: 'nav.pricing' },
  { id: 'support', key: 'nav.support' },
];

function FlagIcon({ code, size = 16 }) {
  if (code === 'auto') {
    return (
      <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ opacity: 0.7 }}>
        <circle cx="12" cy="12" r="10" />
        <line x1="2" y1="12" x2="22" y2="12" />
        <path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z" />
      </svg>
    );
  }
  return (
    <img
      src={`https://flagcdn.com/w20/${code}.png`}
      alt=""
      width={size}
      height={Math.round(size * 0.75)}
      style={{ borderRadius: 2, objectFit: 'cover' }}
    />
  );
}

function LanguagePicker({ locale, setLocale, ariaLabel }) {
  const [open, setOpen] = React.useState(false);
  const containerRef = React.useRef(null);
  const selected = AVAILABLE_LANGUAGES.find((l) => l.code === locale) || AVAILABLE_LANGUAGES[0];

  React.useEffect(() => {
    if (!open) return;
    const handlePointerDown = (e) => {
      if (!containerRef.current?.contains(e.target)) setOpen(false);
    };
    document.addEventListener('mousedown', handlePointerDown);
    return () => document.removeEventListener('mousedown', handlePointerDown);
  }, [open]);

  return (
    <div ref={containerRef} style={{ position: 'relative' }}>
      <button
        type="button"
        aria-label={ariaLabel}
        aria-haspopup="listbox"
        aria-expanded={open}
        onClick={() => setOpen((v) => !v)}
        style={{
          display: 'inline-flex', alignItems: 'center', gap: 6,
          padding: '6px 10px', borderRadius: 7,
          border: '.5px solid var(--line)', background: 'var(--surface)',
          color: 'var(--fg)', fontFamily: 'var(--sans)', fontSize: 12.5,
          cursor: 'pointer', transition: 'border-color .15s ease',
        }}
      >
        <FlagIcon code={selected.flag} size={16} />
        <span style={{ fontWeight: 500 }}>{selected.acronym}</span>
        <svg width="8" height="5" viewBox="0 0 10 6" style={{ opacity: 0.6 }}>
          <path fill="currentColor" d="M1 1l4 4 4-4" />
        </svg>
      </button>
      {open && (
        <div
          role="listbox"
          style={{
            position: 'absolute', right: 0, top: 'calc(100% + 6px)',
            minWidth: 180, maxHeight: 320, overflowY: 'auto',
            borderRadius: 10, border: '.5px solid var(--line)',
            background: 'var(--surface)', boxShadow: '0 12px 40px rgba(0,0,0,.4)',
            padding: 4, zIndex: 100,
          }}
        >
          {AVAILABLE_LANGUAGES.map((lang) => {
            const isSelected = lang.code === locale;
            return (
              <button
                key={lang.code}
                type="button"
                role="option"
                aria-selected={isSelected}
                onClick={() => { setLocale(lang.code); setOpen(false); }}
                style={{
                  display: 'flex', alignItems: 'center', gap: 10,
                  width: '100%', padding: '8px 10px', borderRadius: 6,
                  border: 'none', background: isSelected ? 'var(--accent-soft)' : 'transparent',
                  color: 'var(--fg)', fontFamily: 'var(--sans)', fontSize: 13,
                  cursor: 'pointer', textAlign: 'left',
                  transition: 'background .1s ease',
                }}
                onMouseEnter={(e) => { if (!isSelected) e.currentTarget.style.background = 'color-mix(in oklch, var(--fg) 8%, transparent)'; }}
                onMouseLeave={(e) => { if (!isSelected) e.currentTarget.style.background = 'transparent'; }}
              >
                <FlagIcon code={lang.flag} size={18} />
                <span style={{ flex: 1 }}>{lang.label}</span>
                {isSelected && (
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="var(--accent)" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                    <polyline points="20 6 9 17 4 12" />
                  </svg>
                )}
              </button>
            );
          })}
        </div>
      )}
    </div>
  );
}

function Nav() {
  const { t, locale, setLocale } = useLandingT();
  const [active, setActive] = React.useState(null);

  React.useEffect(() => {
    const ids = NAV_LINKS.map((l) => l.id);
    const sections = ids
      .map((id) => document.getElementById(id))
      .filter(Boolean);
    if (!sections.length) return;

    const obs = new IntersectionObserver(
      (entries) => {
        const visible = entries
          .filter((e) => e.isIntersecting)
          .sort((a, b) => a.boundingClientRect.top - b.boundingClientRect.top);
        if (visible[0]) setActive(visible[0].target.id);
      },
      { rootMargin: '-45% 0px -50% 0px', threshold: 0 },
    );
    sections.forEach((s) => obs.observe(s));
    return () => obs.disconnect();
  }, []);

  const toTop = (e) => {
    e.preventDefault();
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  return (
    <div style={{ position: 'sticky', top: 0, zIndex: 50, padding: '0 16px' }}>
      <nav style={{
        display: 'flex', alignItems: 'center', gap: 28,
        maxWidth: 1100, margin: '12px auto 0',
        padding: '10px 16px', borderRadius: 16,
        background: 'color-mix(in oklch, var(--bg) 72%, transparent)',
        backdropFilter: 'blur(20px) saturate(160%)',
        WebkitBackdropFilter: 'blur(20px) saturate(160%)',
        border: '.5px solid var(--line)',
        boxShadow: '0 8px 30px color-mix(in oklch, var(--bg) 60%, transparent)',
      }}>
        <a href="#top" onClick={toTop} style={{
          display: 'flex', alignItems: 'center', gap: 9, textDecoration: 'none',
        }}>
          <Logo size={45} />
          <span style={{ fontWeight: 600, fontSize: 19, letterSpacing: '-.01em' }}>Shelfire</span>
        </a>
        <div style={{
          display: 'flex', gap: 2, margin: '0 auto',
          padding: 4, borderRadius: 999,
          background: 'color-mix(in oklch, var(--accent) 5%, transparent)',
          border: '.5px solid color-mix(in oklch, var(--accent) 12%, transparent)',
        }}>
          {NAV_LINKS.map((l) => (
            <a
              key={l.id}
              href={`#${l.id}`}
              className={`nav-link${active === l.id ? ' active' : ''}`}
              style={{ fontSize: 13.5, textDecoration: 'none' }}
            >{t(l.key)}</a>
          ))}
        </div>
        <LanguagePicker locale={locale} setLocale={setLocale} ariaLabel={t('nav.language')} />
        <a href="#download" className="nav-cta" style={{
          padding: '7px 14px', borderRadius: 7, background: 'var(--accent)',
          color: 'var(--accent-ink)', fontSize: 13, fontWeight: 600,
          textDecoration: 'none',
        }}>{t('nav.download')}</a>
      </nav>
    </div>
  );
}

function Hero() {
  const { t } = useLandingT();
  return (
    <section style={{
      position: 'relative', padding: '72px 40px 40px',
      overflow: 'hidden',
    }}>
      {/* Ember glow */}
      <div aria-hidden style={{
        position: 'absolute', left: '50%', top: -180, transform: 'translateX(-50%)',
        width: 1100, height: 600, pointerEvents: 'none',
        background: 'radial-gradient(ellipse at center, color-mix(in oklch, var(--accent) 22%, transparent) 0%, transparent 65%)',
        filter: 'blur(20px)',
      }} />
      <div style={{
        position: 'relative', maxWidth: 1240, margin: '0 auto',
        textAlign: 'center',
      }}>
        {/* <div style={{
          display: 'inline-flex', alignItems: 'center', gap: 8,
          padding: '5px 12px', borderRadius: 999,
          border: '.5px solid var(--line)', background: 'var(--surface)',
          fontSize: 12, color: 'var(--mut)', marginBottom: 28,
          fontFamily: 'var(--mono)', letterSpacing: '.02em',
        }}>
          <span style={{ color: 'var(--accent)' }}>●</span>
          v1.0 — cloud save + 6 themes
        </div> */}
        <h1 style={{
          fontFamily: 'var(--serif)', fontWeight: 400,
          fontSize: 'clamp(48px, 7.2vw, 96px)',
          lineHeight: 0.98, letterSpacing: '-.025em',
          margin: 0, textWrap: 'balance',
        }}>
          {t('hero.titleLine1')}<br />
          <em style={{
            fontStyle: 'italic', color: 'var(--accent)',
            fontFamily: 'var(--serif)',
          }}>{t('hero.titleEmphasis')}</em>
        </h1>
        <p style={{
          maxWidth: 600, margin: '24px auto 0', fontSize: 17, lineHeight: 1.5,
          color: 'var(--mut)', textWrap: 'balance',
        }}>
          {t('hero.subtitle')}
        </p>
        <div style={{
          marginTop: 32, display: 'flex', gap: 12, justifyContent: 'center',
          alignItems: 'center', flexWrap: 'wrap',
        }}>
          <a href={getShelfireSite().windowsInstallerUrl} download style={{
            padding: '12px 22px', borderRadius: 9, background: 'var(--accent)',
            color: 'var(--accent-ink)', fontWeight: 600, fontSize: 14,
            textDecoration: 'none', display: 'inline-flex', alignItems: 'center', gap: 8,
          }}>
            <span style={{ fontSize: 12 }}>↓</span> {t('hero.downloadWindows')}
          </a>
          <span style={{
            padding: '12px 18px', borderRadius: 9,
            border: '.5px solid var(--line)', color: 'var(--mut)',
            fontWeight: 500, fontSize: 14,
          }}>
            {t('hero.otherPlatforms')}
          </span>
          <span style={{
            fontSize: 12, color: 'var(--mut)', fontFamily: 'var(--mono)',
            marginLeft: 4,
          }}>{t('hero.free')}</span>
        </div>
      </div>
      {/* App shell screenshot */}
      <div style={{
        position: 'relative', maxWidth: 1180, margin: '64px auto 0',
      }}>
        <img
          src="./img/library.png"
          alt={t('hero.altLibrary')}
          style={{
            width: '100%', display: 'block', borderRadius: 12,
            border: '.5px solid var(--line)',
            boxShadow: '0 30px 80px -20px rgba(0,0,0,.7)',
          }}
        />
      </div>
    </section>
  );
}

function Annotation({ children, style, align = 'left' }) {
  return (
    <div style={{
      position: 'absolute', ...style,
      fontFamily: 'var(--mono)', fontSize: 11, color: 'var(--mut)',
      lineHeight: 1.4, letterSpacing: '.01em',
      display: 'flex', alignItems: 'center', gap: 8,
      flexDirection: align === 'right' ? 'row' : 'row-reverse',
      pointerEvents: 'none',
    }}>
      <span style={{
        width: 6, height: 6, borderRadius: '50%', background: 'var(--accent)',
        flexShrink: 0, boxShadow: '0 0 12px var(--accent)',
      }} />
      <span style={{
        height: 1, width: 28, background: 'var(--line)', flexShrink: 0,
      }} />
      <span style={{ textAlign: align }}>{children}</span>
    </div>
  );
}

// ── Library / scanning ──────────────────────────────────────────────────────

function LibrarySection() {
  const { t } = useLandingT();
  return (
    <SplitSection
      id="library"
      eyebrow={t('library.eyebrow')}
      title={<>{t('library.titleLine1')}<br /><em>{t('library.titleEmphasis')}</em></>}
      body={t('library.body')}
      bullets={[
        { key: 'library.bullet.0' },
        { key: 'library.bullet.1' },
        { key: 'library.bullet.2' },
        { key: 'library.bullet.3' },
      ]}
      visual={
        <img
          src="./img/library.png"
          alt={t('library.altLibrary')}
          style={{
            width: '100%', display: 'block', borderRadius: 10,
            border: '.5px solid var(--line)',
            boxShadow: '0 30px 80px -20px rgba(0,0,0,.7)',
          }}
        />
      }
    />
  );
}

// ── Player ──────────────────────────────────────────────────────────────────

function PlayerSection() {
  const { t } = useLandingT();
  const features = [
    { id: 'resume', title: 'player.feature.resume.title', desc: 'player.feature.resume.desc' },
    { id: 'autoplay', title: 'player.feature.autoplay.title', desc: 'player.feature.autoplay.desc' },
    { id: 'subtitles', title: 'player.feature.subtitles.title', desc: 'player.feature.subtitles.desc' },
    { id: 'audio', title: 'player.feature.audio.title', desc: 'player.feature.audio.desc' },
  ];
  return (
    <section id="player" style={{ padding: '120px 40px' }}>
      <div style={{ maxWidth: 1180, margin: '0 auto' }}>
        <SectionHeader
          eyebrow={t('player.eyebrow')}
          title={<>{t('player.titleBefore')}<em>{t('player.titleEmphasis')}</em></>}
          body={t('player.body')}
        />
        <div style={{ marginTop: 48 }}>
          <img
            src="./img/player.png"
            alt={t('player.altPlayer')}
            style={{
              width: '100%', display: 'block', borderRadius: 12,
              border: '.5px solid var(--line)',
              boxShadow: '0 30px 80px -20px rgba(0,0,0,.7)',
            }}
          />
        </div>
        <div style={{
          marginTop: 40,
          display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 24,
        }}>
          {features.map((f) => (
            <div key={f.id}>
              <div style={{ fontSize: 13.5, fontWeight: 600, marginBottom: 6 }}>{t(f.title)}</div>
              <div style={{ fontSize: 13, lineHeight: 1.5, color: 'var(--mut)' }}>{t(f.desc)}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ── Discovery ───────────────────────────────────────────────────────────────

function DiscoverySection() {
  const { t } = useLandingT();
  return (
    <SplitSection
      reverse
      id="discovery"
      eyebrow={t('discovery.eyebrow')}
      title={<>{t('discovery.titleLine1')}<br /><em>{t('discovery.titleEmphasis')}</em></>}
      body={t('discovery.body')}
      bullets={[
        { key: 'discovery.bullet.0' },
        { key: 'discovery.bullet.1' },
        { key: 'discovery.bullet.2' },
        { key: 'discovery.bullet.3' },
      ]}
      visual={<CatalogMock />}
    />
  );
}

// ── Tracking ────────────────────────────────────────────────────────────────

function TrackingSection() {
  const { t } = useLandingT();
  return (
    <SplitSection
      id="tracking"
      eyebrow={t('tracking.eyebrow')}
      title={<>{t('tracking.titleLine1')}<br /><em>{t('tracking.titleEmphasis')}</em></>}
      body={t('tracking.body')}
      bullets={[
        { key: 'tracking.bullet.0' },
        { key: 'tracking.bullet.1' },
        { key: 'tracking.bullet.2' },
        { key: 'tracking.bullet.3', premium: true },
      ]}
      visual={
        <img
          src="./img/tracker.png"
          alt={t('tracking.altTracker')}
          style={{
            width: '100%', display: 'block', borderRadius: 12,
            border: '.5px solid var(--line)',
            boxShadow: '0 30px 80px -20px rgba(0,0,0,.7)',
          }}
        />
      }
    />
  );
}

// ── Lists & Ratings ─────────────────────────────────────────────────────────

function ListsSection() {
  const { t } = useLandingT();
  return (
    <section id="lists" style={{ padding: '120px 40px' }}>
      <div style={{ maxWidth: 1180, margin: '0 auto' }}>
        <SectionHeader
          eyebrow={t('lists.eyebrow')}
          title={<>{t('lists.titleBefore')}<em>{t('lists.titleEmphasis')}</em></>}
          body={t('lists.body')}
        />
        <div style={{ marginTop: 48 }}>
          <ListsMock />
        </div>
      </div>
    </section>
  );
}

// ── Themes ──────────────────────────────────────────────────────────────────

function ThemesSection() {
  const { t } = useLandingT();
  const themes = [
    { id: 'dark', bg: '#050b14', fg: '#f8fafc', accent: '#3b82f6', line: '#334155', surf: '#0f1a2e' },
    { id: 'black', bg: '#000000', fg: '#f5f5f5', accent: '#3b82f6', line: '#262626', surf: '#141414' },
    { id: 'light', bg: '#f8fafc', fg: '#0f172a', accent: '#2563eb', line: '#e2e8f0', surf: '#ffffff' },
    { id: 'dracula', bg: '#282a36', fg: '#f8f8f2', accent: '#bd93f9', line: '#44475a', surf: '#343746', premium: true },
    { id: 'nord', bg: '#2e3440', fg: '#eceff4', accent: '#88c0d0', line: '#434c5e', surf: '#3b4252', premium: true },
    { id: 'sepia', bg: '#fbf0d9', fg: '#3e2b1b', accent: '#a8742e', line: '#d7bea0', surf: '#fff8e6', premium: true },
  ];
  return (
    <section id="themes" style={{ padding: '120px 40px' }}>
      <div style={{ maxWidth: 1180, margin: '0 auto' }}>
        <SectionHeader
          eyebrow={t('themes.eyebrow')}
          title={<>{t('themes.titleLine1')}<br /><em>{t('themes.titleEmphasis')}</em></>}
          body={t('themes.body')}
        />
        <div style={{
          marginTop: 48,
          display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 18,
        }}>
          {themes.map((theme) => <ThemeCard key={theme.id} theme={theme} />)}
        </div>
      </div>
    </section>
  );
}

function ThemeCard({ theme }) {
  const { t } = useLandingT();
  const name = t(`themes.name.${theme.id}`);
  return (
    <div style={{
      borderRadius: 14, overflow: 'hidden', border: '.5px solid var(--line)',
      background: 'var(--surface)', position: 'relative',
    }}>
      <div style={{
        padding: 14, background: theme.bg, color: theme.fg,
        borderBottom: `.5px solid ${theme.line}`,
      }}>
        <div style={{
          display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12,
        }}>
          <div style={{
            width: 14, height: 14, borderRadius: 4, background: theme.accent,
          }} />
          <div style={{ fontSize: 11, fontWeight: 600 }}>Shelfire</div>
          <div style={{ flex: 1 }} />
          <div style={{ fontSize: 9, opacity: .5, fontFamily: 'var(--mono)' }}>
            {name.toLowerCase()}
          </div>
        </div>
        <div style={{ display: 'flex', gap: 6 }}>
          {[1,2,3,4].map((i) => (
            <div key={i} style={{
              flex: 1, height: 56, borderRadius: 4,
              background: theme.surf, position: 'relative', overflow: 'hidden',
            }}>
              <div style={{
                position: 'absolute', bottom: 0, left: 0, height: 2,
                width: i === 2 ? '60%' : i === 1 ? '100%' : '0%',
                background: theme.accent,
              }} />
            </div>
          ))}
        </div>
        <div style={{
          display: 'flex', gap: 4, marginTop: 10,
        }}>
          {[1,2,3,4,5,6,7].map((i) => (
            <div key={i} style={{
              height: 6, flex: 1, borderRadius: 2,
              background: i <= 5 ? theme.accent : theme.line, opacity: i <= 5 ? .85 : 1,
            }} />
          ))}
        </div>
      </div>
      <div style={{
        padding: '12px 14px', display: 'flex', alignItems: 'center', gap: 10,
      }}>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 13, fontWeight: 600 }}>{name}</div>
          <div style={{ fontSize: 11, color: 'var(--mut)' }}>{t(`themes.desc.${theme.id}`)}</div>
        </div>
        {theme.premium && (
          <div style={{
            padding: '2px 7px', borderRadius: 4, fontSize: 9.5,
            background: 'var(--accent-soft)', color: 'var(--accent)',
            fontWeight: 700, letterSpacing: '.06em', textTransform: 'uppercase',
            fontFamily: 'var(--mono)',
          }}>{t('common.premium')}</div>
        )}
      </div>
    </div>
  );
}

// ── Cloud / Sync ────────────────────────────────────────────────────────────

function CloudSection() {
  const { t } = useLandingT();
  return (
    <section style={{ padding: '120px 40px' }}>
      <div style={{ maxWidth: 1180, margin: '0 auto' }}>
        <div style={{
          borderRadius: 18, padding: '52px 48px',
          background: 'linear-gradient(135deg, color-mix(in oklch, var(--accent) 14%, var(--surface)) 0%, var(--surface) 60%)',
          border: '.5px solid var(--line)',
          display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 56,
          alignItems: 'center',
        }}>
          <div>
            <div style={{
              display: 'flex', alignItems: 'center', gap: 10, marginBottom: 14,
            }}>
              <div style={{
                fontFamily: 'var(--mono)', fontSize: 11, letterSpacing: '.08em',
                textTransform: 'uppercase', color: 'var(--accent)',
              }}>{t('cloud.eyebrow')}</div>
              <div style={{
                padding: '2px 8px', borderRadius: 4, fontSize: 9.5,
                background: 'var(--accent)', color: 'var(--accent-ink)',
                fontWeight: 700, letterSpacing: '.08em', textTransform: 'uppercase',
                fontFamily: 'var(--mono)',
              }}>{t('common.premium')}</div>
            </div>
            <h2 style={{
              fontFamily: 'var(--serif)', fontWeight: 400,
              fontSize: 48, lineHeight: 1.05, letterSpacing: '-.02em',
              margin: 0, textWrap: 'balance',
            }}>
              {t('cloud.titleBefore')}<em style={{ color: 'var(--accent)' }}>{t('cloud.titleEmphasis')}</em>
            </h2>
            <p style={{
              marginTop: 18, fontSize: 15, lineHeight: 1.55, color: 'var(--mut)',
              maxWidth: 460,
            }}>
              {t('cloud.body')}
            </p>
            <div style={{
              marginTop: 26, display: 'flex', gap: 10, alignItems: 'center',
            }}>
              <a href="#" style={{
                padding: '11px 18px', borderRadius: 9,
                background: 'var(--fg)', color: 'var(--bg)',
                fontSize: 13.5, fontWeight: 600, textDecoration: 'none',
                display: 'inline-flex', alignItems: 'center', gap: 10,
              }}>
                <GoogleG /> {t('cloud.signIn')}
              </a>
              <span style={{ fontSize: 12, color: 'var(--mut)', fontFamily: 'var(--mono)' }}>
                {t('cloud.encrypted')}
              </span>
            </div>
          </div>
          <SyncDiagram />
        </div>
      </div>
    </section>
  );
}

function GoogleG() {
  return (
    <svg width="14" height="14" viewBox="0 0 24 24" aria-hidden="true">
      <path fill="#4285F4" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"/>
      <path fill="#34A853" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.99.66-2.25 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"/>
      <path fill="#FBBC05" d="M5.84 14.1c-.22-.66-.35-1.36-.35-2.1s.13-1.44.35-2.1V7.06H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.94l3.66-2.84z"/>
      <path fill="#EA4335" d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.06l3.66 2.84C6.71 7.31 9.14 5.38 12 5.38z"/>
    </svg>
  );
}

const SYNC_DIAGRAM_W = 340;
const SYNC_DIAGRAM_H = 280;
const SYNC_BOX_W = 120;
const SYNC_BOX_H = 60;
const SYNC_CLOUD = { x: SYNC_DIAGRAM_W / 2, y: SYNC_DIAGRAM_H / 2 };

function syncLineAnchor(d) {
  const cx = d.x + SYNC_BOX_W / 2;
  const cy = d.y + SYNC_BOX_H / 2;
  const dx = SYNC_CLOUD.x - cx;
  const dy = SYNC_CLOUD.y - cy;
  const halfW = SYNC_BOX_W / 2;
  const halfH = SYNC_BOX_H / 2;
  const scale = 1 / Math.max(Math.abs(dx) / halfW, Math.abs(dy) / halfH, 1e-6);
  return { x: cx + dx * scale, y: cy + dy * scale };
}

function SyncDiagram() {
  const { t } = useLandingT();
  const devices = [
    { name: 'PC', subKey: 'cloud.device.home', x: 0, y: 0 },
    { name: 'Studio', subKey: 'cloud.device.office', x: 220, y: 30 },
    { name: 'iPad', subKey: 'cloud.device.couch', x: 40, y: 150 },
    { name: 'NUC', subKey: 'cloud.device.livingRoom', x: 240, y: 170 },
  ];
  return (
    <div style={{
      position: 'relative', width: SYNC_DIAGRAM_W, height: SYNC_DIAGRAM_H,
      maxWidth: '100%', margin: '0 auto',
    }}>
      <svg
        viewBox={`0 0 ${SYNC_DIAGRAM_W} ${SYNC_DIAGRAM_H}`}
        style={{ position: 'absolute', inset: 0, width: '100%', height: '100%' }}
        aria-hidden
      >
        {devices.map((d, i) => {
          const anchor = syncLineAnchor(d);
          return (
            <line key={i}
              x1={SYNC_CLOUD.x} y1={SYNC_CLOUD.y}
              x2={anchor.x} y2={anchor.y}
              stroke="var(--line)" strokeDasharray="3 4" />
          );
        })}
      </svg>
      {/* central cloud */}
      <div style={{
        position: 'absolute', left: SYNC_CLOUD.x, top: SYNC_CLOUD.y,
        transform: 'translate(-50%,-50%)',
        width: 96, height: 96, borderRadius: '50%',
        background: 'var(--accent)', display: 'grid', placeItems: 'center',
        boxShadow: '0 0 60px color-mix(in oklch, var(--accent) 50%, transparent)',
        color: 'var(--accent-ink)', fontFamily: 'var(--mono)', fontWeight: 700,
        fontSize: 11, letterSpacing: '.08em', textTransform: 'uppercase',
      }}>
        <div style={{ textAlign: 'center', lineHeight: 1.2 }}>
          Shelfire<br />Cloud
        </div>
      </div>
      {devices.map((d, i) => (
        <div key={i} style={{
          position: 'absolute', left: d.x, top: d.y, width: SYNC_BOX_W, height: SYNC_BOX_H,
          borderRadius: 10, background: 'var(--surface)',
          border: '.5px solid var(--line)',
          padding: '10px 12px', display: 'flex', flexDirection: 'column',
          justifyContent: 'center',
        }}>
          <div style={{ fontSize: 12.5, fontWeight: 600 }}>{d.name}</div>
          <div style={{
            fontSize: 10.5, color: 'var(--mut)', fontFamily: 'var(--mono)',
            display: 'flex', alignItems: 'center', gap: 6, marginTop: 2,
          }}>
            <span style={{
              width: 5, height: 5, borderRadius: '50%', background: 'oklch(0.78 0.14 150)',
            }} />
            {t(d.subKey)} · {t('cloud.synced')}
          </div>
        </div>
      ))}
    </div>
  );
}

function PricingFeature({ strongKey, restKey }) {
  const { t } = useLandingT();
  return (
    <span><strong>{t(strongKey)}</strong>{t(restKey)}</span>
  );
}

// ── Pricing ─────────────────────────────────────────────────────────────────

function PricingSection() {
  const { t } = useLandingT();
  const { windowsInstallerUrl } = getShelfireSite();
  const freeFeatures = [
    { id: '0', type: 'plain', key: 'pricing.free.feature.0' },
    { id: '1', type: 'plain', key: 'pricing.free.feature.1' },
    { id: '2', type: 'plain', key: 'pricing.free.feature.2' },
    { id: '3', type: 'split', strong: 'pricing.free.feature.3.strong', rest: 'pricing.free.feature.3.rest' },
    { id: '4', type: 'plain', key: 'pricing.free.feature.4' },
    { id: '5', type: 'plain', key: 'pricing.free.feature.5' },
  ];
  const premiumFeatures = [
    { id: '0', type: 'plain', key: 'pricing.premium.feature.0' },
    { id: '1', type: 'split', strong: 'pricing.premium.feature.1.strong', rest: 'pricing.premium.feature.1.rest' },
    { id: '2', type: 'split', strong: 'pricing.premium.feature.2.strong', rest: 'pricing.premium.feature.2.rest' },
    { id: '3', type: 'split', strong: 'pricing.premium.feature.3.strong', rest: 'pricing.premium.feature.3.rest' },
  ];
  return (
    <section id="pricing" style={{ padding: '120px 40px' }}>
      <div style={{ maxWidth: 1080, margin: '0 auto' }}>
        <SectionHeader
          eyebrow={t('pricing.eyebrow')}
          title={<>{t('pricing.titleBefore')}<em>{t('pricing.titleEmphasis')}</em></>}
          body={t('pricing.body')}
          center
        />
        <div style={{
          marginTop: 56,
          display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 18,
        }}>
          {/* Free */}
          <div style={{
            borderRadius: 16, padding: '32px 30px',
            border: '.5px solid var(--line)', background: 'var(--surface)',
            display: 'flex', flexDirection: 'column',
          }}>
            <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 6 }}>Shelfire</div>
            <div style={{ fontSize: 12, color: 'var(--mut)', marginBottom: 22 }}>
              {t('pricing.free.tagline')}
            </div>
            <div style={{
              fontFamily: 'var(--serif)', fontSize: 52, lineHeight: 1,
              fontWeight: 400, letterSpacing: '-.02em', marginBottom: 4,
            }}>$0</div>
            <div style={{
              fontSize: 12, color: 'var(--mut)', fontFamily: 'var(--mono)', marginBottom: 24,
            }}>{t('pricing.free.priceNote')}</div>
            <ul style={{
              listStyle: 'none', padding: 0, margin: '0 0 28px',
              display: 'grid', gap: 9, fontSize: 13,
            }}>
              {freeFeatures.map((f) => (
                <li key={f.id} style={{ display: 'flex', gap: 10 }}>
                  <span style={{ color: 'var(--accent)' }}>✓</span>
                  <span>
                    {f.type === 'split'
                      ? <PricingFeature strongKey={f.strong} restKey={f.rest} />
                      : t(f.key)}
                  </span>
                </li>
              ))}
            </ul>
            <a href={windowsInstallerUrl} download style={{
              marginTop: 'auto', textAlign: 'center',
              padding: '11px 18px', borderRadius: 9,
              border: '.5px solid var(--line)', color: 'var(--fg)',
              fontWeight: 600, fontSize: 13.5, textDecoration: 'none',
            }}>{t('pricing.free.cta')}</a>
          </div>
          {/* Premium */}
          <div style={{
            borderRadius: 16, padding: '32px 30px', position: 'relative',
            background: 'linear-gradient(160deg, color-mix(in oklch, var(--accent) 18%, var(--surface)) 0%, var(--surface) 70%)',
            border: '.5px solid color-mix(in oklch, var(--accent) 40%, var(--line))',
            display: 'flex', flexDirection: 'column',
          }}>
            <div style={{
              position: 'absolute', top: 20, right: 22,
              padding: '3px 9px', borderRadius: 999, fontSize: 10,
              background: 'var(--accent)', color: 'var(--accent-ink)',
              fontWeight: 700, letterSpacing: '.06em', textTransform: 'uppercase',
              fontFamily: 'var(--mono)',
            }}>{t('pricing.premium.badge')}</div>
            <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 6 }}>Shelfire Premium</div>
            <div style={{ fontSize: 12, color: 'var(--mut)', marginBottom: 22 }} />
            <div style={{
              display: 'flex', alignItems: 'baseline', gap: 6, marginBottom: 4,
            }}>
              <span style={{
                fontFamily: 'var(--serif)', fontSize: 52, lineHeight: 1,
                fontWeight: 400, letterSpacing: '-.02em',
              }}>$3</span>
              <span style={{ fontSize: 14, color: 'var(--mut)' }}>{t('pricing.premium.perMonth')}</span>
            </div>
            <div
              aria-hidden="true"
              style={{
                fontSize: 12, fontFamily: 'var(--mono)', marginBottom: 24,
                minHeight: '1.2em',
              }}
            />
            <ul style={{
              listStyle: 'none', padding: 0, margin: '0 0 28px',
              display: 'grid', gap: 9, fontSize: 13,
            }}>
              {premiumFeatures.map((f) => (
                <li key={f.id} style={{ display: 'flex', gap: 10 }}>
                  <span style={{ color: 'var(--accent)' }}>✓</span>
                  <span>
                    {f.type === 'split'
                      ? <PricingFeature strongKey={f.strong} restKey={f.rest} />
                      : t(f.key)}
                  </span>
                </li>
              ))}
            </ul>
            <a href="#" style={{
              marginTop: 'auto', textAlign: 'center',
              padding: '11px 18px', borderRadius: 9,
              background: 'var(--accent)', color: 'var(--accent-ink)',
              fontWeight: 600, fontSize: 13.5, textDecoration: 'none',
            }}>{t('pricing.premium.cta')}</a>
          </div>
        </div>
      </div>
    </section>
  );
}

// ── Footer / CTA ────────────────────────────────────────────────────────────

function Footer() {
  const { t } = useLandingT();
  const { windowsInstallerUrl, version } = getShelfireSite();
  const platforms = [
    { id: 'windows', os: 'Windows', subKey: 'footer.installer', active: true },
    { id: 'macos', os: 'macOS', subKey: 'footer.comingSoon', active: false },
    { id: 'linux', os: 'Linux', subKey: 'footer.comingSoon', active: false },
  ];
  return (
    <footer id="download" style={{
      borderTop: '.5px solid var(--line)',
      padding: '100px 40px 40px', position: 'relative', overflow: 'hidden',
    }}>
      <div aria-hidden style={{
        position: 'absolute', left: '50%', top: '-30%', transform: 'translateX(-50%)',
        width: 900, height: 600, pointerEvents: 'none',
        background: 'radial-gradient(ellipse at center, color-mix(in oklch, var(--accent) 18%, transparent) 0%, transparent 65%)',
        filter: 'blur(20px)',
      }} />
      <div style={{
        position: 'relative', maxWidth: 1080, margin: '0 auto', textAlign: 'center',
      }}>
        <h2 style={{
          fontFamily: 'var(--serif)', fontWeight: 400,
          fontSize: 'clamp(40px, 5vw, 64px)', lineHeight: 1.0,
          letterSpacing: '-.025em', margin: 0,
        }}>
          {t('footer.titleBefore')}<em style={{ color: 'var(--accent)' }}>{t('footer.titleEmphasis')}</em>
        </h2>
        <p style={{
          marginTop: 18, fontSize: 15, lineHeight: 1.5, color: 'var(--mut)',
          maxWidth: 460, margin: '18px auto 0',
        }}>
          {t('footer.subtitle')}
        </p>
        <div style={{
          marginTop: 32, display: 'inline-flex', gap: 10, padding: 6,
          background: 'var(--surface)', border: '.5px solid var(--line)',
          borderRadius: 12,
        }}>
          {platforms.map(({ id, os, subKey, active }) => (
            <a key={id} href={active ? windowsInstallerUrl : undefined} download={active || undefined} style={{
              padding: '12px 20px', borderRadius: 8, minWidth: 150,
              background: active ? 'var(--accent)' : 'transparent',
              color: active ? 'var(--accent-ink)' : 'var(--mut)',
              textDecoration: 'none', display: 'flex', flexDirection: 'column',
              alignItems: 'flex-start',
              cursor: active ? 'pointer' : 'default',
              pointerEvents: active ? 'auto' : 'none',
            }}>
              <span style={{ fontWeight: 600, fontSize: 14 }}>{os}</span>
              <span style={{
                fontSize: 10.5, fontFamily: 'var(--mono)',
                opacity: active ? .8 : .55,
              }}>{t(subKey)}</span>
            </a>
          ))}
        </div>
      </div>
      <div style={{
        position: 'relative', maxWidth: 1180, margin: '100px auto 0',
        paddingTop: 30, borderTop: '.5px solid var(--line)',
        display: 'flex', alignItems: 'center', gap: 16,
        fontSize: 12, color: 'var(--mut)',
      }}>
        <div style={{ marginLeft: 'auto', marginRight: 'auto', display: 'flex', alignItems: 'center', gap: 8 }}>
          <Logo size={16} />
          <span style={{ fontWeight: 600, color: 'var(--fg)' }}>Shelfire</span>
          <span style={{ fontFamily: 'var(--mono)' }}>v{version}</span>
        </div>
        {/* <div style={{ display: 'flex', gap: 20, marginLeft: 24 }}>
          <a href="#" style={{ color: 'var(--mut)', textDecoration: 'none' }}>Privacy</a>
          <a href="#" style={{ color: 'var(--mut)', textDecoration: 'none' }}>Terms</a>
          <a href="#support" style={{ color: 'var(--mut)', textDecoration: 'none' }}>Support</a>
          <a href="#" style={{ color: 'var(--mut)', textDecoration: 'none' }}>Changelog</a>
          <a href="#" style={{ color: 'var(--mut)', textDecoration: 'none' }}>GitHub</a>
        </div> */}
        {/* <div style={{ marginLeft: 'auto', fontFamily: 'var(--mono)' }}>
          Built quietly in Lisboa
        </div> */}
      </div>
    </footer>
  );
}

// ── Support ─────────────────────────────────────────────────────────────────

function SupportSection() {
  const { t } = useLandingT();
  const [email, setEmail] = React.useState('');
  const [subject, setSubject] = React.useState('');
  const [message, setMessage] = React.useState('');
  const [status, setStatus] = React.useState('idle'); // idle | sending | sent | error
  const [error, setError] = React.useState('');

  const emailOk = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.trim());
  const canSend = emailOk && subject.trim() && message.trim() && status !== 'sending';

  const submit = async (e) => {
    e.preventDefault();
    if (!canSend) return;
    setStatus('sending');
    setError('');
    try {
      const supportApiBase = getShelfireSite().supportApiBase.replace(/\/$/, '');
      const resp = await fetch(`${supportApiBase}/support/report`, {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({
          category: 'suggestion',
          title: subject.trim(),
          description: message.trim(),
          contactEmail: email.trim(),
          details: {},
          metadata: {
            build: 'website',
            appVersion: '',
            browserLanguage: navigator.language || '',
            platform: navigator.platform || '',
            userAgent: navigator.userAgent || '',
            timestamp: new Date().toISOString(),
          },
        }),
      });
      if (!resp.ok) {
        const data = await resp.json().catch(() => ({}));
        throw new Error(data.error || `Request failed (${resp.status})`);
      }
      setStatus('sent');
      setEmail(''); setSubject(''); setMessage('');
    } catch (err) {
      setError(err && err.message ? err.message : String(err));
      setStatus('error');
    }
  };

  const field = {
    width: '100%', padding: '11px 13px', borderRadius: 9,
    border: '.5px solid var(--line)', background: 'var(--bg)',
    color: 'var(--fg)', fontSize: 14, fontFamily: 'var(--sans)',
    outline: 'none', boxSizing: 'border-box',
  };
  const label = {
    display: 'block', fontSize: 11, fontFamily: 'var(--mono)',
    letterSpacing: '.04em', textTransform: 'uppercase',
    color: 'var(--mut)', marginBottom: 7,
  };

  return (
    <section id="support" style={{ padding: '120px 40px' }}>
      <div style={{ maxWidth: 1080, margin: '0 auto' }}>
        <SectionHeader
          eyebrow={t('support.eyebrow')}
          title={<>{t('support.titleBefore')}<em>{t('support.titleEmphasis')}</em></>}
          body={t('support.body')}
          center
        />
        <div style={{
          marginTop: 56,
          display: 'grid', gridTemplateColumns: '0.8fr 1.2fr', gap: 18,
          alignItems: 'stretch',
        }}>
          {/* Contact email card */}
          <div style={{
            borderRadius: 16, padding: '32px 30px',
            border: '.5px solid var(--line)', background: 'var(--surface)',
            display: 'flex', flexDirection: 'column',
          }}>
            <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 6 }}>{t('support.email.title')}</div>
            <div style={{ fontSize: 13, color: 'var(--mut)', lineHeight: 1.55, marginBottom: 22 }}>
              {t('support.email.body')}
            </div>
            <a href="mailto:support@shelfire.com" style={{
              marginTop: 'auto', textAlign: 'center',
              padding: '11px 18px', borderRadius: 9,
              border: '.5px solid var(--line)', color: 'var(--fg)',
              fontWeight: 600, fontSize: 13.5, textDecoration: 'none',
              fontFamily: 'var(--mono)',
            }}>support@shelfire.com</a>
          </div>
          {/* Contact form */}
          <form onSubmit={submit} style={{
            borderRadius: 16, padding: '32px 30px',
            background: 'linear-gradient(160deg, color-mix(in oklch, var(--accent) 12%, var(--surface)) 0%, var(--surface) 70%)',
            border: '.5px solid color-mix(in oklch, var(--accent) 30%, var(--line))',
            display: 'flex', flexDirection: 'column', gap: 16,
          }}>
            <div>
              <label htmlFor="sup-email" style={label}>{t('support.form.email')}</label>
              <input id="sup-email" type="email" required value={email}
                onChange={(e) => { setEmail(e.target.value); setStatus('idle'); }}
                placeholder={t('support.form.placeholder.email')} style={field} />
            </div>
            <div>
              <label htmlFor="sup-subject" style={label}>{t('support.form.subject')}</label>
              <input id="sup-subject" type="text" required value={subject}
                onChange={(e) => { setSubject(e.target.value); setStatus('idle'); }}
                placeholder={t('support.form.placeholder.subject')} style={field} />
            </div>
            <div>
              <label htmlFor="sup-message" style={label}>{t('support.form.message')}</label>
              <textarea id="sup-message" required value={message} rows={5}
                onChange={(e) => { setMessage(e.target.value); setStatus('idle'); }}
                placeholder={t('support.form.placeholder.message')}
                style={{ ...field, resize: 'vertical', lineHeight: 1.5 }} />
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
              <button type="submit" disabled={!canSend} style={{
                padding: '11px 20px', borderRadius: 9, border: 'none',
                background: 'var(--accent)', color: 'var(--accent-ink)',
                fontWeight: 600, fontSize: 13.5, fontFamily: 'var(--sans)',
                cursor: canSend ? 'pointer' : 'not-allowed',
                opacity: canSend ? 1 : 0.5,
              }}>{status === 'sending' ? t('support.form.sending') : t('support.form.send')}</button>
              {status === 'sent' && (
                <span style={{ fontSize: 13, color: 'oklch(0.78 0.14 150)' }}>
                  {t('support.form.sent')}
                </span>
              )}
              {status === 'error' && (
                <span style={{ fontSize: 13, color: 'oklch(0.7 0.18 25)' }}>{error}</span>
              )}
            </div>
          </form>
        </div>
      </div>
    </section>
  );
}

// ── Layout helpers ──────────────────────────────────────────────────────────

function SectionHeader({ eyebrow, title, body, center }) {
  return (
    <div style={{
      textAlign: center ? 'center' : 'left',
      maxWidth: center ? 720 : 720, margin: center ? '0 auto' : 0,
    }}>
      <div style={{
        fontFamily: 'var(--mono)', fontSize: 11, letterSpacing: '.1em',
        textTransform: 'uppercase', color: 'var(--accent)', marginBottom: 14,
      }}>{eyebrow}</div>
      <h2 style={{
        fontFamily: 'var(--serif)', fontWeight: 400,
        fontSize: 'clamp(38px, 4vw, 56px)', lineHeight: 1.04,
        letterSpacing: '-.02em', margin: 0, textWrap: 'balance',
      }}>{title}</h2>
      <p style={{
        marginTop: 18, fontSize: 15, lineHeight: 1.55, color: 'var(--mut)',
        maxWidth: 540, marginLeft: center ? 'auto' : 0,
        marginRight: center ? 'auto' : 0,
        textWrap: 'pretty',
      }}>{body}</p>
    </div>
  );
}

function SplitSection({ id, eyebrow, title, body, bullets, visual, reverse }) {
  const { t } = useLandingT();
  return (
    <section id={id} style={{ padding: '120px 40px' }}>
      <div style={{
        maxWidth: 1180, margin: '0 auto',
        display: 'grid', gridTemplateColumns: '1fr 1.15fr', gap: 64,
        alignItems: 'center',
        direction: reverse ? 'rtl' : 'ltr',
      }}>
        <div style={{ direction: 'ltr' }}>
          <div style={{
            fontFamily: 'var(--mono)', fontSize: 11, letterSpacing: '.1em',
            textTransform: 'uppercase', color: 'var(--accent)', marginBottom: 14,
          }}>{eyebrow}</div>
          <h2 style={{
            fontFamily: 'var(--serif)', fontWeight: 400,
            fontSize: 'clamp(36px, 3.8vw, 52px)', lineHeight: 1.04,
            letterSpacing: '-.02em', margin: 0, textWrap: 'balance',
          }}>{title}</h2>
          <p style={{
            marginTop: 18, fontSize: 15, lineHeight: 1.55, color: 'var(--mut)',
            maxWidth: 460, textWrap: 'pretty',
          }}>{body}</p>
          <ul style={{
            listStyle: 'none', padding: 0, margin: '24px 0 0',
            display: 'grid', gap: 11, fontSize: 13.5,
          }}>
            {bullets.map((b) => (
              <li key={b.key} style={{ display: 'flex', gap: 12, alignItems: 'baseline' }}>
                <span style={{
                  color: 'var(--accent)', fontFamily: 'var(--mono)', fontSize: 11,
                }}>→</span>
                <span>
                  {t(b.key)}
                  {b.premium && <PremiumBadge />}
                </span>
              </li>
            ))}
          </ul>
        </div>
        <div style={{ direction: 'ltr' }}>{visual}</div>
      </div>
    </section>
  );
}

Object.assign(window, {
  Nav, Hero, LibrarySection, PlayerSection, DiscoverySection,
  TrackingSection, ListsSection, ThemesSection, CloudSection,
  PricingSection, SupportSection, Footer,
});
