// page-home.jsx — landing page with game-flavored animations
const { SiteCtx, useReveal, CountUp, I18N } = window.MM_HOOKS;

function HomePage({ motion, onJump }) {
  const { lang } = React.useContext(SiteCtx);
  const t = I18N[lang];
  const D = window.SITE_DATA;
  const stats = D.HERO.stats;
  const [ref1, s1] = useReveal({ threshold: 0.1 });
  const [ref2, s2] = useReveal({ threshold: 0.1 });
  const [ref3, s3] = useReveal({ threshold: 0.1 });
  const [ref4, s4] = useReveal({ threshold: 0.1 });
  const [ref5, s5] = useReveal({ threshold: 0.2 });
  const [agentOpen, setAgentOpen] = React.useState(false);

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

  return (
    <section id="home" className="page home">
      <div className="home-grid-bg"></div>
      <div className="home-sprite s1">▲</div>
      <div className="home-sprite s2">◆</div>
      <div className="home-sprite s3">●</div>
      <div className="home-sprite s4">■</div>

      <div className="home-inner">
        <div ref={ref1} className={`reveal-pop ${s1 ? "is-shown" : ""}`}>
          <div className="home-pretitle">
            <span className="blink">▶</span>
            {t.home_eyebrow}
          </div>
        </div>

        <h1 ref={ref2} className={`home-tagline reveal ${s2 ? "is-shown" : ""}`}>
          {t.home_tagline_a}<span className="accent">{t.home_tagline_b}</span>{t.home_tagline_c}
        </h1>

        <p ref={ref3} className={`home-sub reveal ${s3 ? "is-shown" : ""}`} style={{ transitionDelay: "120ms" }}>
          {t.home_sub}
        </p>

        <div ref={ref4} className={`home-doors stagger ${s4 ? "is-shown" : ""}`}>
          <button className="door door--human" onClick={() => onJump("cases")}>
            <div className="door-icon">👤</div>
            <div className="door-body">
              <div className="door-title">{lang === "zh" ? "Human view" : "Human view"}</div>
              <div className="door-sub">{lang === "zh" ? "往下滚——案例、Side Project、简历、AI 对话。" : "Scroll on — cases, side projects, résumé, chat."}</div>
            </div>
            <div className="door-arrow">↓</div>
          </button>
          <button className="door door--agent" onClick={() => setAgentOpen(true)}>
            <div className="door-icon">🤖</div>
            <div className="door-body">
              <div className="door-title">{lang === "zh" ? "Agent view" : "Agent view"}</div>
              <div className="door-sub">{lang === "zh" ? "看一个 agent 来这里会先抓哪几个文件。可以一键复制成 curl。" : "See which files an agent fetches here first. Copy as curl."}</div>
            </div>
            <div className="door-arrow">→</div>
          </button>
        </div>
        <div className={`home-mini-cta stagger ${s4 ? "is-shown" : ""}`}>
          <a className="mini-link" href="llms.txt" target="_blank">/llms.txt</a>
          <a className="mini-link" href="skill.md" target="_blank">/skill.md</a>
          <a className="mini-link" href="candidate.md" target="_blank">/candidate.md</a>
          <a className="mini-link" href="projects.json" target="_blank">/projects.json</a>
          <a className="mini-link" href="resume.pdf" download>📄 resume.pdf</a>
        </div>

        <div ref={ref5} className={`home-stats stagger ${s5 ? "is-shown" : ""}`}>
          {stats.map((s, i) => (
            <div key={i} className="home-stat">
              <div className="home-stat-num">
                {s.note_en && <span className="home-stat-approx">{lang === "zh" ? s.note_zh : s.note_en}</span>}
                <CountUp target={s.value} suffix={s.suffix} motion={motion} />
              </div>
              <div className="home-stat-label">{lang === "zh" ? s.label_zh : s.label_en}</div>
            </div>
          ))}
        </div>
      </div>

      <div className="home-scroll-hint">
        <span>{t.scroll_hint}</span>
        <div className="arrow"></div>
      </div>

      {agentOpen && <AgentView onClose={() => setAgentOpen(false)} lang={lang} />}
    </section>
  );
}

// ============================================================
// AgentView — demonstrates the fetch sequence an LLM agent runs
// against this site. Not a mode toggle — a product demo of
// agent-readable design. Resources are real & fetched live.
// ============================================================
const AGENT_SEQUENCE = [
  { url: "/llms.txt",        type: "text/markdown",   purpose_en: "Site map for agents (llmstxt.org spec)",   purpose_zh: "agent 的站点地图（llmstxt.org 规范）" },
  { url: "/skill.md",        type: "text/markdown",   purpose_en: "How to evaluate this candidate",            purpose_zh: "如何评估这个候选人" },
  { url: "/candidate.md",    type: "text/markdown",   purpose_en: "Full CV, EN + 中文",                         purpose_zh: "完整简历，中英双语" },
  { url: "/projects.json",   type: "application/json",purpose_en: "Machine-readable project list",              purpose_zh: "结构化的项目列表" },
];

function AgentView({ onClose, lang }) {
  const [active, setActive] = React.useState(0);
  const [bodies, setBodies] = React.useState({});
  const [status, setStatus] = React.useState({});
  const [copied, setCopied] = React.useState(false);

  // fetch all four resources lazily, show first 20 lines
  React.useEffect(() => {
    AGENT_SEQUENCE.forEach((s, i) => {
      const path = s.url.replace(/^\//, "");
      setStatus(prev => ({ ...prev, [i]: "fetching" }));
      fetch(path, { headers: { Accept: s.type } })
        .then(r => r.text().then(t => ({ ok: r.ok, code: r.status, text: t })))
        .then(({ ok, code, text }) => {
          setStatus(prev => ({ ...prev, [i]: ok ? `200 OK · ${text.length.toLocaleString()} bytes` : `${code}` }));
          setBodies(prev => ({ ...prev, [i]: text }));
        })
        .catch(() => setStatus(prev => ({ ...prev, [i]: "error" })));
    });
  }, []);

  const origin = typeof window !== "undefined" ? window.location.origin : "https://mingmu.site";
  const curl = AGENT_SEQUENCE.map(s =>
    `curl -H "Accept: ${s.type}" ${origin}${s.url}`
  ).join(" \\\n  && ");

  const copyCurl = async () => {
    try {
      await navigator.clipboard.writeText(curl);
      setCopied(true);
      setTimeout(() => setCopied(false), 1800);
    } catch {}
  };

  const cur = AGENT_SEQUENCE[active];
  const body = bodies[active] || "";
  const previewLines = body.split("\n").slice(0, 20);
  const truncated = body.split("\n").length > 20;

  return (
    <div className="agent-view" onClick={onClose}>
      <div className="agent-view-card" onClick={(e) => e.stopPropagation()}>
        <div className="agent-view-bar">
          <div className="agent-view-bar-l">
            <span className="dot dot--r"></span>
            <span className="dot dot--y"></span>
            <span className="dot dot--g"></span>
          </div>
          <div className="agent-view-bar-c">
            <span className="agent-view-mark">🤖</span>
            <span className="agent-view-title">{lang === "zh" ? "Agent 视图 — 一个 LLM 代理在这个站点会做什么" : "Agent view — what an LLM agent fetches here"}</span>
          </div>
          <button className="agent-view-close" onClick={onClose}>✕</button>
        </div>

        <div className="agent-view-body">
          <div className="agent-view-pane agent-view-pane--list">
            <div className="agent-view-pane-h">
              <span className="agent-view-pane-h-num">01</span>
              <span>{lang === "zh" ? "请求序列" : "Fetch sequence"}</span>
            </div>
            <ol className="agent-seq">
              {AGENT_SEQUENCE.map((s, i) => (
                <li
                  key={i}
                  className={`agent-seq-item ${active === i ? "is-active" : ""}`}
                  onClick={() => setActive(i)}
                >
                  <div className="agent-seq-line">
                    <span className="agent-seq-method">GET</span>
                    <span className="agent-seq-url">{s.url}</span>
                    <span className={`agent-seq-status ${status[i] && status[i].startsWith("200") ? "is-ok" : ""}`}>
                      {status[i] || "—"}
                    </span>
                  </div>
                  <div className="agent-seq-purpose">{lang === "zh" ? s.purpose_zh : s.purpose_en}</div>
                  <div className="agent-seq-accept">
                    <span className="agent-seq-tag">Accept:</span> {s.type}
                  </div>
                </li>
              ))}
            </ol>

            <div className="agent-view-curl">
              <div className="agent-view-pane-h">
                <span className="agent-view-pane-h-num">02</span>
                <span>{lang === "zh" ? "复制成 curl" : "Copy as curl"}</span>
              </div>
              <pre className="agent-view-curl-block"><code>{curl}</code></pre>
              <button className="agent-view-copy" onClick={copyCurl}>
                {copied
                  ? (lang === "zh" ? "✓ 已复制" : "✓ Copied")
                  : (lang === "zh" ? "📋 复制全部" : "📋 Copy all")}
              </button>
            </div>
          </div>

          <div className="agent-view-pane agent-view-pane--preview">
            <div className="agent-view-pane-h">
              <span className="agent-view-pane-h-num">03</span>
              <span>{lang === "zh" ? "响应预览（前 20 行）" : "Response preview (first 20 lines)"}</span>
            </div>
            <div className="agent-view-resp-meta">
              <code>GET {cur.url}</code>
              <code>Content-Type: {cur.type}</code>
              <code>{status[active] || "fetching…"}</code>
            </div>
            <pre className="agent-view-resp-body">
              {previewLines.map((line, i) => (
                <div key={i} className="agent-view-resp-line">
                  <span className="agent-view-resp-ln">{String(i + 1).padStart(2, "0")}</span>
                  <span className="agent-view-resp-tx">{line || " "}</span>
                </div>
              ))}
              {truncated && (
                <div className="agent-view-resp-line agent-view-resp-line--more">
                  <span className="agent-view-resp-ln">…</span>
                  <span className="agent-view-resp-tx">
                    <a href={cur.url.replace(/^\//, "")} target="_blank" rel="noopener">
                      {lang === "zh" ? `打开完整文件 (${body.split("\n").length} 行)` : `Open full file (${body.split("\n").length} lines)`} ↗
                    </a>
                  </span>
                </div>
              )}
            </pre>
          </div>
        </div>

        <div className="agent-view-foot">
          <span className="agent-view-foot-l">
            {lang === "zh"
              ? "上面四个 URL 都是真的，agent 现在就能 curl。"
              : "All four URLs are real. An agent could curl them right now."}
          </span>
          <span className="agent-view-foot-r">{lang === "zh" ? "Esc 关闭" : "press Esc to close"}</span>
        </div>
      </div>
    </div>
  );
}

window.HomePage = HomePage;
