// landing-sections.jsx — page sections with asymmetric bento layouts

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

// ─── Icon helpers ──────────────────────────────────────────────────────────
const Icon = {
  Github: (p) => (
    <svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor" {...p}>
      <path d="M12 .5C5.65.5.5 5.65.5 12c0 5.08 3.29 9.39 7.86 10.92.58.1.79-.25.79-.56 0-.27-.01-1-.02-1.96-3.2.7-3.87-1.54-3.87-1.54-.52-1.33-1.28-1.69-1.28-1.69-1.04-.71.08-.7.08-.7 1.15.08 1.76 1.18 1.76 1.18 1.03 1.77 2.7 1.26 3.36.96.1-.75.4-1.26.73-1.55-2.55-.29-5.23-1.28-5.23-5.7 0-1.26.45-2.29 1.18-3.1-.12-.29-.51-1.47.11-3.06 0 0 .97-.31 3.18 1.18a11.1 11.1 0 0 1 5.78 0c2.21-1.49 3.18-1.18 3.18-1.18.62 1.59.23 2.77.11 3.06.74.81 1.18 1.84 1.18 3.1 0 4.43-2.69 5.4-5.25 5.69.41.36.78 1.06.78 2.14 0 1.55-.01 2.8-.01 3.18 0 .31.21.67.8.56 4.57-1.54 7.86-5.84 7.86-10.92C23.5 5.65 18.35.5 12 .5Z"/>
    </svg>
  ),
  Star: (p) => (
    <svg viewBox="0 0 24 24" width="14" height="14" fill="currentColor" {...p}>
      <path d="M12 2l2.95 6.55 7.05.85-5.2 4.95L18.18 22 12 18.27 5.82 22 7.2 14.35 2 9.4l7.05-.85L12 2z"/>
    </svg>
  ),
  Download: (p) => (
    <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <path d="M12 3v12"/><path d="M7 10l5 5 5-5"/><path d="M5 21h14"/>
    </svg>
  ),
  Search: (p) => (
    <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <circle cx="11" cy="11" r="7"/><path d="M21 21l-4.3-4.3"/>
    </svg>
  ),
  Folder: (p) => (
    <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <path d="M3 6.5A1.5 1.5 0 0 1 4.5 5h4l2 2h9A1.5 1.5 0 0 1 21 8.5V18a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V6.5z"/>
    </svg>
  ),
  Play: (p) => (
    <svg viewBox="0 0 24 24" width="14" height="14" fill="currentColor" {...p}>
      <path d="M6 4l14 8-14 8V4z"/>
    </svg>
  ),
  Wish: (p) => (
    <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}>
      <path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"/>
    </svg>
  ),
  Sparkle: (p) => (
    <svg viewBox="0 0 24 24" width="14" height="14" fill="currentColor" {...p}>
      <path d="M12 2l1.6 6.4L20 10l-6.4 1.6L12 18l-1.6-6.4L4 10l6.4-1.6L12 2z"/>
    </svg>
  ),
};

const GITHUB_REPO = "https://github.com/yuma-dev/hynite";
const RELEASE_URL = `${GITHUB_REPO}/releases/latest`;

function formatStars(count) {
  if (!Number.isFinite(count)) return "stars";
  if (count >= 1000) return `${(count / 1000).toFixed(count >= 10000 ? 0 : 1)}k`;
  return `${count}`;
}

function useGithubStars() {
  const [stars, setStars] = useState(null);

  useEffect(() => {
    let cancelled = false;
    fetch("https://api.github.com/repos/yuma-dev/hynite", {
      headers: { Accept: "application/vnd.github+json" },
    })
      .then((response) => response.ok ? response.json() : Promise.reject(new Error("GitHub request failed")))
      .then((data) => {
        if (!cancelled && typeof data.stargazers_count === "number") {
          setStars(data.stargazers_count);
        }
      })
      .catch(() => {
        if (!cancelled) setStars(null);
      });

    return () => { cancelled = true; };
  }, []);

  return stars;
}

function DownloadButton({ className = "" }) {
  return (
    <a className={`btn btn-primary btn-lg download-btn ${className}`} href={RELEASE_URL}>
      <Icon.Download /><span>Download for Windows</span>
      {[1, 2, 3, 4, 5, 6].map((n) => (
        <span key={n} className={`download-star star-${n}`} aria-hidden="true">
          <Icon.Star />
        </span>
      ))}
    </a>
  );
}

// ─── Hero ──────────────────────────────────────────────────────────────────
const HERO_SHOTS = [
  { src: "assets/homescreen.jpg" },
  { src: "assets/bigpicture.jpg" },
  { src: "assets/detailspage.png" },
];

function HeroShotCycle() {
  const [idx, setIdx] = useState(0);
  useEffect(() => {
    const id = setInterval(() => setIdx(v => (v + 1) % HERO_SHOTS.length), 4500);
    return () => clearInterval(id);
  }, []);
  return (
    <div className="hero-shot" aria-hidden="true">
      <div className="shot-frame">
        {HERO_SHOTS.map((s, i) => (
          <img key={s.src} src={s.src} alt="" className={i === idx ? "on" : ""} />
        ))}
        <div className="shot-dots">
          {HERO_SHOTS.map((_, i) => (
            <button key={i} className={`shot-dot ${i === idx ? "on" : ""}`} onClick={() => setIdx(i)} aria-label={`Show hero screenshot ${i + 1}`} />
          ))}
        </div>
      </div>
    </div>
  );
}

function Hero({ layout, onScroll }) {
  const stars = useGithubStars();
  return (
    <section className={`hero hero-${layout}`}>
      <div className="hero-inner">
        <div className="hero-mark" aria-label="Hynite">
          <img src="assets/HyniteLogo.png" alt="" className="hero-logo" />
          <span className="hero-name">YNITE</span>
        </div>
        <p className="hero-sub">
          A game library built around the moment <em>before</em> you press play.
          Steam, local installs, discovery, hydra sources, and Spotlight live in one
          launcher doing the work for you.
        </p>
        <div className="hero-cta">
          <DownloadButton />
          <a className="btn btn-ghost btn-lg" href={GITHUB_REPO}>
            <Icon.Github />
          </a>
        </div>
      </div>

      {layout === "split"   && <HeroShotCycle />}
      {layout === "centered" && (
        <div className="hero-shot-bottom"><HeroShotCycle /></div>
      )}

      <button className="hero-scroll" onClick={onScroll} aria-label="Scroll down">
        <span>scroll</span>
        <svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" strokeWidth="2"><path d="M6 9l6 6 6-6"/></svg>
      </button>
    </section>
  );
}

// ─── Library section (app cover cards) ─────────────────────────────────────
function HyniteCover({ game, onEnter, onLeave, onMove }) {
  const [loaded, setLoaded] = useState(false);

  return (
    <div
      className="game-cover landing-game-cover"
      role="button"
      tabIndex={0}
      aria-label={game.title}
      onPointerEnter={() => onEnter(game)}
      onPointerLeave={onLeave}
      onPointerMove={() => onMove(game, 0)}
      style={{ "--cover-a": game.palette[1], "--cover-b": game.palette[3], "--cover-glow": game.glow }}
    >
      <span className="cover-art">
        <img
          className={loaded ? "cover-img loaded" : "cover-img"}
          src={game.cover}
          alt=""
          loading="lazy"
          decoding="async"
          onLoad={() => setLoaded(true)}
        />
        <span className="cover-reveal">
          <span className="cover-logo">
            <img className="cover-logo-img" src={game.logo} alt={game.title} loading="lazy" decoding="async" />
          </span>
          <button className={game.action === "Play" ? "cover-action cover-action-play" : "cover-action cover-action-details"} type="button" aria-label={`${game.action} ${game.title}`}>
            {game.action === "Play" ? <Icon.Play width="22" height="22" /> : <span className="cover-info-mark">i</span>}
          </button>
          <span className="cover-playtime">{game.activity} - {game.playtime}</span>
        </span>
      </span>
      <span className="cover-state-pill">{game.state}</span>
    </div>
  );
}

function LibrarySection({ onHoverGame, onLeaveGame, onMoveGame }) {
  return (
    <section className="sec sec-library" id="library">
      <div className="sec-eyebrow"><Icon.Folder /> auto-discovery</div>
      <div className="bento bento-library">
        <div className="bento-copy">
          <h2 className="sec-title">It searches the games for you.</h2>
          <p className="sec-sub">
            You add your Folders, and Hynite quietly does the work of finding executables, reading manifests, and building your library.
          </p>
          <div className="local-map-panel">
            <div className="local-map-line">
              <strong>Steam libraries</strong>
              <span>412 games</span>
            </div>
            <div className="local-map-line">
              <strong>Local folders</strong>
              <span>68 games</span>
            </div>
            <div className="folder-tree">
              <strong>C:\Games</strong>
              <span>D:\SteamLibrary\steamapps\common</span>
              <span>E:\GOG Galaxy\Games</span>
              <span>F:\Archive</span>
            </div>
          </div>
        </div>

        <div className="bento-grid">
          <div className="library-covers">
            {GAMES.slice(0, 8).map(g => (
              <HyniteCover key={g.id} game={g}
                onEnter={onHoverGame}
                onLeave={onLeaveGame}
                onMove={onMoveGame}
              />
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

// ─── Spotlight section (split with big keys) ───────────────────────────────
function SpotlightRows({ results, selectedIndex, setSelectedIndex, onActivate }) {
  return (
    <>
      {results.map((result, index) => (
        <button
          key={result.id}
          type="button"
          className={index === selectedIndex ? "spotlight-row active" : "spotlight-row"}
          onPointerEnter={() => setSelectedIndex(index)}
          onClick={() => onActivate(result)}
          role="option"
          aria-selected={index === selectedIndex}
        >
          <span className="spotlight-icon has-image has-cover">
            <img src={result.icon} alt="" draggable={false} />
          </span>
          <span className="spotlight-copy">
            <strong>{result.title}</strong>
            <em>{result.state} / {result.source}</em>
          </span>
          <span className="spotlight-action">{result.action}</span>
        </button>
      ))}
    </>
  );
}

function SpotlightPanel({ results, selectedIndex, setSelectedIndex, q, setQ, inputRef, launchHandoff, onActivate }) {
  if (launchHandoff) {
    return (
      <section className="spotlight-panel launching">
        <div className="spotlight-launch-handoff">
          <div className="spotlight-launch-identity">
            {launchHandoff.logo ? (
              <img className="spotlight-launch-logo" src={launchHandoff.logo} alt="" draggable={false} />
            ) : (
              <h1>{launchHandoff.title}</h1>
            )}
            <span className="spotlight-launch-line"><span /></span>
          </div>
        </div>
      </section>
    );
  }

  return (
    <section
      className="spotlight-panel"
      onKeyDown={(event) => {
        if (event.key === "ArrowDown") {
          event.preventDefault();
          setSelectedIndex(Math.min(results.length - 1, selectedIndex + 1));
        } else if (event.key === "ArrowUp") {
          event.preventDefault();
          setSelectedIndex(Math.max(0, selectedIndex - 1));
        } else if (event.key === "Enter") {
          event.preventDefault();
          onActivate(results[selectedIndex]);
        }
      }}
    >
      <label className="spotlight-search">
        <Icon.Search />
        <input
          ref={inputRef}
          value={q}
          onChange={(event) => setQ(event.currentTarget.value)}
          placeholder="Search games"
        />
      </label>
      <div className="spotlight-list" role="listbox" aria-label="Games">
        <SpotlightRows results={results} selectedIndex={selectedIndex} setSelectedIndex={setSelectedIndex} onActivate={onActivate} />
        {results.length === 0 ? <div className="spotlight-empty">No games found</div> : null}
      </div>
      <footer className="spotlight-footer">
        <span>Enter to launch, arrows to navigate</span>
      </footer>
    </section>
  );
}

function SpotlightSection({ onPaletteShift }) {
  const [q, setQ] = useState("");
  const [sel, setSel] = useState(0);
  const demoInputRef = useRef(null);
  const [launchHandoff, setLaunchHandoff] = useState(null);

  const results = useMemo(() => {
    const term = q.trim().toLowerCase();
    if (!term) return SPOTLIGHT.slice(0, 5);
    return SPOTLIGHT.filter(g =>
      g.title.toLowerCase().includes(term) ||
      g.studio.toLowerCase().includes(term) ||
      (g.tag || "").toLowerCase().includes(term)
    ).slice(0, 6);
  }, [q]);

  useEffect(() => { setSel(0); }, [q]);

  useEffect(() => {
    const r = results[sel];
    if (!r) return;
    const known = GAMES.find(g => g.id === r.id);
    if (known) onPaletteShift(known);
  }, [sel, results, onPaletteShift]);

  const activate = useCallback((result) => {
    if (!result) return;
    setLaunchHandoff(result);
    window.setTimeout(() => setLaunchHandoff(null), 1600);
  }, []);

  return (
    <section className="sec sec-spotlight" id="spotlight">
      <div className="sec-eyebrow"><Icon.Sparkle /> spotlight</div>
      <div className="bento bento-spotlight">
        <div className="bento-copy">
          <h2 className="sec-title">The fastest way to start your games</h2>
          <p className="sec-sub">
            The app doesn't need to be open. Hit the hotkey from your desktop. Type a few letters, hit enter.
            You're in.
          </p>
          <div className="keys-stack">
            <kbd className="bigkey">Alt</kbd>
            <span className="key-plus">+</span>
            <kbd className="bigkey">Space</kbd>
          </div>
        </div>

        <div className="bento-demo">
          <div className="spotlight-demo-shell">
            <SpotlightPanel
              results={results.slice(0, 6)}
              selectedIndex={sel}
              setSelectedIndex={setSel}
              q={q}
              setQ={setQ}
              inputRef={demoInputRef}
              launchHandoff={launchHandoff}
              onActivate={activate}
            />
          </div>
        </div>
      </div>
    </section>
  );
}

// ─── Sources & wishlist section ────────────────────────────────────────────
const WISHLIST_DAYS = [
  { label: "Past 2 weeks", month: true, items: [GAMES[7], GAMES[10], GAMES[2], GAMES[11]] },
  { label: "Today", items: [GAMES[1], GAMES[4], GAMES[0]] },
  { label: "May 27", items: [GAMES[8], GAMES[5], GAMES[3]] },
  { label: "June", month: true, items: [] },
  { label: "Jun 06", items: [GAMES[9], GAMES[6], GAMES[3], GAMES[2]] },
];

const ACTIVE_SOURCES = [
  { name: "Hydra community", entries: "2,184", url: "https://hydra.example/source.json", updated: "updated today" },
  { name: "Steam wishlist", entries: "118", url: "steam profile", updated: "updated 1m ago" },
  { name: "GOG freebies", entries: "42", url: "manual import", updated: "updated 12m ago" },
];

function CalendarCover({ game, available }) {
  const [loaded, setLoaded] = useState(false);
  return (
    <div className="game-cover calendar-cover" role="button" tabIndex={0} style={{ "--cover-a": game.palette[1], "--cover-b": game.palette[3], "--cover-glow": game.glow }}>
      <span className="cover-art">
        <img
          className={loaded ? "cover-img loaded" : "cover-img"}
          src={game.cover}
          alt=""
          loading="lazy"
          decoding="async"
          onLoad={() => setLoaded(true)}
        />
        <span className="cover-reveal">
          <span className="cover-logo">
            <img className="cover-logo-img" src={game.logo} alt={game.title} loading="lazy" decoding="async" />
          </span>
          <button className="cover-action cover-action-details" type="button" aria-label={`Open ${game.title}`}>
            <span className="cover-info-mark">i</span>
          </button>
          <span className="cover-playtime">{game.tag}</span>
        </span>
      </span>
      {available ? <span className="wishlist-source-pill available">Source</span> : <span className="wishlist-source-pill missing">Missing</span>}
    </div>
  );
}

function SourcesSection() {
  return (
    <section className="sec sec-sources" id="sources">
      <div className="sec-eyebrow"><Icon.Wish /> sources &amp; wishlist</div>
      <div className="bento bento-sources">
        <div className="bento-copy">
          <h2 className="sec-title">Your wishlist taken with you.</h2>
          <p className="sec-sub">
            Add Hydra sources, community-shared libraries, demo collections,
            freebie trackers. Hynite cross-references them with your Steam wishlist
            and quietly tells you when something you wanted shows up somewhere to download.
          </p>
        </div>

        <div className="wishlist-calendar src-card-wishlist">
          <div className="wishlist-day-list">
            {WISHLIST_DAYS.map((row, rowIndex) => (
              <section key={row.label} className={row.items.length > 0 ? "wishlist-day-row has-items" : "wishlist-day-row"}>
                {row.month ? (
                  <div className="wishlist-month-marker">
                    <span>{row.label}</span>
                  </div>
                ) : (
                  <div className="wishlist-day-heading">
                    <span>{row.label}</span>
                  </div>
                )}
                {row.items.length > 0 ? (
                  <div className="wishlist-mini-grid wishlist-day-grid">
                    {row.items.map((game, gameIndex) => (
                      <CalendarCover key={`${row.label}-${game.id}`} game={game} available={(rowIndex + gameIndex) % 2 === 0} />
                    ))}
                  </div>
                ) : null}
              </section>
            ))}
          </div>
        </div>

        <section className="source-active src-card-sources">
          <div className="section-head">
            <h2>Active sources</h2>
          </div>
          <div className="source-list">
            {ACTIVE_SOURCES.map((source) => (
              <div className="source-card" key={source.name}>
                <div className="source-row">
                  <div className="source-row-info">
                    <strong>{source.name}</strong>
                    <span>{source.entries} entries · <span className="source-url">{source.url}</span> · {source.updated}</span>
                  </div>
                  <div className="source-row-actions">
                    <button className="icon-action" type="button">Refresh</button>
                    <button className="icon-action danger" type="button" aria-label={`Remove ${source.name}`}>×</button>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </section>

      </div>
    </section>
  );
}

// ─── Install / Footer ──────────────────────────────────────────────────────
function InstallFooter() {
  const stars = useGithubStars();
  return (
    <footer className="foot" id="install">
      <div className="foot-cta">
        <div className="foot-mark" aria-label="Hynite">
          <img src="assets/HyniteLogo.png" alt="" />
        </div>
        <h2 className="foot-title">Organize your Library.</h2>
        <div className="foot-buttons">
          <DownloadButton />
          <a className="btn btn-ghost btn-lg" href={GITHUB_REPO}>
            <Icon.Github />
          </a>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, {
  Hero, LibrarySection, SpotlightSection, SourcesSection, InstallFooter, Icon,
});
