/* v3 — App shell with simpler home + dedicated Features page.
   v3.1 — Home/Features nav, merged hero+showcase, feature overview table. */

const NAV_LINKS_V3 = [
  { id: "home", label: "Home", view: "home" },
  { id: "features", label: "Features", view: "features" },
  { id: "opensource", label: "Open Source", view: "opensource" },
];

function NavV3({ onNavigate, current }) {
  const [scrolled, setScrolled] = React.useState(false);
  React.useEffect(() => {
    const fn = () => setScrolled(window.scrollY > 12);
    fn();
    window.addEventListener('scroll', fn, { passive: true });
    return () => window.removeEventListener('scroll', fn);
  }, []);
  return (
    <header className={`nav ${scrolled ? "scrolled" : ""}`}>
      <div className="container nav-row">
        <a className="nav-brand" href="#" onClick={(e)=>{e.preventDefault(); onNavigate('home');}}>
          <Logo/>
        </a>
        <nav className="nav-links">
          {NAV_LINKS_V3.map(l => (
            <a key={l.id} href="#"
               onClick={(e)=>{ e.preventDefault(); onNavigate(l.view, l.anchor); }}>{l.label}</a>
          ))}
          <a href="#vote" onClick={(e)=>{e.preventDefault(); onNavigate('vote');}}>Vote</a>
          <button className="btn btn-primary btn-sm" style={{marginLeft: 16}} onClick={()=>onNavigate('home','download')}>Download free</button>
        </nav>
      </div>
    </header>
  );
}

/* ---- Showcase data (used in merged hero) ---- */

const SHOWCASE_VIEWS = [
  {
    id: "library",
    label: "Library",
    short: "Library",
    src: "assets/screen-library.webp",
    caption: <><strong>Your collection, at home.</strong> Albums, artists, songs, composers and genres — all browsable on the Mac you already own.</>
  },
  {
    id: "nowplaying",
    label: "Now Playing",
    short: "Playing",
    src: "assets/screen-nowplaying.webp",
    caption: <><strong>An ambient view that adapts to what you're playing.</strong> The background quietly tints itself from the album artwork.</>
  },
  {
    id: "search",
    label: "Search",
    short: "Search",
    src: "assets/screen-search.webp",
    caption: <><strong>Find anything instantly.</strong> Indexed locally across titles, artists, composers, albums and tags.</>
  },
  {
    id: "edit",
    label: "Edit Metadata",
    short: "Edit",
    src: "assets/screen-edit.webp",
    caption: <><strong>Built-in metadata editor.</strong> Clean up titles, artwork and tags without leaving the app — batch-edit included.</>
  },
];

/* ---- Hero (merged with showcase: copy on top, tab+screenshot below) ---- */

function HeroV3({ onNavigate }) {
  const [active, setActive] = React.useState("library");
  const cur = SHOWCASE_VIEWS.find(v => v.id === active) || SHOWCASE_VIEWS[0];

  React.useEffect(() => {
    SHOWCASE_VIEWS.forEach(v => { const i = new Image(); i.src = v.src; });
  }, []);

  return (
    <section className="hero hero-show">
      <div className="hero-glow"/>
      <div className="container hero-inner">
        <div className="hero-copy">
          <h1>
            A serious music player<br/>
            for <span className="serif-italic">real</span> libraries.
          </h1>
          <p className="lede">
            Moonlight is a simple, free, open-source music player for macOS.
            For people who own their music and want it to feel like it.
          </p>
          <div className="hero-ctas">
            <button className="btn btn-primary btn-lg" onClick={()=>onNavigate('home','download')}>
              <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor"><path d="M11.5 1.5c-.6.7-1.6 1.2-2.5 1.1-.1-.9.3-1.8.9-2.4.6-.7 1.6-1.2 2.4-1.2.1.9-.3 1.9-.8 2.5zM14 11.5c-.4 1-.6 1.4-1.1 2.3-.7 1.2-1.7 2.7-2.9 2.7-1.1 0-1.4-.7-2.9-.7-1.5 0-1.8.7-2.9.7-1.2 0-2.2-1.4-2.9-2.6C-.3 11-.4 6.8 1 4.6c1-1.5 2.5-2.4 4-2.4 1.1 0 2.1.7 2.9.7.8 0 2-.8 3.3-.7.6 0 2.1.2 3.1 1.6-2.7 1.5-2.3 5.4-.3 6.7z"/></svg>
              Get it free on the Mac App Store
            </button>
          </div>
          <div className="hero-foot">
            <span className="dot-sep">Free and open source</span>
            <span className="dot-sep">Apple Silicon &amp; Intel</span>
            <span className="dot-sep">No account, no telemetry</span>
          </div>
        </div>
      </div>

      <div className="container hero-mockup-wrap">
        <div className="hshow-host" data-view={active}>
          <div className="hshow-glow"/>

          <div className="hshow-switch" role="tablist" aria-label="Showcase views">
            {SHOWCASE_VIEWS.map(v => (
              <button
                key={v.id}
                role="tab"
                aria-selected={active === v.id}
                className={`hshow-tab ${active === v.id ? "active" : ""}`}
                onClick={() => setActive(v.id)}>
                <span className="tab-label-long">{v.label}</span>
                <span className="tab-label-short">{v.short}</span>
              </button>
            ))}
          </div>

          <div className="hshow-frame">
            {SHOWCASE_VIEWS.map(v => (
              <img
                key={v.id}
                className={`hshow-img ${active === v.id ? "active" : ""}`}
                src={v.src}
                alt={`Moonlight — ${v.label}`}
                loading={v.id === "library" ? "eager" : "lazy"}
              />
            ))}
          </div>

          <p className="hshow-caption">{cur.caption}</p>
        </div>
      </div>
    </section>
  );
}

/* ---- Feature overview (home page, grouped) ---- */

function CatIcon({ name }) {
  const c = { width: 18, height: 18, viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: 1.4, strokeLinecap: "round", strokeLinejoin: "round" };
  const icons = {
    player:    <svg {...c}><circle cx="12" cy="12" r="9"/><path d="M10 8.5v7l6-3.5z" fill="currentColor" stroke="none"/></svg>,
    search:    <svg {...c}><circle cx="11" cy="11" r="6.5"/><path d="M16 16l5 5"/></svg>,
    library:   <svg {...c}><path d="M4 5h16M4 10h16M4 15h16M4 20h10"/></svg>,
    playlists: <svg {...c}><path d="M4 7h11M4 12h11M4 17h7"/><circle cx="18" cy="17" r="2.5"/><path d="M20.5 16.5V8l-3 1"/></svg>,
    metadata:  <svg {...c}><path d="M3 12l9-9 8 1 1 8-9 9z"/><circle cx="15" cy="9" r="1.4"/></svg>,
    other:     <svg {...c}><circle cx="12" cy="12" r="9"/><circle cx="12" cy="12" r="3"/></svg>,
  };
  return icons[name];
}

function ItemIcon({ name }) {
  const c = { width: 14, height: 14, viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: 1.5, strokeLinecap: "round", strokeLinejoin: "round" };
  const icons = {
    nowplaying: <svg {...c}><rect x="3" y="5" width="18" height="13" rx="2"/><path d="M3 9h18"/><circle cx="6" cy="7" r="0.6" fill="currentColor"/><circle cx="8" cy="7" r="0.6" fill="currentColor"/></svg>,
    gapless:    <svg {...c}><path d="M5 12h4M15 12h4"/><circle cx="12" cy="12" r="2.2"/></svg>,
    airplay:    <svg {...c}><path d="M4 16V6h16v10M4 16h3M20 16h-3"/><path d="M8 20l4-5 4 5z"/></svg>,
    mediakeys:  <svg {...c}><rect x="3" y="6" width="18" height="12" rx="2"/><path d="M7 10h.01M11 10h.01M15 10h.01M7 14h10"/></svg>,
    themes:     <svg {...c}><circle cx="12" cy="12" r="9"/><circle cx="8" cy="10" r="1" fill="currentColor"/><circle cx="14" cy="8" r="1" fill="currentColor"/><circle cx="16" cy="13" r="1" fill="currentColor"/><path d="M12 21a3 3 0 010-6 1.5 1.5 0 100-3"/></svg>,
    search:     <svg {...c}><circle cx="11" cy="11" r="6.5"/><path d="M16 16l5 5"/></svg>,
    scale:      <svg {...c}><ellipse cx="12" cy="6" rx="8" ry="3"/><path d="M4 6v6c0 1.7 3.6 3 8 3s8-1.3 8-3V6M4 12v6c0 1.7 3.6 3 8 3s8-1.3 8-3v-6"/></svg>,
    scan:       <svg {...c}><path d="M3 7V5a2 2 0 012-2h2M17 3h2a2 2 0 012 2v2M21 17v2a2 2 0 01-2 2h-2M7 21H5a2 2 0 01-2-2v-2"/><path d="M7 12h10"/></svg>,
    browse:     <svg {...c}><rect x="3" y="3" width="7" height="7" rx="1"/><rect x="14" y="3" width="7" height="7" rx="1"/><rect x="3" y="14" width="7" height="7" rx="1"/><rect x="14" y="14" width="7" height="7" rx="1"/></svg>,
    favorites:  <svg {...c}><path d="M12 20s-7-4.4-7-10a4 4 0 017-2.6A4 4 0 0119 10c0 5.6-7 10-7 10z"/></svg>,
    dnd:        <svg {...c}><path d="M4 7h12M4 12h12M4 17h8"/><path d="M18 14l3 3-3 3M21 17h-6"/></svg>,
    queue:      <svg {...c}><path d="M3 6l4 3-4 3M3 13l4 3-4 3"/><path d="M10 7h11M10 14h11M10 19h7"/></svg>,
    export:     <svg {...c}><path d="M12 4v11M8 8l4-4 4 4"/><path d="M5 17v2a2 2 0 002 2h10a2 2 0 002-2v-2"/></svg>,
    tags:       <svg {...c}><path d="M3 12l9-9 8 1 1 8-9 9z"/><circle cx="15" cy="9" r="1.4"/></svg>,
    artwork:    <svg {...c}><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="9" cy="9" r="1.6"/><path d="M21 16l-5-5-9 9"/></svg>,
    formats:    <svg {...c}><path d="M14 3H6a2 2 0 00-2 2v14a2 2 0 002 2h12a2 2 0 002-2V9z"/><path d="M14 3v6h6"/></svg>,
    opensource: <svg {...c}><path d="M9 19c-5 1.5-5-2.5-7-3m14 6v-3.9a3.4 3.4 0 00-.9-2.6c3.1-.3 6.4-1.5 6.4-7A5.4 5.4 0 0020 7.8 5.1 5.1 0 0019.9 4S18.7 3.7 16 5.5a13.4 13.4 0 00-7 0C6.3 3.7 5.1 4 5.1 4A5.1 5.1 0 005 7.8 5.4 5.4 0 003.5 11.5c0 5.4 3.3 6.6 6.4 7A3.4 3.4 0 009 21.1V25"/></svg>,
  };
  return icons[name];
}

const FEATURE_GROUPS = [
  { ico: "player", name: "Player Experience", items: [
    { ico: "nowplaying", t: "Built-in Now Playing and Mini Player views" },
    { ico: "gapless",    t: "Gapless playback" },
    { ico: "airplay",    t: "AirPlay support" },
    { ico: "mediakeys",  t: "macOS media keys integration" },
    { ico: "themes",     t: "Multiple built-in themes to customize the app appearance" },
  ]},
  { ico: "library", name: "Library", items: [
    { ico: "scale",      t: "Built for large local music libraries" },
    { ico: "scan",       t: "Incremental and live folder scanning" },
    { ico: "browse",     t: "Browse Artists, Albums, Songs, Favorites, Composers, and Genres" },
    { ico: "favorites",  t: "Favorites, play counts, and last-played tracking" },
  ]},
  { ico: "playlists", name: "Playlists & Queue", items: [
    { ico: "dnd",        t: "Local playlists with drag-and-drop support" },
    { ico: "queue",      t: "Play Next, Play Later, and Shuffle actions" },
    { ico: "export",     t: "Export playlists as .m3u" },
  ]},
  { ico: "metadata", name: "Metadata", items: [
    { ico: "tags",       t: "Built-in tag editor with batch editing" },
    { ico: "artwork",    t: "Artwork editing" },
    { ico: "formats",    t: "Broad format support: MP3, FLAC, ALAC, WAV, AIFF, AAC, M4A" },
  ]},
  { ico: "search", name: "Search & More", items: [
    { ico: "search",     t: "Powerful Spotlight-style search across albums, artists, composers, and songs" },
    { ico: "opensource", t: "Open source" },
  ]},
];

function FeatureOverview({ onNavigate }) {
  return (
    <section className="feat-overview">
      <div className="container">
        <div className="feat-overview-head">
          <h2>Feature overview</h2>
        </div>

        <div className="feat-grid">
          {FEATURE_GROUPS.map((g) => (
            <article key={g.name} className="feat-group">
              <header className="feat-group-head">
                <span className="feat-group-ico"><CatIcon name={g.ico}/></span>
                <h3>{g.name}</h3>
              </header>
              <ul className="feat-group-list">
                {g.items.map((it, i) => (
                  <li key={i}>
                    <span className="feat-item-ico"><ItemIcon name={it.ico}/></span>
                    <span className="feat-item-t">{it.t}</span>
                  </li>
                ))}
              </ul>
            </article>
          ))}
        </div>

        <div className="feat-overview-foot">
          <a href="#features" className="feat-more" onClick={(e)=>{e.preventDefault(); onNavigate('features');}}>
            See the full feature tour
            <svg width="12" height="12" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M6 4l4 4-4 4"/></svg>
          </a>
        </div>
      </div>
    </section>
  );
}

/* ---- Features page (dedicated route) ---- */

function FeaturesPageV3({ onNavigate }) {
  React.useEffect(() => { window.scrollTo({top: 0, behavior: "instant"}); }, []);
  return (
    <div className="fpage">
      <div className="container">
        <div className="fpage-head">
          <span className="eyebrow">Features</span>
          <h1>Everything Moonlight does,<br/>and nothing it doesn't.</h1>
          <p className="lede">
            A focused tour of the app — what it indexes, what it edits, how it plays,
            and the deliberate things it leaves out.
          </p>
        </div>
      </div>

      {/* Reuse existing components */}
      <Features/>
      <LibrarySection/>
    </div>
  );
}

/* ---- Open Source page (dedicated route) ---- */

function OpenSourcePageV3({ onNavigate }) {
  React.useEffect(() => { window.scrollTo({top: 0, behavior: "instant"}); }, []);
  return (
    <div className="fpage">
      <OpenSource/>
    </div>
  );
}

/* ---- App router ---- */

function AppV3() {
  const [view, setView] = React.useState(() => {
    const h = location.hash.replace('#', '');
    if (h === 'vote') return 'vote';
    if (h === 'features') return 'features';
    if (h === 'opensource') return 'opensource';
    return 'home';
  });

  const navigate = (target, anchor) => {
    const goHomeAnchor = () => {
      if (anchor) {
        requestAnimationFrame(() => {
          const el = document.getElementById(anchor);
          if (el) window.scrollTo({ top: el.offsetTop - 60, behavior: "smooth" });
        });
      } else {
        window.scrollTo({ top: 0, behavior: "smooth" });
      }
    };

    if (target === "vote") {
      setView("vote");
      history.replaceState(null, "", "#vote");
      window.scrollTo({ top: 0, behavior: "instant" });
      return;
    }
    if (target === "features") {
      setView("features");
      history.replaceState(null, "", "#features");
      window.scrollTo({ top: 0, behavior: "instant" });
      return;
    }
    if (target === "opensource") {
      setView("opensource");
      history.replaceState(null, "", "#opensource");
      window.scrollTo({ top: 0, behavior: "instant" });
      return;
    }
    // home
    if (view !== "home") {
      setView("home");
      history.replaceState(null, "", anchor ? `#${anchor}` : "#");
      setTimeout(goHomeAnchor, 30);
    } else {
      goHomeAnchor();
    }
  };

  React.useEffect(() => {
    const onHash = () => {
      const h = location.hash.replace('#', '');
      if (h === 'vote') setView('vote');
      else if (h === 'features') setView('features');
      else if (h === 'opensource') setView('opensource');
      else setView('home');
    };
    window.addEventListener('hashchange', onHash);
    return () => window.removeEventListener('hashchange', onHash);
  }, []);

  return (
    <>
      <NavV3 onNavigate={navigate} current={view}/>
      {view === "home" && (
        <>
          <HeroV3 onNavigate={navigate}/>
          <FeatureOverview onNavigate={navigate}/>
          <Download onNavigate={navigate}/>
        </>
      )}
      {view === "features" && <FeaturesPageV3 onNavigate={navigate}/>}
      {view === "opensource" && <OpenSourcePageV3 onNavigate={navigate}/>}
      {view === "vote" && <VotePage onNavigate={navigate}/>}
      <Footer onNavigate={navigate}/>
    </>
  );
}

window.AppV3 = AppV3;
window.NavV3 = NavV3;
window.HeroV3 = HeroV3;
window.FeatureOverview = FeatureOverview;
window.FeaturesPageV3 = FeaturesPageV3;
window.OpenSourcePageV3 = OpenSourcePageV3;
