/* Download + How-to + FAQ + Contact */

function DownloadPage({ go }) {
  const [dl, setDl] = React.useState(null); // { name, sizeMb, t }
  const installer = useReleaseAsset(RELEASE_CONFIG.installerPattern);
  const changelog = useReleaseChangelog();

  // Real download when the release lookup worked; otherwise send the
  // visitor to the GitHub releases page rather than fake anything.
  const handleDownload = (asset) => {
    if (asset && asset.url) {
      triggerDownload(asset.url, asset.name);
      // Still show the "complete" state so the user gets confirmation copy.
      setDl({ name: asset.name, sizeMb: asset.sizeMb, kind: "installer", real: true });
    } else {
      window.open(`https://github.com/${RELEASE_CONFIG.repo}/releases/latest`, "_blank", "noopener");
    }
  };

  // Display version/size straight from the live release; say nothing
  // rather than something stale while it loads (or if GitHub is down).
  const displayVersion = installer.version;
  const displaySize    = installer.sizeMb;
  const versionLine = [displayVersion, displaySize && `${displaySize} MB`, "latest release"]
    .filter(Boolean).join(" · ");

  return (
    <div className="page" data-screen-label="03 Download">
      <section className="section" style={{ paddingTop: 64 }}>
        <div className="container" style={{ maxWidth: 1040 }}>
          <div style={{ marginBottom: 48 }}>
            <div className="eyebrow" style={{ marginBottom: 16 }}>Free download · Windows</div>
            <h1 style={{ marginBottom: 22 }}>Get My Crafty Stash on your computer.</h1>
            <p className="lead" style={{ maxWidth: 620 }}>
              One download. No installer wizard tricks, no bundled junk, no
              account required. Just the app.
            </p>
          </div>

          <div className="card bordered" style={{ padding: 36, marginBottom: 24 }}>
            <div style={{ display: "grid", gridTemplateColumns: "auto 1fr auto", gap: 28, alignItems: "center" }} className="dl-card">
              <div style={{
                width: 72, height: 72, background: "var(--ink)",
                borderRadius: 12, display: "grid", placeItems: "center",
                color: "var(--paper)", fontSize: 28,
              }}>
                <svg width="32" height="32" viewBox="0 0 24 24" fill="currentColor"><path d="M0 3.449L9.75 2.1v9.451H0m10.949-9.602L24 0v11.4H10.949M0 12.6h9.75v9.451L0 20.699M10.949 12.6H24V24l-13.051-1.851"/></svg>
              </div>
              <div>
                <h3 style={{ fontSize: "1.4rem", marginBottom: 6 }}>My Crafty Stash for Windows</h3>
                <div className="kicker">{installer.loading ? "checking latest release…" : versionLine}</div>
              </div>
              <button
                className="btn btn-lg"
                disabled={installer.loading}
                onClick={() => handleDownload(installer)}
              >
                <DownloadIcon /> {installer.loading ? "Loading…" : "Download installer"}
              </button>
            </div>
            <hr className="divider" />
            <div style={{ display: "grid", gridTemplateColumns: "repeat(6, 1fr)", gap: 24 }} className="specs-row">
              {[
                ["System", "Windows 10 / 11"],
                ["Architecture", "64-bit"],
                ["Disk space", "~80 MB"],
                ["RAM", "2 GB"],
                ["Internet", "Not required"],
                ["Account", "Not required"],
              ].map(([k, v]) => (
                <div key={k}>
                  <div className="kicker" style={{ marginBottom: 6 }}>{k}</div>
                  <div style={{ fontWeight: 500, fontSize: "0.95rem" }}>{v}</div>
                </div>
              ))}
            </div>
          </div>

          <div className="section-head" style={{ marginTop: 80 }}>
            <div className="eyebrow">Changelog</div>
            <h2>What's new{changelog.version ? ` in ${changelog.version}` : ""}</h2>
          </div>
          <div style={{ borderTop: "1px solid var(--line-soft)" }}>
            {changelog.loading && (
              <div style={{ padding: "18px 0", color: "var(--ink-3)", fontSize: "0.95rem" }}>
                Loading the latest release notes…
              </div>
            )}
            {!changelog.loading && changelog.bullets.length === 0 && (
              <div style={{ padding: "18px 0", fontSize: "0.95rem" }}>
                <a href={`https://github.com/${RELEASE_CONFIG.repo}/releases`}
                   target="_blank" rel="noopener noreferrer"
                   style={{ color: "var(--accent-deep)" }}>
                  See the release notes on GitHub →
                </a>
              </div>
            )}
            {changelog.bullets.map((c, i) => (
              <div key={i} style={{
                display: "grid", gridTemplateColumns: "100px 1fr",
                gap: 24, padding: "18px 0",
                borderBottom: "1px solid var(--line-soft)",
              }}>
                <span className="kicker" style={{ color: c.tag === "new" ? "var(--accent-deep)" : "var(--ink-3)" }}>{c.tag}</span>
                <span style={{ fontSize: "0.97rem" }}>{c.text}</span>
              </div>
            ))}
          </div>
        </div>
      </section>
      {dl && <DownloadDialog file={dl} onClose={() => setDl(null)} />}
    </div>
  );
}

function AltCard({ tag, title, body, cta, onClick }) {
  return (
    <div className="card" style={{ padding: 28 }}>
      <div className="kicker" style={{ marginBottom: 12, color: "var(--accent-deep)" }}>{tag}</div>
      <h3 style={{ marginBottom: 10, fontSize: "1.2rem" }}>{title}</h3>
      <p style={{ color: "var(--ink-2)", margin: "0 0 18px", fontSize: "0.95rem" }}>{body}</p>
      <button className="btn secondary" onClick={onClick}>{cta}</button>
    </div>
  );
}

function DownloadDialog({ file, onClose }) {
  // For real downloads (file.real === true), the browser is doing the
  // actual download — we just show the "complete" confirmation right away.
  const [pct, setPct] = React.useState(file.real ? 100 : 0);
  const [done, setDone] = React.useState(!!file.real);
  const [speed, setSpeed] = React.useState(2.4); // MB/s

  React.useEffect(() => {
    if (file.real) return; // skip simulation
    setPct(0); setDone(false);
    let p = 0;
    const id = setInterval(() => {
      // accelerating curve
      const inc = 1 + Math.random() * 4 + p * 0.04;
      p = Math.min(100, p + inc);
      setPct(p);
      setSpeed(1.8 + Math.random() * 1.6);
      if (p >= 100) {
        clearInterval(id);
        setTimeout(() => setDone(true), 220);
      }
    }, 90);
    return () => clearInterval(id);
  }, [file.name, file.real]);

  React.useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    return () => {
      window.removeEventListener("keydown", onKey);
      document.body.style.overflow = "";
    };
  }, [onClose]);

  const downloaded = (file.sizeMb * pct / 100);
  const remaining = file.sizeMb - downloaded;
  const eta = Math.max(0, remaining / speed);

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal-card" onClick={(e) => e.stopPropagation()} style={{ width: "min(540px, 100%)", padding: 32 }}>
        {!done ? (
          <>
            <div className="kicker" style={{ marginBottom: 8 }}>Downloading</div>
            <div style={{ fontFamily: "var(--mono-font)", fontSize: "1rem", marginBottom: 24, wordBreak: "break-all" }}>
              {file.name}
            </div>
            <div style={{
              height: 10, background: "var(--paper-2)", borderRadius: 99,
              overflow: "hidden", marginBottom: 14,
              border: "1px solid var(--line-soft)",
            }}>
              <div style={{
                height: "100%", width: `${pct}%`,
                background: "var(--accent)",
                transition: "width .12s linear",
              }} />
            </div>
            <div style={{ display: "flex", justifyContent: "space-between", fontSize: "0.88rem", color: "var(--ink-2)", fontFamily: "var(--mono-font)" }}>
              <span>{downloaded.toFixed(1)} / {file.sizeMb} MB</span>
              <span>{speed.toFixed(1)} MB/s · {eta < 1 ? "<1s" : `${Math.ceil(eta)}s left`}</span>
            </div>
            <div style={{ marginTop: 26, display: "flex", justifyContent: "flex-end", gap: 10 }}>
              <button className="btn secondary" onClick={onClose}>Cancel</button>
            </div>
          </>
        ) : (
          <>
            <div style={{
              width: 56, height: 56, borderRadius: 99,
              background: "var(--accent-soft)", color: "var(--accent-deep)",
              display: "grid", placeItems: "center", marginBottom: 18,
            }}>
              <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                <path d="M5 13l4 4L19 7"/>
              </svg>
            </div>
            <h3 style={{ marginBottom: 10 }}>{file.real ? "Download started." : "Download complete."}</h3>
            <p style={{ color: "var(--ink-2)", margin: "0 0 8px", fontSize: "0.97rem" }}>
              <b style={{ fontFamily: "var(--mono-font)", fontWeight: 500 }}>{file.name}</b>
            </p>
            <p style={{ color: "var(--ink-2)", margin: "0 0 22px", fontSize: "0.95rem", lineHeight: 1.55 }}>
              {file.real
                ? (file.kind === "portable"
                    ? "Check your Downloads folder. Unzip it anywhere — no installer needed. Run MyCraftyStash.exe to start."
                    : "Check your Downloads folder. Open the installer and follow the prompts. The app will start automatically when it's done.")
                : file.kind === "portable"
                  ? "Unzip it anywhere — no installer needed. Run MyCraftyStash.exe to start."
                  : file.kind === "legacy"
                    ? "Open the installer and follow the prompts. v0.9.6 will live in its own folder, separate from any other version."
                    : "Open the installer and follow the prompts. Takes about 30 seconds. The app will start automatically when it's done."}
            </p>
            <div style={{
              padding: "14px 16px",
              background: "var(--paper-2)",
              border: "1px solid var(--line-soft)",
              borderRadius: 10,
              fontSize: "0.88rem", color: "var(--ink-2)", lineHeight: 1.55,
              marginBottom: 22,
            }}>
              <b style={{ color: "var(--ink)" }}>Heads up:</b> Windows SmartScreen may show a "Don't run" warning the first time. Click <em>More info → Run anyway</em>. The installer is signed but new builds take a few weeks to earn full Microsoft reputation.
            </div>
            <div style={{ display: "flex", justifyContent: "flex-end", gap: 10 }}>
              <button className="btn" onClick={onClose}>Got it</button>
            </div>
          </>
        )}
      </div>
    </div>
  );
}

function HowToPage({ go }) {
  // To stream a real video, paste its YouTube ID into `yt` (the part after
  // youtu.be/ or ?v= in a YouTube URL). Empty `yt` shows a "coming soon"
  // placeholder so the page works before every clip is recorded.
  const videos = [
    { yt: "aYvw46oe9qU", c: "var(--accent-soft)", title: "Your home dashboard",            duration: "2:30", chapter: "Getting started" },
    { yt: "",            c: "var(--mint)",        title: "Building your inventory",         duration: "3:30", chapter: "Getting started" },
    { yt: "",            c: "var(--sky)",         title: "Settings, set up your way",       duration: "3:00", chapter: "Getting started" },
    { yt: "",            c: "var(--butter)",      title: "Saving your projects",            duration: "3:00", chapter: "Making cards" },
    { yt: "",            c: "var(--sky)",         title: "The Card Build Wizard",           duration: "3:30", chapter: "Making cards" },
    { yt: "",            c: "var(--lilac)",       title: "Color Match",                     duration: "2:30", chapter: "Making cards" },
    { yt: "",            c: "var(--mint)",        title: "Sentiment Search: find the words", duration: "2:30", chapter: "Making cards" },
    { yt: "",            c: "var(--accent-soft)", title: "Your wishlist",                   duration: "3:00", chapter: "Planning ahead" },
    { yt: "",            c: "var(--lilac)",       title: "Cloud Sync: your stash on your phone", duration: "4:00", chapter: "Planning ahead" },
  ];
  const chapters = ["Getting started", "Making cards", "Planning ahead"];
  const [active, setActive] = React.useState("All");
  const [playing, setPlaying] = React.useState(null);
  const filtered = active === "All" ? videos : videos.filter(v => v.chapter === active);

  return (
    <div className="page" data-screen-label="04 How to">
      <section className="section" style={{ paddingTop: 64 }}>
        <div className="container">
          <div style={{ marginBottom: 48 }}>
            <div className="eyebrow" style={{ marginBottom: 16 }}>How to</div>
            <h1 style={{ marginBottom: 22 }}>Short videos. Real fast learning.</h1>
            <p className="lead" style={{ maxWidth: 640 }}>
              Each clip is under six minutes and shows you one thing only.
              Watch what you need, skip what you don't.
            </p>
          </div>

          <div style={{ display: "flex", gap: 6, flexWrap: "wrap", marginBottom: 36, paddingBottom: 20, borderBottom: "1px solid var(--line-soft)" }}>
            <ChapterChip label="All" count={videos.length} active={active === "All"} onClick={() => setActive("All")} />
            {chapters.map(c => (
              <ChapterChip
                key={c}
                label={c}
                count={videos.filter(v => v.chapter === c).length}
                active={active === c}
                onClick={() => setActive(c)}
              />
            ))}
          </div>

          <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(280px, 1fr))", gap: 20 }}>
            {filtered.map((v) => (
              <VideoCard
                key={v.title}
                {...v}
                index={videos.indexOf(v)}
                onPlay={() => setPlaying({ ...v, index: videos.indexOf(v) })}
              />
            ))}
          </div>
        </div>
      </section>
      {playing && (
        <VideoModal
          video={playing}
          videos={videos}
          onClose={() => setPlaying(null)}
          onPlay={(v) => setPlaying(v)}
        />
      )}
    </div>
  );
}

function ChapterChip({ label, count, active, onClick }) {
  return (
    <button onClick={onClick} style={{
      padding: "8px 14px",
      background: active ? "var(--ink)" : "transparent",
      color: active ? "var(--paper)" : "var(--ink-2)",
      border: "1px solid " + (active ? "var(--ink)" : "var(--line-soft)"),
      borderRadius: 999,
      fontSize: "0.88rem", fontWeight: 500,
      fontFamily: "inherit", cursor: "pointer",
      display: "inline-flex", alignItems: "center", gap: 8,
    }}>
      {label}
      <span style={{ opacity: active ? 0.7 : 0.5, fontFamily: "var(--mono-font)", fontSize: "0.78rem" }}>{count}</span>
    </button>
  );
}

function VideoCard({ yt, c, title, duration, chapter, index, onPlay }) {
  const [hover, setHover] = React.useState(false);
  const thumb = yt ? `https://i.ytimg.com/vi/${yt}/hqdefault.jpg` : null;
  return (
    <div
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      onClick={onPlay}
      style={{
        border: "1px solid " + (hover ? "var(--ink)" : "var(--line-soft)"),
        borderRadius: 12,
        overflow: "hidden", background: "var(--paper)",
        transition: "border-color .15s",
        cursor: "pointer",
      }}
    >
      <div style={{
        position: "relative", aspectRatio: "16 / 10",
        background: thumb ? `#000 center/cover no-repeat url(${thumb})` : c,
        borderBottom: "1px solid var(--line-soft)",
        display: "grid", placeItems: "center",
      }}>
        <div style={{
          width: 48, height: 48, borderRadius: "50%",
          background: "var(--paper)",
          display: "grid", placeItems: "center",
          boxShadow: "0 4px 14px rgba(0,0,0,.15)",
          transform: hover ? "scale(1.08)" : "scale(1)",
          transition: "transform .15s",
        }}>
          <svg width="16" height="16" viewBox="0 0 24 24" fill="var(--ink)" style={{ marginLeft: 2 }}>
            <path d="M8 5v14l11-7z"/>
          </svg>
        </div>
        <div style={{
          position: "absolute", bottom: 12, right: 12,
          padding: "3px 8px", background: "var(--ink)", color: "var(--paper)",
          borderRadius: 6, fontFamily: "var(--mono-font)",
          fontSize: 11, fontWeight: 500,
        }}>{duration}</div>
        <div className="kicker" style={{
          position: "absolute", top: 12, left: 12,
          padding: "3px 8px", background: "var(--paper)",
          borderRadius: 6,
        }}>{String(index + 1).padStart(2, "0")}</div>
      </div>
      <div style={{ padding: "14px 16px" }}>
        <div className="kicker" style={{ marginBottom: 6 }}>{chapter}</div>
        <div style={{ fontSize: "1rem", fontWeight: 500, lineHeight: 1.35 }}>{title}</div>
      </div>
    </div>
  );
}

function VideoModal({ video, videos, onClose, onPlay }) {
  const [loaded, setLoaded] = React.useState(false);

  React.useEffect(() => {
    const onKey = (e) => {
      if (e.key === "Escape") onClose();
    };
    window.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    return () => {
      window.removeEventListener("keydown", onKey);
      document.body.style.overflow = "";
    };
  }, [onClose]);

  // Reset to facade whenever the video changes.
  React.useEffect(() => { setLoaded(false); }, [video.yt]);

  const idx = video.index;
  const next = videos[idx + 1];
  const prev = videos[idx - 1];
  const thumb = video.yt ? `https://i.ytimg.com/vi/${video.yt}/maxresdefault.jpg` : null;
  const ytUrl = video.yt ? `https://youtu.be/${video.yt}` : null;
  const origin = (typeof window !== "undefined" && window.location && window.location.origin && window.location.origin !== "null")
    ? `&origin=${encodeURIComponent(window.location.origin)}`
    : "";

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div
        onClick={(e) => e.stopPropagation()}
        style={{
          background: "var(--paper)",
          borderRadius: 14,
          width: "min(960px, 100%)",
          overflow: "hidden",
          boxShadow: "0 30px 80px rgba(0,0,0,.45)",
          border: "1px solid var(--line)",
        }}
      >
        {/* Header */}
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 16, padding: "14px 18px", borderBottom: "1px solid var(--line-soft)" }}>
          <div style={{ minWidth: 0 }}>
            <div className="kicker" style={{ marginBottom: 2 }}>
              {String(idx + 1).padStart(2, "0")} · {video.chapter}
            </div>
            <div style={{ fontWeight: 600, fontSize: "1.05rem", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
              {video.title}
            </div>
          </div>
          <button
            onClick={onClose}
            aria-label="Close"
            style={{
              flexShrink: 0,
              width: 36, height: 36, borderRadius: 99,
              background: "var(--paper)", border: "1px solid var(--line-soft)",
              cursor: "pointer", fontSize: 18,
              display: "grid", placeItems: "center",
              fontFamily: "inherit",
            }}
          >×</button>
        </div>

        {/* Stage */}
        <div style={{
          position: "relative",
          aspectRatio: "16 / 9",
          background: video.yt ? "#000" : video.c,
          overflow: "hidden",
        }}>
          {video.yt && loaded ? (
            <iframe
              key={video.yt}
              src={`https://www.youtube-nocookie.com/embed/${video.yt}?autoplay=1&rel=0&modestbranding=1&playsinline=1${origin}`}
              title={video.title}
              style={{ position: "absolute", inset: 0, width: "100%", height: "100%", border: 0 }}
              allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
              allowFullScreen
            />
          ) : video.yt ? (
            // Facade: thumbnail + play button. Click loads the real player.
            <button
              onClick={() => setLoaded(true)}
              aria-label={`Play ${video.title}`}
              style={{
                position: "absolute", inset: 0, width: "100%", height: "100%",
                border: 0, cursor: "pointer", padding: 0,
                background: thumb ? `#000 center/cover no-repeat url(${thumb})` : "#000",
              }}
            >
              <span style={{
                position: "absolute", inset: 0,
                background: "linear-gradient(transparent, rgba(0,0,0,.25))",
              }} />
              <span style={{
                position: "absolute", top: "50%", left: "50%",
                transform: "translate(-50%,-50%)",
                width: 72, height: 72, borderRadius: "50%",
                background: "var(--accent)",
                display: "grid", placeItems: "center",
                boxShadow: "0 8px 28px rgba(0,0,0,.4)",
              }}>
                <svg width="26" height="26" viewBox="0 0 24 24" fill="var(--paper)" style={{ marginLeft: 4 }}><path d="M8 5v14l11-7z"/></svg>
              </span>
            </button>
          ) : (
            // No YouTube ID yet — styled "coming soon" placeholder.
            <div style={{ position: "absolute", inset: 0, display: "grid", placeItems: "center", textAlign: "center", padding: 32 }}>
              <div>
                <div style={{
                  width: 56, height: 56, borderRadius: "50%",
                  background: "var(--paper)", margin: "0 auto 18px",
                  display: "grid", placeItems: "center",
                  boxShadow: "0 4px 14px rgba(0,0,0,.15)",
                }}>
                  <svg width="20" height="20" viewBox="0 0 24 24" fill="var(--ink)" style={{ marginLeft: 3 }}><path d="M8 5v14l11-7z"/></svg>
                </div>
                <div style={{
                  fontFamily: "var(--display-font)",
                  fontSize: "1.6rem", fontWeight: 700,
                  lineHeight: 1.15, maxWidth: 520, margin: "0 auto 8px",
                  color: "var(--ink)",
                }}>
                  {video.title}
                </div>
                <div className="kicker">This tutorial streams here once published</div>
              </div>
            </div>
          )}
        </div>

        {/* Footer: nav */}
        <div style={{ padding: "18px 22px", display: "flex", justifyContent: "space-between", alignItems: "center", gap: 16, flexWrap: "wrap" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 16, flexWrap: "wrap" }}>
            <div className="kicker">{video.duration} · {idx + 1} of {videos.length}</div>
            {ytUrl && (
              <a
                href={ytUrl}
                target="_blank"
                rel="noopener noreferrer"
                style={{ display: "inline-flex", alignItems: "center", gap: 6, color: "var(--accent-deep)", textDecoration: "none", fontSize: "0.88rem", fontWeight: 500 }}
              >
                <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="M21.58 7.19c-.23-.86-.91-1.54-1.77-1.77C18.25 5 12 5 12 5s-6.25 0-7.81.42c-.86.23-1.54.91-1.77 1.77C2 8.75 2 12 2 12s0 3.25.42 4.81c.23.86.91 1.54 1.77 1.77C5.75 19 12 19 12 19s6.25 0 7.81-.42c.86-.23 1.54-.91 1.77-1.77C22 15.25 22 12 22 12s0-3.25-.42-4.81zM10 15V9l5.2 3-5.2 3z"/></svg>
                Watch on YouTube
              </a>
            )}
          </div>
          <div style={{ display: "flex", gap: 8 }}>
            <button
              className="btn secondary"
              disabled={!prev}
              onClick={() => prev && onPlay({ ...prev, index: idx - 1 })}
              style={{ opacity: prev ? 1 : 0.4 }}
            >← Previous</button>
            <button
              className="btn"
              disabled={!next}
              onClick={() => next && onPlay({ ...next, index: idx + 1 })}
              style={{ opacity: next ? 1 : 0.4 }}
            >Next video →</button>
          </div>
        </div>
      </div>
    </div>
  );
}

function FAQPage({ go }) {
  const faqs = [
    { q: "Is it really free?", a: "The desktop app is free and always will be. Down the road there may be a small subscription fee for the optional view-your-stash-online feature, purely to help offset the server costs. Everything on your PC stays free.", cat: "Pricing" },
    { q: "Where is my data stored?", a: "On your computer, in a small database file (inventory.db) in the app's folder. Nothing leaves your machine unless you turn on the optional Cloud Sync. The app doesn't even need an internet connection.", cat: "Data" },
    { q: "How do I back up my stash?", a: "Copy inventory.db and settings.db from the app's folder (Settings shows you where it lives) somewhere safe — Dropbox, OneDrive, an external drive, a USB stick. Those two files are your entire collection and all your preferences.", cat: "Data" },
    { q: "Can I use it on a Mac or iPad?", a: "No. v1 is Windows only, and nothing else is planned right now.", cat: "Compatibility" },
    { q: "What can I track in my inventory?", a: "Every stamp, die, stencil, ink, and sheet of cardstock you own — with photos, item numbers, themes, storage locations, stock levels, and what you paid. Add items by hand or look them up from your favorite retailers.", cat: "Features" },
    { q: "What is the Card Build Wizard?", a: "A step-by-step builder that walks you through a card layer by layer — base, mats, focal point, sentiments, even the inside — and records every supply you used, so each project remembers exactly how you made it.", cat: "Features" },
    { q: "How does Color Match know what coordinates?", a: "The color data comes straight from information the companies share with the developer, so the matches reflect the real products. The app compares the color you pick against that data for the cardstock and inks in your inventory and sorts by closeness.", cat: "Features" },
    { q: "What is Sentiment Search?", a: "Clip the sentiments from your stamp set photos once, and from then on you can search every sentiment you own by its words — type 'thinking of you' and see exactly which sets have it.", cat: "Features" },
    { q: "What does the Wishlist do?", a: "Keeps your want-lists with prices and links. Paste a product URL (or import a whole Taylored Expressions wishlist) and items drop in automatically — and when you buy one, it moves straight into your inventory.", cat: "Features" },
    { q: "What is the Envelope & Box tool?", a: "A built-in calculator that gives you cutting and scoring dimensions for a custom envelope or box sized to whatever card you just made.", cat: "Features" },
    { q: "What is Cloud Sync?", a: "An optional feature that uploads a read-only copy of your stash so you can browse it from your phone — in the craft store, at a crop, anywhere. Your desktop app stays the source of truth.", cat: "Features" },
    { q: "What if my computer dies?", a: "If you've been backing up inventory.db, just install My Crafty Stash on the new machine and drop your backup into the app's folder. You're back up and running in under a minute.", cat: "Data" },
    { q: "Is the source code available?", a: "No, and there are no plans to open-source it. Your data is never locked in, though — it lives in a standard SQLite database file on your machine.", cat: "About" },
    { q: "Can I request a feature?", a: "Please do. Use the contact form. Most of the recent features (including Color Match) came directly from user requests.", cat: "About" },
  ];
  const [q, setQ] = React.useState("");
  const [open, setOpen] = React.useState(0);
  const [cat, setCat] = React.useState("All");
  const cats = ["All", ...Array.from(new Set(faqs.map(f => f.cat)))];

  const norm = q.trim().toLowerCase();
  const filtered = faqs
    .map((f, idx) => ({ ...f, idx }))
    .filter(f => (cat === "All" || f.cat === cat))
    .filter(f => !norm || f.q.toLowerCase().includes(norm) || f.a.toLowerCase().includes(norm));

  return (
    <div className="page" data-screen-label="05 FAQ">
      <section className="section" style={{ paddingTop: 64 }}>
        <div className="container" style={{ maxWidth: 880 }}>
          <div style={{ marginBottom: 36 }}>
            <div className="eyebrow" style={{ marginBottom: 16 }}>Common questions</div>
            <h1 style={{ marginBottom: 22 }}>Asked and answered.</h1>
            <p className="lead" style={{ maxWidth: 560 }}>
              Can't find what you're looking for? <button onClick={() => go("contact")} style={btnLinkInline}>Drop us a note</button> — every question helps the next person.
            </p>
          </div>

          <div style={{ position: "relative", marginBottom: 18 }}>
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" style={{ position: "absolute", left: 16, top: "50%", transform: "translateY(-50%)", color: "var(--ink-3)" }}>
              <circle cx="11" cy="11" r="7"/><path d="M20 20l-3.5-3.5"/>
            </svg>
            <input
              value={q}
              onChange={(e) => { setQ(e.target.value); setOpen(-1); }}
              placeholder="Search the FAQ — try 'backup' or 'mac'…"
              style={{
                width: "100%", padding: "14px 16px 14px 46px",
                border: "1px solid var(--line)", borderRadius: 10,
                fontSize: "1rem", fontFamily: "inherit",
                background: "var(--paper)", outline: "none",
              }}
            />
            {q && (
              <button
                onClick={() => setQ("")}
                aria-label="Clear"
                style={{
                  position: "absolute", right: 10, top: "50%", transform: "translateY(-50%)",
                  background: "var(--paper-2)", border: 0, padding: "4px 10px",
                  borderRadius: 6, cursor: "pointer", fontSize: 18, color: "var(--ink-3)",
                  fontFamily: "inherit",
                }}
              >×</button>
            )}
          </div>
          <div style={{ display: "flex", gap: 6, flexWrap: "wrap", marginBottom: 28 }}>
            {cats.map(c => (
              <ChapterChip
                key={c}
                label={c}
                count={c === "All" ? faqs.length : faqs.filter(f => f.cat === c).length}
                active={cat === c}
                onClick={() => { setCat(c); setOpen(-1); }}
              />
            ))}
          </div>

          {filtered.length === 0 ? (
            <div style={{ padding: "60px 20px", textAlign: "center", color: "var(--ink-2)", border: "1px dashed var(--line-soft)", borderRadius: 12 }}>
              <div style={{ fontFamily: "var(--display-font)", fontSize: "1.3rem", fontWeight: 600, marginBottom: 8, color: "var(--ink)" }}>No matches.</div>
              <div style={{ marginBottom: 16 }}>Try different words, or send the question to us directly.</div>
              <button className="btn secondary" onClick={() => go("contact")}>Ask the maker</button>
            </div>
          ) : (
            <div style={{ borderTop: "1px solid var(--line-soft)" }}>
              {filtered.map((f) => (
                <div key={f.idx} style={{ borderBottom: "1px solid var(--line-soft)" }}>
                  <button
                    onClick={() => setOpen(open === f.idx ? -1 : f.idx)}
                    style={{
                      all: "unset", cursor: "pointer", width: "100%",
                      padding: "22px 0", display: "flex",
                      justifyContent: "space-between", alignItems: "center",
                      fontSize: "1.08rem", fontWeight: 500,
                      gap: 24,
                    }}
                  >
                    <span style={{ display: "flex", gap: 14, alignItems: "center" }}>
                      <span className="kicker" style={{ minWidth: 90, color: "var(--accent-deep)" }}>{f.cat}</span>
                      <span>{highlight(f.q, norm)}</span>
                    </span>
                    <span style={{
                      width: 24, height: 24, flexShrink: 0,
                      display: "grid", placeItems: "center",
                      transform: open === f.idx ? "rotate(45deg)" : "rotate(0deg)",
                      transition: "transform .2s",
                      fontSize: 22, fontWeight: 300, color: "var(--ink-2)",
                    }}>+</span>
                  </button>
                  {open === f.idx && (
                    <div style={{ padding: "0 0 22px 104px", color: "var(--ink-2)", fontSize: "1rem", lineHeight: 1.65, maxWidth: 720 }}>
                      {highlight(f.a, norm)}
                    </div>
                  )}
                </div>
              ))}
            </div>
          )}
        </div>
      </section>
    </div>
  );
}

function highlight(text, q) {
  if (!q) return text;
  const i = text.toLowerCase().indexOf(q);
  if (i < 0) return text;
  return (
    <React.Fragment>
      {text.slice(0, i)}
      <mark style={{ background: "var(--accent-soft)", color: "var(--ink)", padding: "0 2px", borderRadius: 3 }}>{text.slice(i, i + q.length)}</mark>
      {text.slice(i + q.length)}
    </React.Fragment>
  );
}

const btnLinkInline = {
  background: "none", border: 0, padding: 0,
  color: "var(--accent-deep)", textDecoration: "underline",
  cursor: "pointer", fontSize: "inherit", fontFamily: "inherit", fontWeight: 500,
};

function ContactPage({ go }) {
  const [f, setF] = React.useState({ name: "", email: "", topic: "feature", msg: "" });
  const [sent, setSent] = React.useState(false);
  return (
    <div className="page" data-screen-label="06 Contact">
      <section className="section" style={{ paddingTop: 64 }}>
        <div className="container" style={{ maxWidth: 1040 }}>
          <div style={{ display: "grid", gridTemplateColumns: ".9fr 1.1fr", gap: 64 }} className="hero-grid">
            <div>
              <div className="eyebrow" style={{ marginBottom: 16 }}>Hello</div>
              <h1 style={{ marginBottom: 22 }}>Drop us a note.</h1>
              <p className="lead" style={{ marginBottom: 36 }}>
                Bug reports, feature requests, or just want to share a card you
                made? Every message is read by an actual human (the same one
                who built the app).
              </p>
              <div style={{ borderTop: "1px solid var(--line-soft)" }}>
                <ContactRow label="Email" value="silosoftwarecreations@gmail.com" />
                <ContactRow label="Reply time" value="usually within 2 days" />
              </div>
            </div>
            <div className="card bordered" style={{ padding: 32 }}>
              {sent ? (
                <div style={{ textAlign: "center", padding: "40px 12px" }}>
                  <h3 style={{ marginBottom: 10 }}>Almost there.</h3>
                  <p style={{ color: "var(--ink-2)" }}>
                    Your email app should have opened with the message ready to
                    send. If it didn't, just email{" "}
                    <b>silosoftwarecreations@gmail.com</b> directly.
                  </p>
                  <button className="btn secondary" style={{ marginTop: 20 }} onClick={() => { setSent(false); setF({ name: "", email: "", topic: "feature", msg: "" }); }}>Send another</button>
                </div>
              ) : (
                <form onSubmit={(e) => {
                  e.preventDefault();
                  // No form backend; hand the message to the visitor's own
                  // email app addressed to the developer.
                  const topicLabel = { feature: "Feature idea", bug: "Bug report", hello: "Hello" }[f.topic] || "Message";
                  const subject = encodeURIComponent(`[My Crafty Stash] ${topicLabel} from ${f.name}`);
                  const body = encodeURIComponent(`${f.msg}\n\n— ${f.name} (${f.email})`);
                  window.location.href = `mailto:silosoftwarecreations@gmail.com?subject=${subject}&body=${body}`;
                  setSent(true);
                }}>
                  <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
                    <div className="field">
                      <label>Your name</label>
                      <input value={f.name} onChange={(e) => setF({ ...f, name: e.target.value })} required />
                    </div>
                    <div className="field">
                      <label>Email</label>
                      <input type="email" value={f.email} onChange={(e) => setF({ ...f, email: e.target.value })} required />
                    </div>
                  </div>
                  <div className="field">
                    <label>What's it about?</label>
                    <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 6 }}>
                      {[
                        { v: "feature", l: "Feature idea" },
                        { v: "bug", l: "Bug report" },
                        { v: "hello", l: "Just saying hi" },
                      ].map(o => (
                        <button key={o.v} type="button" onClick={() => setF({ ...f, topic: o.v })} style={{
                          padding: "10px 8px",
                          border: "1px solid " + (f.topic === o.v ? "var(--ink)" : "var(--line-soft)"),
                          borderRadius: 8, cursor: "pointer", fontSize: "0.88rem",
                          background: f.topic === o.v ? "var(--ink)" : "var(--paper)",
                          color: f.topic === o.v ? "var(--paper)" : "var(--ink-2)",
                          fontFamily: "inherit", fontWeight: 500,
                        }}>{o.l}</button>
                      ))}
                    </div>
                  </div>
                  <div className="field">
                    <label>Your message</label>
                    <textarea
                      value={f.msg}
                      onChange={(e) => setF({ ...f, msg: e.target.value })}
                      rows={6}
                      required
                    />
                  </div>
                  <button className="btn" style={{ width: "100%" }} type="submit">Send message</button>
                </form>
              )}
            </div>
          </div>
        </div>
      </section>
    </div>
  );
}

function ContactRow({ label, value }) {
  return (
    <div style={{ display: "grid", gridTemplateColumns: "1fr 2fr", gap: 16, padding: "18px 0", borderBottom: "1px solid var(--line-soft)" }}>
      <div className="kicker">{label}</div>
      <div style={{ fontWeight: 500 }}>{value}</div>
    </div>
  );
}

Object.assign(window, { DownloadPage, HowToPage, FAQPage, ContactPage, VideoModal });
