/* global React */
const { useState, useEffect, useRef, useMemo, useCallback } = React;

// ---------- Icons (clean outline, inline SVG) ----------
const Icon = {
  Wave: ({ className = 'w-5 h-5' }) => (
    <svg viewBox="0 0 24 24" fill="none" className={className} aria-hidden="true">
      <path d="M2 12h2m16 0h2M6 12V8m0 8V12m4 4V6m0 12V16m4 0V4m0 16v-2m4-2v-6m0 10V14" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/>
    </svg>
  ),
  Search: ({ className = 'w-5 h-5' }) => (
    <svg viewBox="0 0 24 24" fill="none" className={className} aria-hidden="true">
      <circle cx="11" cy="11" r="7" stroke="currentColor" strokeWidth="1.6"/>
      <path d="m20 20-3.5-3.5" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/>
    </svg>
  ),
  Globe: ({ className = 'w-4 h-4' }) => (
    <svg viewBox="0 0 24 24" fill="none" className={className} aria-hidden="true">
      <circle cx="12" cy="12" r="9" stroke="currentColor" strokeWidth="1.5"/>
      <path d="M3 12h18M12 3c2.5 3 2.5 15 0 18M12 3c-2.5 3-2.5 15 0 18" stroke="currentColor" strokeWidth="1.5"/>
    </svg>
  ),
  Sparkle: ({ className = 'w-4 h-4' }) => (
    <svg viewBox="0 0 24 24" fill="none" className={className} aria-hidden="true">
      <path d="M12 3v4M12 17v4M3 12h4M17 12h4M6 6l2.5 2.5M15.5 15.5 18 18M6 18l2.5-2.5M15.5 8.5 18 6" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/>
    </svg>
  ),
  ArrowRight: ({ className = 'w-4 h-4' }) => (
    <svg viewBox="0 0 24 24" fill="none" className={className} aria-hidden="true">
      <path d="M5 12h14m-5-5 5 5-5 5" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  ),
  Bolt: ({ className = 'w-5 h-5' }) => (
    <svg viewBox="0 0 24 24" fill="none" className={className} aria-hidden="true">
      <path d="M13 3 5 14h6l-1 7 8-11h-6l1-7Z" stroke="currentColor" strokeWidth="1.5" strokeLinejoin="round"/>
    </svg>
  ),
  Layers: ({ className = 'w-5 h-5' }) => (
    <svg viewBox="0 0 24 24" fill="none" className={className} aria-hidden="true">
      <path d="m12 3 9 5-9 5-9-5 9-5Zm-9 9 9 5 9-5m-18 4 9 5 9-5" stroke="currentColor" strokeWidth="1.5" strokeLinejoin="round"/>
    </svg>
  ),
  Translate: ({ className = 'w-5 h-5' }) => (
    <svg viewBox="0 0 24 24" fill="none" className={className} aria-hidden="true">
      <path d="M3 5h10M8 4v2m0 0c0 4-3 7-5 8m2-4c1 2 4 4 7 5m4 4 4-9 4 9m-7-2h6" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  ),
  Sun: ({ className = 'w-4 h-4' }) => (
    <svg viewBox="0 0 24 24" fill="none" className={className} aria-hidden="true">
      <circle cx="12" cy="12" r="4" stroke="currentColor" strokeWidth="1.6"/>
      <path d="M12 2v2M12 20v2M2 12h2M20 12h2M5 5l1.5 1.5M17.5 17.5 19 19M5 19l1.5-1.5M17.5 6.5 19 5" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/>
    </svg>
  ),
  Moon: ({ className = 'w-4 h-4' }) => (
    <svg viewBox="0 0 24 24" fill="none" className={className} aria-hidden="true">
      <path d="M20 14.5A8 8 0 0 1 9.5 4a8 8 0 1 0 10.5 10.5Z" stroke="currentColor" strokeWidth="1.6" strokeLinejoin="round"/>
    </svg>
  ),
  Close: ({ className = 'w-4 h-4' }) => (
    <svg viewBox="0 0 24 24" fill="none" className={className} aria-hidden="true">
      <path d="M6 6l12 12M18 6 6 18" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/>
    </svg>
  ),
  Play: ({ className = 'w-4 h-4' }) => (
    <svg viewBox="0 0 24 24" fill="currentColor" className={className} aria-hidden="true">
      <path d="M7 5v14l12-7L7 5Z"/>
    </svg>
  ),
  Note: ({ className = 'w-4 h-4' }) => (
    <svg viewBox="0 0 24 24" fill="none" className={className} aria-hidden="true">
      <path d="M9 18V6l11-2v12" stroke="currentColor" strokeWidth="1.6" strokeLinejoin="round"/>
      <circle cx="6" cy="18" r="3" stroke="currentColor" strokeWidth="1.6"/>
      <circle cx="17" cy="16" r="3" stroke="currentColor" strokeWidth="1.6"/>
    </svg>
  ),
};

// ---------- Animated wave bars (logo / loader) ----------
function WaveBars({ count = 5, className = 'h-4' }) {
  return (
    <span className={`wave-bars ${className}`} aria-hidden="true">
      {Array.from({ length: count }).map((_, i) => <i key={i} />)}
    </span>
  );
}

// ---------- Logo ----------
function Logo({ size = 'md' }) {
  const text = size === 'lg' ? 'text-xl' : 'text-base';
  return (
    <a href="#/" className="group inline-flex items-center gap-2.5 select-none" aria-label="Lyrithm home">
      <span className="relative inline-flex items-center justify-center w-8 h-8 rounded-xl bg-gradient-to-br from-accent-500 to-accent-700 shadow-glow-accent">
        <WaveBars count={5} className="h-4 w-4 [&>i]:!w-[2px]" />
      </span>
      <span className={`font-display font-semibold tracking-tight text-ink-100 ${text}`}>
        Lyrithm
      </span>
    </a>
  );
}

// ---------- AI label ----------
function AILabel({ className = '', lang }) {
  const code = lang || (typeof window !== 'undefined' && (window.__lyrLang || (localStorage.getItem && localStorage.getItem('lyr:lang')))) || 'EN';
  return (
    <span className={`inline-flex items-center gap-1.5 text-[10.5px] uppercase tracking-[0.14em] font-medium text-accent-300 bg-accent-500/10 border border-accent-500/25 rounded-full px-2 py-0.5 ${className}`}>
      <Icon.Sparkle className="w-3 h-3" />
      {window.t ? window.t('aiLabel', code) : 'AI-assisted interpretation'}
    </span>
  );
}

// ---------- Theme toggle ----------
function ThemeToggle() {
  const [dark, setDark] = useState(true);
  useEffect(() => {
    document.documentElement.classList.toggle('light', !dark);
  }, [dark]);
  return (
    <button
      onClick={() => setDark(d => !d)}
      className="inline-flex items-center justify-center w-9 h-9 rounded-full border border-ink-700 text-ink-200 hover:text-ink-100 hover:border-ink-600 transition"
      aria-label={dark ? 'Switch to light mode' : 'Switch to dark mode'}
    >
      {dark ? <Icon.Sun /> : <Icon.Moon />}
    </button>
  );
}

// ---------- Language switcher ----------
// Active languages — fully translated UI. Built from LOCALES so adding a locale
// in i18n.jsx automatically surfaces it here.
const LANGS = (typeof window !== 'undefined' && window.LOCALES)
  ? window.LOCALES.map(l => ({ code: l.code, name: l.name }))
  : [
      { code: 'EN', name: 'English' },
      { code: 'ID', name: 'Bahasa Indonesia' },
      { code: 'ES', name: 'Español' },
      { code: 'PT', name: 'Português' },
      { code: 'FR', name: 'Français' },
      { code: 'JP', name: '日本語' },
    ];

function LangSwitcher({ value = 'EN', onChange = () => {}, compact = false }) {
  const [open, setOpen] = useState(false);
  const ref = useRef(null);
  useEffect(() => {
    const onDoc = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', onDoc);
    return () => document.removeEventListener('mousedown', onDoc);
  }, []);
  return (
    <div ref={ref} className="relative">
      <button
        onClick={() => setOpen(o => !o)}
        className={`inline-flex items-center gap-2 rounded-full border border-ink-700 hover:border-ink-600 transition text-ink-100 ${compact ? 'h-9 px-3 text-sm' : 'h-9 px-3.5 text-sm'}`}
        aria-haspopup="listbox"
        aria-expanded={open}
        aria-label={window.t ? window.t('nav.changeLang', value) : 'Change language'}
      >
        <Icon.Globe />
        <span className="font-medium tabular-nums">{value}</span>
        <svg viewBox="0 0 24 24" className="w-3.5 h-3.5 text-ink-300" fill="none"><path d="m6 9 6 6 6-6" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"/></svg>
      </button>
      {open && (
        <div role="listbox" className="absolute right-0 mt-2 w-60 max-h-[70vh] overflow-y-auto rounded-xl border border-ink-700 bg-ink-850/95 backdrop-blur-md shadow-soft p-1.5 z-50">
          {LANGS.map(l => (
            <button
              key={l.code}
              role="option"
              aria-selected={l.code === value}
              onClick={() => { onChange(l.code); setOpen(false); }}
              className={`w-full flex items-center justify-between gap-3 rounded-lg px-3 py-2 text-sm hover:bg-ink-800 transition ${l.code === value ? 'text-ink-100' : 'text-ink-200'}`}
            >
              <span className="flex items-center gap-2.5">
                <span className="font-mono text-[11px] text-ink-300 w-7">{l.code}</span>
                <span>{l.name}</span>
              </span>
              {l.code === value && <span className="w-1.5 h-1.5 rounded-full bg-accent-500"/>}
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

// ---------- Top nav ----------
function TopNav({ page, lang, setLang }) {
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 8);
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  // Saved count badge
  const [savedCount, setSavedCount] = useState(() => {
    try { return JSON.parse(localStorage.getItem('lyr:saved') || '[]').length; } catch { return 0; }
  });
  useEffect(() => {
    const f = () => {
      try { setSavedCount(JSON.parse(localStorage.getItem('lyr:saved') || '[]').length); } catch {}
    };
    window.addEventListener('lyr:saved-changed', f);
    return () => window.removeEventListener('lyr:saved-changed', f);
  }, []);

  return (
    <header
      className={`sticky top-0 z-40 transition-all duration-300 ${scrolled ? 'backdrop-blur-xl bg-ink-900/75 border-b border-ink-800' : 'backdrop-blur-md bg-ink-900/40 border-b border-transparent'}`}
    >
      <div className="max-w-7xl mx-auto px-5 md:px-8 h-16 md:h-[68px] flex items-center gap-3 md:gap-4">
        <Logo />
        {/* Search combobox (typeahead) */}
        <div className="hidden sm:block flex-1 max-w-lg mx-auto">
          {window.SearchCombobox ? <window.SearchCombobox size="md"/> : null}
        </div>

        <nav className="hidden lg:flex items-center gap-1 text-sm text-ink-200" aria-label="Primary">
          <a href="#/" className={`px-3 py-2 rounded-md hover:text-ink-100 transition ${page === 'home' ? 'text-ink-100' : ''}`}>{window.t('nav.home', lang)}</a>
          <a href="#/trending" className={`px-3 py-2 rounded-md hover:text-ink-100 transition ${page === 'trending' ? 'text-ink-100' : ''}`}>{window.t('nav.trending', lang)}</a>
          <a href="#/saved" className={`px-3 py-2 rounded-md hover:text-ink-100 transition inline-flex items-center gap-1.5 ${page === 'saved' ? 'text-ink-100' : ''}`}>
            {window.t('nav.saved', lang)}
            {savedCount > 0 && (
              <span className="inline-flex items-center justify-center min-w-[18px] h-[18px] px-1 rounded-full bg-accent-500/20 border border-accent-500/40 text-[10px] font-mono text-accent-200">{savedCount}</span>
            )}
          </a>
        </nav>

        <div className="ml-auto flex items-center gap-2">
          <LangSwitcher value={lang} onChange={setLang} />
          <ThemeToggle />
          <a
            href="#"
            className="hidden md:inline-flex items-center h-9 px-3.5 rounded-full text-sm text-ink-100 hover:bg-ink-800 transition"
          >{window.t('nav.signIn', lang)}</a>
          <a
            href="#"
            className="inline-flex items-center h-9 px-4 rounded-full text-sm font-medium text-white bg-accent-500 hover:bg-accent-600 transition shadow-glow-accent"
          >{window.t('nav.getStarted', lang)}</a>
        </div>
      </div>

      {/* Mobile inline search */}
      <div className="sm:hidden px-5 pb-3">
        {window.SearchCombobox ? <window.SearchCombobox size="md"/> : null}
      </div>
    </header>
  );
}

// ---------- Footer ----------
function Footer({ lang, setLang }) {
  const LINKS = (window.FOOTER_LINKS_I18N && (window.FOOTER_LINKS_I18N[lang] || window.FOOTER_LINKS_I18N.EN)) || {};
  const lbl = (key) => LINKS[key] || key;
  const cols = [
    {
      title: window.t('footer.cols.browse', lang),
      links: [
        [lbl('browse/artist'),   '#/browse/artist'],
        [lbl('browse/genre'),    '#/browse/genre'],
        [lbl('browse/language'), '#/browse/language'],
        [lbl('browse/era'),      '#/browse/era'],
        [lbl('browse/mood'),     '#/browse/mood'],
        [lbl('browse/new'),      '#/browse/new'],
        [lbl('trending'),        '#/trending'],
        [lbl('saved'),           '#/saved'],
      ],
    },
    {
      title: window.t('footer.cols.product', lang),
      links: [
        [lbl('page/how'), '#/page/how'],
        [lbl('page/meaning-vs-lyrics'), '#/page/meaning-vs-lyrics'],
        [lbl('page/multilingual'), '#/page/multilingual'],
        [lbl('page/compare-genius'), '#/page/compare-genius'],
        [lbl('page/extension'), '#/page/extension'],
        [lbl('page/api'), '#/page/api'],
      ],
    },
    {
      title: window.t('footer.cols.company', lang),
      links: [
        [lbl('page/about'), '#/page/about'],
        [lbl('page/standards'), '#/page/standards'],
        [lbl('page/honesty'), '#/page/honesty'],
        [lbl('page/careers'), '#/page/careers'],
        [lbl('page/press'), '#/page/press'],
        [lbl('page/contact'), '#/page/contact'],
      ],
    },
    {
      title: window.t('footer.cols.resources', lang),
      links: [
        [lbl('page/help'), '#/page/help'],
        [lbl('page/submit'), '#/page/submit'],
        [lbl('page/artist-tools'), '#/page/artist-tools'],
        [lbl('page/status'), '#/page/status'],
        [lbl('page/privacy'), '#/page/privacy'],
        [lbl('page/terms'), '#/page/terms'],
      ],
    },
  ];
  return (
    <footer className="relative border-t border-ink-800 bg-ink-900">
      <div className="max-w-7xl mx-auto px-5 md:px-8 py-16 md:py-20">
        <div className="grid grid-cols-2 md:grid-cols-6 gap-10 md:gap-8">
          <div className="col-span-2 md:col-span-2">
            <Logo size="lg" />
            <p className="mt-4 text-sm leading-relaxed text-ink-300 max-w-xs">
              {window.t('footer.tagline', lang)}
            </p>
            <div className="mt-6 flex items-center gap-3">
              <LangSwitcher value={lang} onChange={setLang} />
              <span className="text-xs text-ink-400">{window.t('common.langAvailable', lang)}</span>
            </div>
          </div>
          {cols.map(col => (
            <div key={col.title}>
              <h4 className="font-display text-[13px] font-semibold tracking-wide text-ink-100 uppercase">{col.title}</h4>
              <ul className="mt-4 space-y-2.5">
                {col.links.map(([label, href]) => (
                  <li key={label + href}>
                    <a href={href} className="text-sm text-ink-300 hover:text-ink-100 transition">{label}</a>
                  </li>
                ))}
              </ul>
            </div>
          ))}
        </div>
        <div className="mt-14 pt-6 border-t border-ink-800 flex flex-col md:flex-row md:items-center justify-between gap-4">
          <div className="flex items-center gap-3 text-xs text-ink-400">
            <span>{window.t('footer.copy', lang)}</span>
            <span className="w-1 h-1 rounded-full bg-ink-600"/>
            <span>{window.t('footer.madeFor', lang)}</span>
          </div>
          <div className="flex items-center gap-4 text-xs text-ink-400">
            <span className="inline-flex items-center gap-1.5"><a href="#/page/status" className="hover:text-ink-200 flex items-center gap-1.5"><span className="w-1.5 h-1.5 rounded-full bg-emerald-400"/> {window.t('footer.allOk', lang)}</a></span>
            <a href="#/page/sitemap" className="hover:text-ink-200">{window.t('common.sitemap', lang)}</a>
          </div>
        </div>
      </div>
    </footer>
  );
}

// ---------- Sticky bottom CTA ----------
function StickyCTA({ lang = 'EN' }) {
  return (
    <div className="fixed inset-x-0 bottom-0 z-40 pointer-events-none">
      <div className="pointer-events-auto mx-auto max-w-7xl px-3 md:px-6 pb-3 md:pb-4">
        <div className="relative overflow-hidden rounded-2xl border border-ink-700 bg-ink-850/90 backdrop-blur-xl shadow-soft">
          {/* subtle waveform on left */}
          <div className="absolute inset-y-0 left-0 w-28 md:w-40 opacity-60 pointer-events-none">
            <svg viewBox="0 0 200 80" preserveAspectRatio="none" className="w-full h-full text-accent-500/60 ambient-wave">
              <path d="M0 40 Q 20 10 40 40 T 80 40 T 120 40 T 160 40 T 200 40" fill="none" stroke="currentColor" strokeWidth="1.4"/>
              <path d="M0 50 Q 25 25 50 50 T 100 50 T 150 50 T 200 50" fill="none" stroke="currentColor" strokeWidth="1"/>
            </svg>
          </div>
          <div className="relative flex items-center gap-3 md:gap-5 pl-4 md:pl-44 pr-3 md:pr-4 py-3 md:py-3.5">
            <div className="hidden md:flex items-center gap-2.5">
              <span className="relative inline-flex w-2 h-2 rounded-full bg-accent-500 pulse-dot"/>
              <span className="text-[11px] uppercase font-mono tracking-[0.2em] text-accent-300">{window.t('sticky.pill', lang)}</span>
            </div>
            <div className="flex-1 min-w-0">
              <div className="hidden sm:block text-[15px] md:text-base font-medium text-ink-100 truncate">
                {window.t('sticky.headline', lang)}
              </div>
              <div className="sm:hidden text-[14px] font-medium text-ink-100 truncate">
                {window.t('sticky.headlineShort', lang)}
              </div>
              <div className="hidden md:block text-xs text-ink-400 mt-0.5">{window.t('sticky.sub', lang)}</div>
            </div>
            <a
              href="#/"
              className="shrink-0 inline-flex items-center gap-1.5 h-10 md:h-11 px-4 md:px-5 rounded-full bg-accent-500 hover:bg-accent-600 text-white text-sm font-medium transition shadow-glow-accent"
            >
              {window.t('sticky.cta', lang)}
              <Icon.ArrowRight className="w-4 h-4"/>
            </a>
          </div>
        </div>
      </div>
    </div>
  );
}

// ---------- Album cover placeholder ----------
const COVER_PALETTES = [
  ['#7C5CFF', '#241560'],
  ['#FF7AB6', '#5634D6'],
  ['#5EE6C8', '#1d4d4a'],
  ['#F4C26B', '#3a2410'],
  ['#7AB6FF', '#0e2a52'],
  ['#C8FF6B', '#1f3a0a'],
  ['#FF8C5C', '#3b1206'],
  ['#B8B8FF', '#2A2A3A'],
];

function AlbumCover({ seed = 0, title = '', rounded = 'rounded-xl', className = '' }) {
  const [a, b] = COVER_PALETTES[seed % COVER_PALETTES.length];
  const r = (seed * 9301 + 49297) % 100;
  return (
    <div className={`relative overflow-hidden ${rounded} ${className}`} aria-hidden="true">
      <div className="absolute inset-0" style={{ background: `linear-gradient(135deg, ${a} 0%, ${b} 100%)` }} />
      {/* halftone dots */}
      <div className="absolute inset-0 opacity-30 mix-blend-overlay" style={{
        backgroundImage: 'radial-gradient(rgba(255,255,255,0.5) 1px, transparent 1.4px)',
        backgroundSize: '10px 10px',
      }}/>
      {/* concentric vinyl arcs */}
      <svg className="absolute inset-0 w-full h-full opacity-50" viewBox="0 0 100 100" preserveAspectRatio="none">
        <g fill="none" stroke="rgba(255,255,255,0.45)" strokeWidth="0.4">
          <circle cx={20 + r/4} cy={80 - r/3} r="60"/>
          <circle cx={20 + r/4} cy={80 - r/3} r="48"/>
          <circle cx={20 + r/4} cy={80 - r/3} r="36"/>
          <circle cx={20 + r/4} cy={80 - r/3} r="22"/>
        </g>
      </svg>
      {/* gloss */}
      <div className="absolute -top-1/2 -left-1/2 w-[180%] h-[180%] rotate-[18deg] opacity-15"
           style={{ background: 'linear-gradient(180deg, rgba(255,255,255,0.6), transparent 30%)' }} />
      {title && (
        <div className="absolute inset-x-0 bottom-0 p-2 text-[9px] font-mono uppercase tracking-widest text-white/70 truncate">
          {title}
        </div>
      )}
    </div>
  );
}

// Expose to other scripts
Object.assign(window, {
  Icon, WaveBars, Logo, AILabel, ThemeToggle, LangSwitcher, TopNav, Footer, StickyCTA, AlbumCover, LANGS,
});
