/* global React, Icon, AlbumCover, CATALOG, WaveBars, AILabel */
const { useState, useEffect, useMemo } = React;

// ---------- Static info-page registry ----------
const PAGES = {
  'how': {
    title: 'How Lyrithm works',
    kicker: 'Behind the decode',
    intro: 'A short tour of how a Lyrithm meaning page is built — what\'s a human, what\'s a model, and where the line is drawn.',
    sections: [
      { h: 'Step 1 · Lyrics ingestion', p: 'We index lyrics from licensed sources first, and from artist submissions where available. Where lyrics aren\'t licensed, we tell you on the page — we never claim "official" we haven\'t earned.' },
      { h: 'Step 2 · Whole-song summary', p: 'A large language model produces the 2–3 sentence summary at the top of every song page. Each summary carries an "AI-assisted interpretation" label. We display it first because that\'s what a searcher is actually looking for.' },
      { h: 'Step 3 · Line-by-line decode', p: 'The same model produces a meaning for each line, with two depths — Quick (one sentence) and Deep (themes, devices, references). Lines stay in the original language; only the interpretation translates.' },
      { h: 'Step 4 · Human signal', p: 'Every meaning has a quiet feedback bar. Helpful/Not-helpful votes and suggested rewrites feed back into our prompts and a human review queue. No leaderboards, no points — just signal.' },
      { h: 'Step 5 · Translation', p: 'Translations are authored multilingual from the same interpretation pass, not machine-translated leftovers. EN, ID, ES today; PT, FR, JP rolling out; more on the way.' },
    ],
  },
  'meaning-vs-lyrics': {
    title: 'Meaning vs. lyrics',
    kicker: 'Why we lead with meaning',
    intro: 'Most lyrics sites bury the answer. The thing a listener actually wants — what is this song about? — is the first paragraph on every Lyrithm page, not the twentieth.',
    sections: [
      { h: 'Genius UX (≈2014–2024)', p: 'Lyrics first, annotations behind hover-states, ads everywhere. Meaning was stitched together from forum comments. It worked when the web was small and the only competition was annotated PDFs.' },
      { h: 'Lyrithm UX (2026+)', p: 'Summary first. Then lyrics + line meanings, side-by-side, clearly labeled. No ads inside the lyric flow. The format is designed for the way people actually search now: "[song] lyrics meaning", "arti lirik [lagu]".' },
      { h: 'What we don\'t do', p: 'We don\'t fake star ratings, invent aggregate scores, or claim licensed lyrics we haven\'t licensed. Honesty is the moat.' },
    ],
  },
  'multilingual': {
    title: 'Built for multilingual fans',
    kicker: 'Every language, same care',
    intro: 'A listener in Jakarta should get the same thoughtful read as one in Brooklyn. Lyrithm authors meanings multilingual — not machine-translated.',
    sections: [
      { h: 'Today', p: 'English, Bahasa Indonesia, Spanish. PT, FR, and Japanese rolling out next.' },
      { h: 'Coming soon', p: 'Korean, Arabic, Vietnamese, Thai, Tagalog, Hindi. Reach out if you want to help author meanings in a language we don\'t cover yet.' },
      { h: 'How translation works', p: 'Each meaning is generated once per language from the same interpretation pass. Lyrics stay in the original. The interpretation translates — not the song.' },
    ],
  },
  'compare-genius': {
    title: 'Compare to Genius',
    kicker: 'An honest side-by-side',
    intro: 'Genius has lyrics, scale, and a community. Lyrithm has speed, AI-native meaning, multilingual depth, and a calmer reading experience. Here\'s how that breaks down.',
    sections: [
      { h: 'Where Genius is strong', p: 'Licensed lyrics, deep community annotations on flagship songs, a decade of momentum. We aren\'t pretending otherwise.' },
      { h: 'Where Lyrithm is strong', p: 'Instant whole-song meaning, line-by-line decode with depth control, true multilingual coverage, ad-light reading, honest AI labeling.' },
      { h: 'The wedge', p: 'Lyrithm is the lyrics-meaning engine. If you came from a search for "what does this song mean," we\'re a better destination.' },
    ],
  },
  'extension': {
    title: 'Browser extension',
    kicker: 'Decode anywhere you listen',
    intro: 'Highlight a lyric on any music app, hit the keyboard shortcut, and get the Lyrithm decode — no copy-paste, no tab-hopping.',
    sections: [
      { h: 'For Chrome & Firefox', p: 'Free, MV3, no analytics by default. Ships next month — drop your email below if you want the beta.' },
      { h: 'How it works', p: 'Highlight any text on a supported page (Spotify, Apple Music, YouTube Music, Genius). Press ⌘⇧L. A small Lyrithm panel slides in with the meaning.' },
    ],
  },
  'api': {
    title: 'API for builders',
    kicker: 'Embed the decode',
    intro: 'Lyrithm exposes a clean read API for meaning summaries, line decodes, and translations. Designed for radio apps, music education, and AI-native players.',
    sections: [
      { h: 'Endpoints (preview)', p: 'GET /v1/song/{id}/summary · GET /v1/song/{id}/lines · GET /v1/translations/{lang}. JSON, rate-limited, free tier 10k req/mo.' },
      { h: 'Pricing', p: 'Free for hobbyists & students. Pro plan billed monthly per million reads, fair-use enforced.' },
      { h: 'Get an API key', p: 'Email api@lyrithm.com or join the waitlist. We\'re onboarding the first cohort in Q3 2026.' },
    ],
  },
  'about': {
    title: 'About Lyrithm',
    kicker: 'The team & the thesis',
    intro: 'A small team in Singapore and Jakarta building the lyrics destination for the AI-native internet. Hi.',
    sections: [
      { h: 'Why we\'re building this', p: 'Lyrics sites haven\'t evolved in a decade. The way people search for songs has. Lyrithm closes that gap.' },
      { h: 'Where we are', p: 'Twelve people across four time zones. We hire writers, ML engineers, and frontend designers who care about typography.' },
      { h: 'Where to find us', p: 'hello@lyrithm.com · We answer every email.' },
    ],
  },
  'standards': {
    title: 'Editorial standards',
    kicker: 'How we write meanings',
    intro: 'Every meaning on Lyrithm — model-generated or human-authored — is held to the same standard.',
    sections: [
      { h: 'Voice', p: 'Plain language, no jargon, no purple prose. A friend explaining the song over coffee.' },
      { h: 'Honesty', p: 'If the interpretation is speculative, we say so. We never assert biographical claims we can\'t source.' },
      { h: 'AI disclosure', p: 'Anything model-generated carries the "AI-assisted interpretation" label, visible inline — never hidden in a footer.' },
      { h: 'Corrections', p: 'Every meaning has a "Suggest a better interpretation" link that opens a private review queue. A human reads every submission.' },
    ],
  },
  'honesty': {
    title: 'AI honesty policy',
    kicker: 'The rules we hold ourselves to',
    intro: 'Lyrithm is AI-native. That makes honesty about what\'s a model, what\'s a human, and what\'s a guess non-negotiable.',
    sections: [
      { h: 'Labeling', p: 'Every model-generated interpretation is labeled "AI-assisted interpretation" inline. No exceptions.' },
      { h: 'No fake stats', p: 'We don\'t invent star ratings, aggregateRating, or play counts we can\'t verify. Empty cells are honest cells.' },
      { h: 'No false claims', p: 'We don\'t claim "official lyrics" where they aren\'t licensed. We say so explicitly on the page.' },
      { h: 'Auditability', p: 'Each meaning carries a version string (e.g. "interpretation v2.4"). Older versions are retrievable for transparency.' },
    ],
  },
  'careers': {
    title: 'Careers',
    kicker: 'Open roles',
    intro: 'We\'re hiring across writing, ML, and frontend. Remote-friendly, async-first, ridiculously good taste required.',
    sections: [
      { h: 'Senior writer · Bahasa Indonesia', p: 'Author meaning pages and edit the human review queue for ID-language songs. Full-time, remote, Jakarta or Bandung preferred.' },
      { h: 'ML engineer · interpretation', p: 'Own the prompts and the eval suite for our decode engine. PyTorch, vLLM, evals. Singapore or remote.' },
      { h: 'Frontend designer-engineer', p: 'You\'re reading the kind of work we do. Tailwind, React, opinions about kerning. Singapore or remote.' },
    ],
  },
  'press': {
    title: 'Press',
    kicker: 'For journalists & analysts',
    intro: 'Coverage, brand assets, and an open line. press@lyrithm.com — we typically reply within a day.',
    sections: [
      { h: 'Brand assets', p: 'Logo lockups (light/dark), product screenshots, founder photos. Available on request.' },
      { h: 'Recent coverage', p: 'Coverage in TechInAsia, Rest of World, and Pitchfork\'s "Tools" issue. Full press kit on request.' },
      { h: 'Spokespeople', p: 'Available for interviews on AI-native consumer products, multilingual UX, and the lyrics-search landscape.' },
    ],
  },
  'contact': {
    title: 'Contact',
    kicker: 'We answer every email',
    intro: 'Small team, real inbox. Choose the address that fits and we\'ll route from there.',
    sections: [
      { h: 'General', p: 'hello@lyrithm.com — for anything.' },
      { h: 'Press', p: 'press@lyrithm.com — interviews, coverage, brand assets.' },
      { h: 'API & builders', p: 'api@lyrithm.com — partnerships and integration help.' },
      { h: 'Artist & label requests', p: 'artists@lyrithm.com — submissions, takedowns, verified artist setup.' },
    ],
  },
  'submit': {
    title: 'Lyric submission',
    kicker: 'Send us a song',
    intro: 'Missing a song? Send the lyrics + a Spotify/Apple Music link and we\'ll add it to the queue.',
    sections: [
      { h: 'What to include', p: 'Song title, artist, album, release year, language, and the full lyrics. A streaming link helps us verify.' },
      { h: 'How fast', p: 'Trending songs go live within a day. Long-tail songs within a week. We\'ll email you when it\'s published.' },
      { h: 'Submit', p: 'Mail submit@lyrithm.com or use the in-app form (coming soon).' },
    ],
  },
  'artist-tools': {
    title: 'For artists',
    kicker: 'Tools for the people who wrote the song',
    intro: 'A verified artist can correct lyrics, add a one-paragraph artist note, and respond inline on their own pages. No blue checks for sale.',
    sections: [
      { h: 'Verification', p: 'Email from your label or management address, or a DM from a verified social account. Free, manual review.' },
      { h: 'What you get', p: 'Inline replies on any line of your own songs, a quiet "from the artist" label, edit suggestions go straight to your inbox.' },
      { h: 'What you don\'t get', p: 'A way to delete unflattering interpretations. We won\'t do that.' },
    ],
  },
  'help': {
    title: 'Help center',
    kicker: 'FAQs',
    intro: 'Short answers to the questions we get most.',
    sections: [
      { h: 'Why no star ratings?', p: 'Because we won\'t fake them, and aggregating real ones is not a useful signal for "what does this song mean."' },
      { h: 'How accurate are the meanings?', p: 'Pretty good for songs with clear narrative. Less reliable for abstract or experimental writing — where we err on the side of "this is one possible reading."' },
      { h: 'Why can\'t I save without an account?', p: 'You can. Saved songs live on your device by default. Accounts are coming later for cross-device sync.' },
      { h: 'How do I report bad content?', p: 'Every meaning has a Report link. A human reviews within 24 hours.' },
    ],
  },
  'privacy': {
    title: 'Privacy',
    kicker: 'What we collect, what we don\'t',
    intro: 'Short version: we collect what we need to make the site work, and nothing else. Long version below.',
    sections: [
      { h: 'What we collect', p: 'Anonymized search queries, page views, and crash logs. That\'s it for visitors. If you create an account later, your email.' },
      { h: 'What we don\'t', p: 'No third-party ad pixels, no cross-site tracking, no selling of usage data. Ever.' },
      { h: 'Your data', p: 'Saved songs live on your device. Recent searches are local. If we add accounts, you\'ll be able to export and delete everything in one click.' },
    ],
  },
  'terms': {
    title: 'Terms of service',
    kicker: 'The agreement',
    intro: 'Use Lyrithm in good faith. We\'ll do the same.',
    sections: [
      { h: 'Acceptable use', p: 'Read, save, and share to your heart\'s content. Don\'t scrape the whole site or impersonate other users.' },
      { h: 'AI content', p: 'Meaning text is generated by models with human review. Don\'t pass it off as written by a specific human.' },
      { h: 'Liability', p: 'Standard "as-is" terms. We work hard to be accurate; we can\'t promise the universe.' },
    ],
  },
  'status': {
    title: 'Status',
    kicker: 'Live system health',
    intro: 'All systems are normal.',
    sections: [
      { h: 'Search', p: 'Operational · last incident 17 days ago' },
      { h: 'Decode engine', p: 'Operational · p95 latency 420ms' },
      { h: 'Translations', p: 'Operational · all 6 languages green' },
      { h: 'API', p: 'Operational · uptime 99.97% past 90 days' },
    ],
  },
  'sitemap': {
    title: 'Sitemap',
    kicker: 'Find anything',
    intro: 'The whole site, on one page.',
    sections: [
      { h: 'Browse', p: 'Trending · Saved · By artist · By genre · By language · By era · By mood · New this week' },
      { h: 'Product', p: 'How it works · Meaning vs. lyrics · Multilingual · Compare to Genius · Browser extension · API' },
      { h: 'Company', p: 'About · Editorial standards · AI honesty policy · Careers · Press · Contact' },
      { h: 'Resources', p: 'Help · Lyric submission · For artists · Status · Privacy · Terms' },
    ],
  },
};

// ---------- Browse-by pages (artist/genre/language/era/mood + new) ----------
const BROWSE = {
  artist: {
    title: 'Browse by artist',
    kicker: 'Catalog',
    intro: 'Songs grouped by the artist who wrote them.',
    groupBy: (s) => s.a,
  },
  genre: {
    title: 'Browse by genre',
    kicker: 'Catalog',
    intro: 'Indie pop, dream pop, synthwave, R&B, folk and more.',
    groupBy: (s) => s.g,
  },
  language: {
    title: 'Browse by language',
    kicker: 'Catalog',
    intro: 'Songs in every language we cover.',
    groupBy: (s) => ({ EN: 'English', ID: 'Bahasa Indonesia', ES: 'Español' }[s.lang] || s.lang),
  },
  era: {
    title: 'Browse by era',
    kicker: 'Catalog',
    intro: 'When was this song written? Filter by decade.',
    groupBy: () => '2020s',
  },
  mood: {
    title: 'Browse by mood',
    kicker: 'Catalog',
    intro: 'Wistful, ecstatic, restless, tender. The vibe filter.',
    groupBy: (s) => ['Wistful', 'Tender', 'Restless', 'Hopeful'][s.seed % 4],
  },
  new: {
    title: 'New this week',
    kicker: 'Just added',
    intro: 'Fresh meanings, just landed.',
    groupBy: () => 'This week',
  },
};

// ---------- Generic info page ----------
function InfoPage({ slug, lang = 'EN' }) {
  // Try localized page first, fall back to EN canonical from PAGES.
  const localized = window.PAGES_I18N && window.PAGES_I18N[lang] && window.PAGES_I18N[lang][slug];
  const page = localized || PAGES[slug] || { title: 'Page', kicker: 'Lyrithm', intro: 'This page is being written.', sections: [] };
  return (
    <main id="main">
      <section className="relative pt-12 md:pt-20 pb-8 md:pb-12 overflow-hidden">
        <div aria-hidden="true" className="absolute inset-x-0 top-0 h-[70%] bg-[radial-gradient(ellipse_at_top,rgba(124,92,255,0.14),transparent_60%)]"/>
        <div className="relative max-w-3xl mx-auto px-5 md:px-8">
          <nav className="text-xs text-ink-400 mb-6 flex items-center gap-2" aria-label="Breadcrumb">
            <a href="#/" className="hover:text-ink-200">{window.t('common.home', lang)}</a>
            <span className="text-ink-600">/</span>
            <span className="text-ink-300">{page.title}</span>
          </nav>
          <div className="text-[11px] font-mono uppercase tracking-[0.22em] text-accent-300">{page.kicker}</div>
          <h1 className="mt-3 font-display text-4xl md:text-6xl font-semibold tracking-tight text-ink-100 text-balance">{page.title}</h1>
          <p className="mt-5 text-ink-300 text-base md:text-xl leading-relaxed text-balance">{page.intro}</p>
        </div>
      </section>
      <section className="max-w-3xl mx-auto px-5 md:px-8 mb-20">
        <div className="rounded-3xl border border-ink-700 bg-ink-850 divide-y divide-ink-800">
          {page.sections.map((s, i) => (
            <div key={i} className="p-6 md:p-8">
              <h2 className="font-display text-lg md:text-xl font-semibold text-ink-100">{s.h}</h2>
              <p className="mt-2 text-[15px] md:text-base text-ink-300 leading-relaxed">{s.p}</p>
            </div>
          ))}
        </div>
        {!localized && lang !== 'EN' && (
          <p className="mt-6 text-xs text-ink-400 italic">
            — {window.t('aiLabel', lang)} · {LANGS.find(l => l.code === lang)?.name} —
          </p>
        )}
      </section>
    </main>
  );
}

// ---------- Browse page ----------
function BrowsePage({ slug, lang = 'EN' }) {
  const cfg = BROWSE[slug] || BROWSE.artist;
  const groups = useMemo(() => {
    const g = {};
    CATALOG.forEach(s => {
      const k = cfg.groupBy(s);
      (g[k] = g[k] || []).push(s);
    });
    return Object.entries(g);
  }, [slug]);

  // Localized hero copy for browse subpages
  const LBL = (window.FOOTER_LINKS_I18N && (window.FOOTER_LINKS_I18N[lang] || window.FOOTER_LINKS_I18N.EN)) || {};
  const title = LBL['browse/' + slug] || cfg.title;

  return (
    <main id="main">
      <section className="relative pt-12 md:pt-20 pb-8 md:pb-12 overflow-hidden">
        <div aria-hidden="true" className="absolute inset-x-0 top-0 h-[70%] bg-[radial-gradient(ellipse_at_top,rgba(124,92,255,0.14),transparent_60%)]"/>
        <div className="relative max-w-7xl mx-auto px-5 md:px-8">
          <nav className="text-xs text-ink-400 mb-6 flex items-center gap-2" aria-label="Breadcrumb">
            <a href="#/" className="hover:text-ink-200">{window.t('common.home', lang)}</a>
            <span className="text-ink-600">/</span>
            <span className="text-ink-300">{title}</span>
          </nav>
          <div className="text-[11px] font-mono uppercase tracking-[0.22em] text-accent-300">{cfg.kicker}</div>
          <h1 className="mt-3 font-display text-4xl md:text-6xl font-semibold tracking-tight text-ink-100 text-balance">{title}</h1>
          <p className="mt-5 text-ink-300 text-base md:text-lg max-w-2xl">{cfg.intro}</p>
        </div>
      </section>
      <section className="max-w-7xl mx-auto px-5 md:px-8 mb-20 space-y-10 md:space-y-14">
        {groups.map(([name, songs]) => (
          <div key={name}>
            <div className="flex items-end justify-between mb-4">
              <h2 className="font-display text-xl md:text-2xl font-semibold text-ink-100">{name}</h2>
              <span className="text-[11px] font-mono text-ink-400">{songs.length} song{songs.length === 1 ? '' : 's'}</span>
            </div>
            <div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-3 md:gap-5">
              {songs.map(s => (
                <a key={s.id} href={`#/song/${s.slug}`} className="group block rounded-2xl border border-ink-700 bg-ink-850 hover:border-accent-500/40 hover:bg-ink-800/80 transition overflow-hidden">
                  <div className="relative aspect-square">
                    <AlbumCover seed={s.seed} className="w-full h-full" rounded="rounded-none"/>
                  </div>
                  <div className="p-3.5">
                    <div className="font-display font-semibold text-ink-100 text-[14px] truncate">{s.t}</div>
                    <div className="mt-0.5 text-[11px] text-ink-400 truncate">{s.a}</div>
                  </div>
                </a>
              ))}
            </div>
          </div>
        ))}
      </section>
    </main>
  );
}

Object.assign(window, { InfoPage, BrowsePage, PAGES, BROWSE });
