/* ChatGPT intro - a full-page intro section that opens a generated chat draft */

const GPT_PROMPT = `hey based on whatever you know and the type of questions i ask, what type of person am i ...im writing an introductory paragraph with the tagline "chatgpt describes me as-"`;

function ThinkingDots() {
  return (
    <span style={{ display: "inline-flex", gap: 5, alignItems: "center", padding: "4px 0" }}>
      {[0, 1, 2].map((i) => (
        <span key={i} style={{
          width: 7, height: 7, borderRadius: 999, background: "var(--fg3)",
          animation: `dotPulse 1.1s ${i * 0.16}s ease-in-out infinite`,
        }} />
      ))}
      <style>{`@keyframes dotPulse{0%,100%{opacity:.25;transform:translateY(0)}50%{opacity:1;transform:translateY(-3px)}}`}</style>
    </span>
  );
}

function QuestionChips() {
  return (
    <div style={{ margin: "8px 0 2px" }}>
      <p className="eyebrow" style={{ marginBottom: 12, color: "var(--fg4)" }}>// the questions you keep asking</p>
      <div style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
        {window.GPT_QUESTIONS.map((q, i) => (
          <Reveal key={q} delay={i * 55} dir="scale">
            <span style={{
              fontFamily: "var(--font-mono)", fontSize: 13, color: "var(--fg2)",
              border: "1px solid var(--border-default)", borderRadius: 999, padding: "7px 14px",
              background: "var(--bg-inset)", display: "inline-block",
            }}>{q}</span>
          </Reveal>
        ))}
      </div>
    </div>
  );
}

function IntroMotion() {
  const chips = ["Why exactly?", "What changes?", "How does this scale?", "What is actually happening underneath?"];
  return (
    <div className="intro-orbit" aria-hidden style={{ position: "relative", minHeight: 420 }}>
      <div style={{ position: "absolute", inset: "12% 12% 10% 4%", border: "1px solid var(--border-subtle)", borderRadius: 999, opacity: .5, animation: "introSpin 18s linear infinite" }} />
      <div style={{ position: "absolute", inset: "22% 26% 18% 18%", border: "1px solid var(--border-subtle)", borderRadius: 999, opacity: .35, animation: "introSpin 13s linear infinite reverse" }} />
      {chips.map((chip, i) => (
        <span key={chip} style={{
          position: "absolute",
          top: ["13%", "34%", "60%", "78%"][i],
          left: ["24%", "50%", "14%", "42%"][i],
          maxWidth: i === 3 ? 270 : 190,
          fontFamily: "var(--font-mono)",
          fontSize: 12,
          lineHeight: 1.5,
          color: "var(--fg2)",
          border: "1px solid var(--border-subtle)",
          borderRadius: 8,
          background: "rgba(13,13,13,.74)",
          padding: "10px 12px",
          transform: `translateY(${i % 2 ? 0 : 12}px)`,
          animation: `introFloat ${7 + i}s ${i * .4}s ease-in-out infinite`,
        }}>{chip}</span>
      ))}
      <div style={{
        position: "absolute", right: "8%", top: "39%", width: 180, height: 180,
        border: "1px solid var(--border-default)", borderRadius: 12,
        display: "grid", placeItems: "center", background: "var(--bg-inset)", boxShadow: "var(--shadow-glow)",
      }}>
        <span style={{ fontFamily: "var(--font-mono)", fontSize: 48, color: "var(--fg1)", animation: "introPulse 2.4s ease-in-out infinite" }}>*</span>
      </div>
      <style>{`@keyframes introFloat{0%,100%{transform:translateY(0)}50%{transform:translateY(-18px)}}@keyframes introSpin{to{transform:rotate(360deg)}}@keyframes introPulse{0%,100%{opacity:.42;transform:scale(.95)}50%{opacity:1;transform:scale(1.04)}}@media(max-width:880px){.intro-orbit{display:none}}`}</style>
    </div>
  );
}

function AssistantBody({ start }) {
  const frozen = typeof document !== "undefined" && (document.hidden || document.documentElement.classList.contains("anim-off"));
  const [phase, setPhase] = React.useState(frozen ? "done" : "idle");

  React.useEffect(() => {
    if (!start) return;
    if (frozen) {
      setPhase("done");
      return;
    }
    setPhase("thinking");
    const typing = setTimeout(() => setPhase("typing"), 450);
    const done = setTimeout(() => setPhase("done"), 3600);
    return () => {
      clearTimeout(typing);
      clearTimeout(done);
    };
  }, [start]);

  const [typed, typedDone] = useTypewriter(window.GPT_INTRO, { speed: 16, start: phase === "typing" });
  React.useEffect(() => { if (typedDone) setPhase("done"); }, [typedDone]);

  return (
    <div>
      {phase === "thinking" && <ThinkingDots />}
      {(phase === "typing" || phase === "done") && (
        <React.Fragment>
          <p className="ds-body-lg" style={{ margin: "0 0 22px", color: "var(--fg1)", fontWeight: 500 }}>
            {phase === "typing" ? typed : window.GPT_INTRO}{phase === "typing" && <span className="caret" />}
          </p>
          {phase === "done" && (
            <React.Fragment>
              {window.GPT_PARAS.map((para, i) => (
                <React.Fragment key={i}>
                  <Reveal delay={i * 70}>
                    <p className="ds-body" style={{ margin: "0 0 20px", color: "var(--fg2)", maxWidth: 760 }}>{para}</p>
                  </Reveal>
                  {i === 2 && <QuestionChips />}
                </React.Fragment>
              ))}
            </React.Fragment>
          )}
        </React.Fragment>
      )}
    </div>
  );
}

function ChatGPTModal({ open, onClose }) {
  React.useEffect(() => {
    if (!open) return;
    document.body.classList.add("noscroll");
    const onKey = (e) => e.key === "Escape" && onClose();
    window.addEventListener("keydown", onKey);
    return () => {
      document.body.classList.remove("noscroll");
      window.removeEventListener("keydown", onKey);
    };
  }, [open]);

  if (!open) return null;

  return (
    <div style={{ position: "fixed", inset: 0, zIndex: 100, background: "rgba(0,0,0,0.72)", backdropFilter: "blur(8px)", display: "grid", placeItems: "center", padding: "24px", animation: "fadeBg .22s ease both" }} onClick={onClose}>
      <div onClick={(e) => e.stopPropagation()} style={{ width: "min(960px, 100%)", maxHeight: "min(790px, 88vh)", display: "flex", flexDirection: "column", border: "1px solid var(--border-default)", borderRadius: 10, background: "var(--bg-surface)", boxShadow: "var(--shadow-lg)", overflow: "hidden", animation: "chatPop .32s var(--ease-out) both" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "13px 18px", borderBottom: "1px solid var(--border-subtle)" }}>
          <span style={{ width: 22, height: 22, borderRadius: 6, border: "1px solid var(--border-strong)", display: "inline-flex", alignItems: "center", justifyContent: "center", fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--fg2)" }}>*</span>
          <span style={{ fontFamily: "var(--font-mono)", fontSize: 13, color: "var(--fg2)" }}>chatgpt</span>
          <span style={{ marginLeft: "auto", fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: ".1em", color: "var(--fg4)" }}>INTRO DRAFT</span>
          <button type="button" onClick={onClose} className="lk" style={{ marginLeft: 12, color: "var(--fg3)", fontFamily: "var(--font-mono)", fontSize: 13 }}>close</button>
        </div>

        <div style={{ padding: "26px 28px 30px", overflowY: "auto", display: "flex", flexDirection: "column", gap: 24 }}>
          <div style={{ display: "flex", justifyContent: "flex-end" }}>
            <div style={{ background: "var(--paper)", color: "var(--paper-ink)", borderRadius: "10px 10px 2px 10px", padding: "12px 16px", maxWidth: 610, fontFamily: "var(--font-sans)", fontSize: 15, lineHeight: 1.55 }}>
              {GPT_PROMPT}
            </div>
          </div>
          <div style={{ display: "flex", gap: 14, alignItems: "flex-start" }}>
            <span style={{ flexShrink: 0, width: 30, height: 30, borderRadius: 8, border: "1px solid var(--border-default)", display: "inline-flex", alignItems: "center", justifyContent: "center", fontFamily: "var(--font-mono)", fontSize: 13, color: "var(--fg2)", marginTop: 2 }}>*</span>
            <div style={{ minWidth: 0, flex: 1 }}>
              <AssistantBody start={open} />
            </div>
          </div>
        </div>
      </div>
      <style>{`@keyframes chatPop{from{transform:translateY(22px) scale(.98);opacity:.45}to{transform:none;opacity:1}}@keyframes fadeBg{from{opacity:0}to{opacity:1}}`}</style>
    </div>
  );
}

function ChatGPTSection() {
  const [open, setOpen] = React.useState(false);

  return (
    <section id="gpt" style={{ minHeight: "calc(100vh - 68px)", padding: "96px 0 72px", position: "relative", display: "flex", alignItems: "center", overflow: "hidden" }}>
      <div className="wrap" style={{ position: "relative", zIndex: 2, width: "100%" }}>
        <div style={{ display: "grid", gridTemplateColumns: "minmax(0, .95fr) minmax(320px, .8fr)", gap: 64, alignItems: "center" }} className="intro-grid">
          <div>
            <Reveal style={{ marginBottom: 18 }}><span className="eyebrow">01 - intro</span></Reveal>
            <Reveal delay={80}>
              <h2 className="ds-display" style={{ fontSize: "clamp(54px, 7vw, 104px)", maxWidth: 820, margin: "0 0 18px", lineHeight: 1.02 }}>
                <WordReveal text="I'll let ChatGPT do the intro for me." />
              </h2>
            </Reveal>
            <Reveal delay={250}>
              <button type="button" className="btn-primary lk" onClick={() => setOpen(true)}>
                Open ChatGPT intro <span className="arrow">→</span>
              </button>
            </Reveal>
          </div>
          <Reveal delay={130} dir="right">
            <IntroMotion />
          </Reveal>
        </div>
      </div>
      <ChatGPTModal open={open} onClose={() => setOpen(false)} />
      <style>{`@media(max-width:880px){.intro-grid{grid-template-columns:1fr !important;gap:32px !important}}`}</style>
    </section>
  );
}

Object.assign(window, { ChatGPTSection });
