/* Voting (preview + full page) + Download CTA + Footer */

const ROADMAP = [
  { id: "miniplayer", title: "Mini-player", desc: "A compact, always-on-top window for when Moonlight isn't your foreground app.", status: "progress", votes: 1284, hot: true },
  { id: "ios", title: "iPhone &amp; iPad companion app", desc: "Library sync over the local network. Browse and play the same library on the couch.", status: "planned", votes: 2417, hot: true },
  { id: "ffmpeg", title: "Ogg, Opus, and FFmpeg formats", desc: "Beyond AVFoundation defaults — playback for the long tail of formats serious collectors keep around.", status: "planned", votes: 982 },
  { id: "smart", title: "Smart playlists", desc: "Rule-based playlists. Recently added classical under 5 minutes; jazz from the 50s; anything you can describe.", status: "consider", votes: 856 },
  { id: "gapless", title: "Gapless playback", desc: "Seamless transitions between tracks for live albums, concept records, and continuous classical works.", status: "progress", votes: 1547, hot: true },
  { id: "replaygain", title: "ReplayGain", desc: "Volume normalization that respects the original mastering. Album mode and track mode.", status: "planned", votes: 612 },
  { id: "lyrics", title: "Lyrics", desc: "Embedded and synced lyrics. Pulled from tags, never the cloud.", status: "consider", votes: 478 },
  { id: "lastfm", title: "Last.fm scrobbling", desc: "Optional, off by default, and the only thing in Moonlight that talks to a third party.", status: "consider", votes: 521 },
  { id: "metadata", title: "Metadata editing &amp; overrides", desc: "Fix titles, dates, and tags without rewriting the underlying files — overrides stay in Moonlight.", status: "planned", votes: 723 },
  { id: "eq", title: "Equalizer", desc: "10-band EQ with presets. Per-output device profiles for headphones and speakers.", status: "later", votes: 346 },
  { id: "crossfade", title: "Crossfade", desc: "Optional crossfade between tracks for casual listening and DJ-style transitions.", status: "later", votes: 287 },
  { id: "carplay", title: "CarPlay", desc: "Browse and play your library from the dashboard. Comes after the mobile app.", status: "later", votes: 411 },
];

const STATUS_META = {
  progress:  { label: "In progress",         cls: "badge-progress" },
  planned:   { label: "Planned",             cls: "badge-planned" },
  consider:  { label: "Under consideration", cls: "badge-consider" },
  later:     { label: "Later",               cls: "badge-later" },
  shipped:   { label: "Shipped",             cls: "badge-shipped" },
};

function useVotes() {
  const [votes, setVotes] = React.useState(() => {
    try { return JSON.parse(localStorage.getItem("ml_votes") || "{}"); } catch { return {}; }
  });
  const toggle = (id) => {
    setVotes(v => {
      const next = { ...v, [id]: !v[id] };
      try { localStorage.setItem("ml_votes", JSON.stringify(next)); } catch {}
      return next;
    });
  };
  return [votes, toggle];
}

function VoteButton({ item, voted, onToggle, size = "md" }) {
  const count = item.votes + (voted ? 1 : 0);
  return (
    <button
      className={`vote-btn vote-btn-${size} ${voted ? "voted" : ""}`}
      onClick={() => onToggle(item.id)}
      aria-pressed={voted}
    >
      <svg width="11" height="11" viewBox="0 0 12 12" fill="none">
        <path d="M6 2L10 7H7v3H5V7H2z" fill="currentColor"/>
      </svg>
      <span className="vote-count">{count.toLocaleString()}</span>
    </button>
  );
}

/* ----- Roadmap preview (on landing page) ----- */

function RoadmapPreview({ onNavigate }) {
  const [votes, toggle] = useVotes();
  const preview = [...ROADMAP].sort((a,b)=>b.votes-a.votes).slice(0, 5);
  return (
    <section id="roadmap" className="roadmap">
      <div className="container">
        <div className="roadmap-head">
          <div>
            <span className="eyebrow">Vote &amp; suggest</span>
            <h2>Help decide what<br/>Moonlight builds next.</h2>
          </div>
          <p className="lede">
            Moonlight has no committee and no marketing roadmap. Vote on what's
            been suggested, or open a new request — the most-voted ideas move
            from <span className="serif-italic">considering</span> to <span className="serif-italic">shipping</span>.
          </p>
        </div>

        <div className="vote-list">
          {preview.map((item) => (
            <div key={item.id} className="vote-row">
              <VoteButton item={item} voted={!!votes[item.id]} onToggle={toggle}/>
              <div className="vote-row-body">
                <div className="vote-row-head">
                  <h3 className="vote-row-title" dangerouslySetInnerHTML={{__html: item.title}}/>
                  <span className={`badge ${STATUS_META[item.status].cls}`}>
                    <span className="dot"/>{STATUS_META[item.status].label}
                  </span>
                  {item.hot && <span className="hot-tag">Trending</span>}
                </div>
                <p className="vote-row-desc">{item.desc}</p>
              </div>
            </div>
          ))}
        </div>

        <div className="roadmap-foot">
          <button className="btn btn-ghost btn-lg" onClick={()=>onNavigate('vote')}>
            See all feature requests &amp; vote
            <svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.4"><path d="M3 8h10M9 4l4 4-4 4" strokeLinecap="round" strokeLinejoin="round"/></svg>
          </button>
        </div>
      </div>
    </section>
  );
}

/* ----- Full Vote page ----- */

function VotePage({ onNavigate }) {
  const [votes, toggle] = useVotes();
  const [filter, setFilter] = React.useState("all");
  const [sort, setSort] = React.useState("votes");
  const [query, setQuery] = React.useState("");

  const totalVotes = ROADMAP.reduce((s,r)=>s+r.votes,0) + Object.values(votes).filter(Boolean).length;
  const myVotes = Object.values(votes).filter(Boolean).length;

  const filtered = ROADMAP
    .filter(r => filter === "all" || r.status === filter)
    .filter(r => !query || r.title.toLowerCase().includes(query.toLowerCase()) || r.desc.toLowerCase().includes(query.toLowerCase()))
    .sort((a,b) => sort === "votes" ? (b.votes+(votes[b.id]?1:0)) - (a.votes+(votes[a.id]?1:0)) : a.title.localeCompare(b.title));

  const counts = {
    all: ROADMAP.length,
    progress: ROADMAP.filter(r=>r.status==="progress").length,
    planned: ROADMAP.filter(r=>r.status==="planned").length,
    consider: ROADMAP.filter(r=>r.status==="consider").length,
    later: ROADMAP.filter(r=>r.status==="later").length,
  };

  return (
    <main className="vote-page">
      <div className="container">

        <div className="vote-hero">
          <span className="eyebrow">Feature requests</span>
          <h1 style={{fontSize:"clamp(40px, 5vw, 64px)"}}>Vote on what<br/>Moonlight should build next.</h1>
          <p className="lede" style={{marginTop:18}}>
            One vote per person per feature. No accounts, no spam. The team reads every
            comment that comes through the linked GitHub issue. Open source means open priorities.
          </p>

          <div className="vote-stats">
            <div className="vote-stat">
              <div className="vote-stat-num">{ROADMAP.length}</div>
              <div className="vote-stat-lbl">Open requests</div>
            </div>
            <div className="vote-stat">
              <div className="vote-stat-num">{totalVotes.toLocaleString()}</div>
              <div className="vote-stat-lbl">Votes cast all-time</div>
            </div>
            <div className="vote-stat">
              <div className="vote-stat-num">{myVotes}</div>
              <div className="vote-stat-lbl">Your votes</div>
            </div>
            <div className="vote-stat">
              <div className="vote-stat-num">14</div>
              <div className="vote-stat-lbl">Shipped since v0.5</div>
            </div>
          </div>
        </div>

        {/* Toolbar */}
        <div className="vote-toolbar">
          <div className="vote-search">
            <svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.4">
              <circle cx="7" cy="7" r="4.5"/><path d="M10.5 10.5l3 3" strokeLinecap="round"/>
            </svg>
            <input
              type="text"
              placeholder="Search features"
              value={query}
              onChange={(e)=>setQuery(e.target.value)}
            />
          </div>

          <div className="vote-filters">
            {[
              ["all", "All", counts.all],
              ["progress", "In progress", counts.progress],
              ["planned", "Planned", counts.planned],
              ["consider", "Under consideration", counts.consider],
              ["later", "Later", counts.later],
            ].map(([id, label, n]) => (
              <button key={id} className={`chip ${filter===id?"active":""}`} onClick={()=>setFilter(id)}>
                {label} <span className="chip-n">{n}</span>
              </button>
            ))}
          </div>

          <div className="vote-sort">
            <span className="muted">Sort</span>
            <button className={`chip ${sort==="votes"?"active":""}`} onClick={()=>setSort("votes")}>Most voted</button>
            <button className={`chip ${sort==="az"?"active":""}`} onClick={()=>setSort("az")}>A–Z</button>
          </div>
        </div>

        <div className="vote-list full">
          {filtered.map((item) => (
            <div key={item.id} className="vote-row">
              <VoteButton item={item} voted={!!votes[item.id]} onToggle={toggle} size="lg"/>
              <div className="vote-row-body">
                <div className="vote-row-head">
                  <h3 className="vote-row-title" dangerouslySetInnerHTML={{__html: item.title}}/>
                  <span className={`badge ${STATUS_META[item.status].cls}`}>
                    <span className="dot"/>{STATUS_META[item.status].label}
                  </span>
                  {item.hot && <span className="hot-tag">Trending</span>}
                </div>
                <p className="vote-row-desc">{item.desc}</p>
                <div className="vote-row-foot">
                  <a className="muted-link" href="https://github.com" target="_blank" rel="noreferrer">
                    <svg width="12" height="12" viewBox="0 0 16 16" fill="currentColor"><path d="M8 0C3.58 0 0 3.58 0 8a8 8 0 005.47 7.59c.4.07.55-.17.55-.38v-1.49c-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82a7.42 7.42 0 014 0c1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48v2.2c0 .21.15.46.55.38A8.01 8.01 0 0016 8c0-4.42-3.58-8-8-8z"/></svg>
                    Issue #{42 + filtered.indexOf(item)*3}
                  </a>
                  <span className="muted">Last updated {["2d", "1w", "3w", "5d", "today", "today", "1m", "1w", "3d", "2m", "1m", "4d"][filtered.indexOf(item) % 12]} ago</span>
                </div>
              </div>
            </div>
          ))}
        </div>

        <div className="vote-footnote">
          Don't see what you want? <a href="https://github.com" target="_blank" rel="noreferrer">Open an issue on GitHub</a> and start the conversation.
        </div>
      </div>
    </main>
  );
}

/* ----- Download section ----- */

function Download({ onNavigate }) {
  return (
    <section id="download" className="download">
      <div className="container download-inner">
        <img src="assets/moonlight-icon.png" width="120" height="120" alt="" className="download-icon"/>
        <span className="eyebrow">Get Moonlight</span>
        <h2>Bring it home.<br/>Free, forever.</h2>
        <p className="lede" style={{textAlign:'center', margin:'18px auto 0'}}>
          Free on the Mac App Store. Universal binary, no account, no telemetry, no nag screens.
          iPhone and iPad companion are <a href="#vote" onClick={(e)=>{e.preventDefault(); onNavigate('vote');}} className="inline-link">on the way</a>.
        </p>

        <div className="download-ctas">
          <a className="btn-mas" href="https://apps.apple.com" target="_blank" rel="noreferrer">
            <svg width="32" height="32" viewBox="0 0 16 16" fill="currentColor" aria-hidden="true">
              <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>
            <span>
              <span className="mas-pre">Download on the</span>
              <span className="mas-title">Mac App Store</span>
            </span>
          </a>
        </div>

        <div className="download-meta">
          <span>macOS 14 Sonoma or later</span>
          <span className="sep">·</span>
          <span>Universal · Apple Silicon &amp; Intel</span>
          <span className="sep">·</span>
          <span>Free · No in-app purchases</span>
        </div>
      </div>
    </section>
  );
}

/* ----- Footer ----- */

function Footer({ onNavigate }) {
  const cols = [
    { h: "Product", links: [
      { l: "Features", on: () => onNavigate('home', 'features') },
      { l: "Showcase", on: () => onNavigate('home', 'library') },
      { l: "Vote on features", on: () => onNavigate('vote') },
      { l: "Get the app", on: () => onNavigate('home', 'download') },
      { l: "Changelog", href: "https://github.com" },
    ]},
    { h: "Open source", links: [
      { l: "GitHub", href: "https://github.com" },
      { l: "Issues", href: "https://github.com" },
      { l: "Discussions", href: "https://github.com" },
      { l: "Contribute", href: "https://github.com" },
      { l: "MIT License", href: "https://github.com" },
    ]},
    { h: "Help", links: [
      { l: "Documentation", href: "#" },
      { l: "Keyboard shortcuts", href: "#" },
      { l: "Supported formats", href: "#" },
      { l: "Privacy", href: "#" },
      { l: "Contact", href: "mailto:hello@moonlight.app" },
    ]},
  ];
  return (
    <footer className="footer">
      <div className="container footer-inner">
        <div className="footer-brand">
          <Logo size={32}/>
          <p className="footer-tag">
            A local-first music player for macOS. Built quietly, in the open.
          </p>
          <div className="footer-social">
            <a href="https://github.com" target="_blank" rel="noreferrer" aria-label="GitHub" className="iconbtn-lg">
              <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor"><path d="M8 0C3.58 0 0 3.58 0 8a8 8 0 005.47 7.59c.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82a7.42 7.42 0 014 0c1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.01 8.01 0 0016 8c0-4.42-3.58-8-8-8z"/></svg>
            </a>
            <a href="#" aria-label="RSS" className="iconbtn-lg">
              <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor"><path d="M2 4a10 10 0 0110 10h-2.5A7.5 7.5 0 002 6.5V4zm0 4a6 6 0 016 6H5.5A3.5 3.5 0 002 10.5V8zm2 4a2 2 0 110 4 2 2 0 010-4z"/></svg>
            </a>
            <a href="mailto:hello@moonlight.app" aria-label="Email" className="iconbtn-lg">
              <svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.3"><rect x="1.5" y="3" width="13" height="10" rx="1.5"/><path d="M2 4l6 5 6-5"/></svg>
            </a>
          </div>
        </div>
        <div className="footer-cols">
          {cols.map((c, i) => (
            <div key={i} className="footer-col">
              <h4>{c.h}</h4>
              <ul>
                {c.links.map((lk, j) => (
                  <li key={j}>
                    {lk.on
                      ? <a href="#" onClick={(e)=>{e.preventDefault(); lk.on();}}>{lk.l}</a>
                      : <a href={lk.href} target={lk.href.startsWith('http') ? "_blank" : undefined} rel="noreferrer">{lk.l}</a>}
                  </li>
                ))}
              </ul>
            </div>
          ))}
        </div>
      </div>
      <div className="container footer-bottom">
        <span>© 2026 Moonlight</span>
        <span className="muted">MIT licensed · Made in the open · No tracking on this site</span>
      </div>
    </footer>
  );
}

window.RoadmapPreview = RoadmapPreview;
window.VotePage = VotePage;
window.Download = Download;
window.Footer = Footer;
window.ROADMAP = ROADMAP;
