/* anim-curriculum.jsx — Animations for the curriculum prelude chapter */

/* ===== 1. Evolution: Simple → RAG → Tool → Agentic ===== */
const EvolutionSim = () => {
  const STAGES = [
    { name: "Simple LLM", desc: "Reactive · no memory · generic advice", capabilities: { memory: 0, knowledge: 1, action: 0, planning: 0 }, color: "#a3a39d" },
    { name: "RAG Chatbot", desc: "Company knowledge · still reactive", capabilities: { memory: 1, knowledge: 4, action: 0, planning: 0 }, color: "#2d5fb8" },
    { name: "Tool-Augmented", desc: "Calls APIs · executes actions · still rigid", capabilities: { memory: 2, knowledge: 4, action: 4, planning: 1 }, color: "#c7521c" },
    { name: "Agentic AI", desc: "Plans · adapts · monitors · self-corrects", capabilities: { memory: 5, knowledge: 5, action: 5, planning: 5 }, color: "#2e7d4f" },
  ];
  const { step, containerRef } = useStepper({ steps: STAGES.length, intervalMs: 2000 });
  const cur = STAGES[step];
  const axes = [["memory","Memory"],["knowledge","Knowledge"],["action","Action"],["planning","Planning"]];

  return (
    <div ref={containerRef}>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 8, marginBottom: 20 }}>
        {STAGES.map((s, i) => (
          <div key={i} style={{
            padding: "10px 12px", borderRadius: 6,
            border: `1px solid ${i === step ? s.color : "#e7e7e2"}`,
            background: i === step ? "#fff" : "#fbfbfa",
            opacity: i <= step ? 1 : 0.4, transition: "all 0.3s",
            boxShadow: i === step ? "0 4px 12px rgba(0,0,0,0.06)" : "none",
          }}>
            <div style={{ fontSize: 10, fontFamily: "JetBrains Mono, monospace", color: s.color, textTransform: "uppercase", letterSpacing: "0.06em", marginBottom: 4 }}>stage {i+1}</div>
            <div style={{ fontWeight: 600, fontSize: 13, color: "#1a1a1a" }}>{s.name}</div>
          </div>
        ))}
      </div>
      <div style={{ background: "#fff", border: "1px solid #e7e7e2", borderRadius: 8, padding: 20 }}>
        <div style={{ fontSize: 13, color: "#6b6b66", marginBottom: 16, fontFamily: "JetBrains Mono, monospace" }}>{cur.desc}</div>
        {axes.map(([k, label]) => (
          <div key={k} style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 8 }}>
            <div style={{ width: 90, fontSize: 11, color: "#6b6b66", fontFamily: "JetBrains Mono, monospace" }}>{label}</div>
            <div style={{ flex: 1, height: 10, background: "#f4f4f1", borderRadius: 2, overflow: "hidden" }}>
              <div style={{ height: "100%", width: `${cur.capabilities[k] * 20}%`, background: cur.color, transition: "width 0.6s ease" }}></div>
            </div>
            <div style={{ width: 30, fontSize: 11, color: "#1a1a1a", fontFamily: "JetBrains Mono, monospace", textAlign: "right" }}>{cur.capabilities[k]}/5</div>
          </div>
        ))}
      </div>
    </div>
  );
};

/* ===== 2. 5 Core Components diagram ===== */
const CoreComponentsSim = () => {
  const COMPS = [
    { name: "Brain (LLM)", role: "Interprets goal · plans · selects tools", x: 250, y: 60, color: "#2d5fb8" },
    { name: "Orchestrator", role: "Sequences tasks · routes · retries · loops", x: 250, y: 180, color: "#c7521c" },
    { name: "Tools", role: "APIs · DBs · RAG · external systems", x: 70, y: 280, color: "#2e7d4f" },
    { name: "Memory", role: "State · session history · preferences", x: 250, y: 280, color: "#6b3fa0" },
    { name: "Supervisor", role: "Guardrails · escalations · HITL approvals", x: 430, y: 280, color: "#b8861a" },
  ];
  const { step, containerRef } = useStepper({ steps: COMPS.length + 1, intervalMs: 1500 });

  return (
    <div ref={containerRef}>
      <div style={{ display: "grid", gridTemplateColumns: "1.2fr 1fr", gap: 24 }}>
        <svg viewBox="0 0 540 380" style={{ width: "100%", height: "auto", background: "#fbfbfa", borderRadius: 8, border: "1px solid #e7e7e2" }}>
          {/* Connections from orchestrator */}
          {[2,3,4].map(i => {
            const a = COMPS[1], b = COMPS[i];
            const visible = step > Math.max(1, i);
            return <line key={i} x1={a.x} y1={a.y} x2={b.x} y2={b.y} stroke={visible ? "#c7c7c0" : "#f4f4f1"} strokeWidth="1.5" strokeDasharray="3 3" style={{ transition: "stroke 0.3s" }} />;
          })}
          <line x1={COMPS[0].x} y1={COMPS[0].y} x2={COMPS[1].x} y2={COMPS[1].y} stroke={step > 1 ? "#c7c7c0" : "#f4f4f1"} strokeWidth="1.5" />
          {COMPS.map((c, i) => {
            const visible = step > i;
            return (
              <g key={i} style={{ opacity: visible ? 1 : 0.15, transition: "opacity 0.4s" }}>
                <rect x={c.x - 80} y={c.y - 22} width="160" height="44" rx="8"
                  fill="#fff" stroke={c.color} strokeWidth="1.5" />
                <text x={c.x} y={c.y + 5} textAnchor="middle"
                  fontSize="13" fontWeight="600" fill={c.color} fontFamily="Inter Tight, sans-serif">
                  {c.name}
                </text>
              </g>
            );
          })}
        </svg>
        <div>
          <div style={{ fontFamily: "JetBrains Mono, monospace", fontSize: 11, color: "#6b6b66", marginBottom: 10, textTransform: "uppercase", letterSpacing: "0.06em" }}>5 core components</div>
          <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
            {COMPS.map((c, i) => (
              <div key={i} style={{
                padding: "8px 12px",
                borderLeft: `3px solid ${step > i ? c.color : "#e7e7e2"}`,
                background: step > i ? "#fff" : "#fbfbfa",
                opacity: step > i ? 1 : 0.4, transition: "all 0.3s",
                fontSize: 12,
              }}>
                <div style={{ fontWeight: 600, color: c.color, fontSize: 12 }}>{c.name}</div>
                <div style={{ color: "#6b6b66", fontSize: 11, marginTop: 2 }}>{c.role}</div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
};

/* ===== 3. LangChain vs LangGraph ===== */
const ChainVsGraphSim = () => {
  const { step, containerRef } = useStepper({ steps: 6, intervalMs: 1300 });
  return (
    <div ref={containerRef}>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
        <div style={{ background: "#fff", border: "1px solid #e7e7e2", borderRadius: 8, padding: 16 }}>
          <div style={{ fontFamily: "JetBrains Mono, monospace", fontSize: 11, color: "#c7521c", marginBottom: 12, textTransform: "uppercase", letterSpacing: "0.06em" }}>LangChain · sequential</div>
          <svg viewBox="0 0 280 140" style={{ width: "100%" }}>
            {[0,1,2,3].map(i => {
              const x = 30 + i * 70;
              const reached = step > i;
              return (
                <g key={i}>
                  <rect x={x-22} y={50} width="44" height="40" rx="4"
                    fill={reached ? "#fbeadc" : "#fbfbfa"} stroke={reached ? "#c7521c" : "#c7c7c0"} strokeWidth="1.5" style={{ transition: "all 0.3s" }} />
                  <text x={x} y={75} textAnchor="middle" fontSize="11" fontFamily="JetBrains Mono, monospace" fill={reached ? "#c7521c" : "#a3a39d"}>step{i+1}</text>
                  {i < 3 && <line x1={x+22} y1={70} x2={x+48} y2={70} stroke={reached && step > i+1 ? "#c7521c" : "#e7e7e2"} strokeWidth="1.5" markerEnd="url(#arr-c)" />}
                </g>
              );
            })}
            <defs><marker id="arr-c" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="6" markerHeight="6" orient="auto"><path d="M0,0 L10,5 L0,10 z" fill="#c7521c" /></marker></defs>
          </svg>
          <div style={{ marginTop: 10, fontSize: 12, color: "#6b6b66", lineHeight: 1.5 }}>
            ✗ stateless · ✗ no pause/resume · ✗ no loops · ✓ great for linear chains
          </div>
        </div>
        <div style={{ background: "#fff", border: "1px solid #e7e7e2", borderRadius: 8, padding: 16 }}>
          <div style={{ fontFamily: "JetBrains Mono, monospace", fontSize: 11, color: "#2e7d4f", marginBottom: 12, textTransform: "uppercase", letterSpacing: "0.06em" }}>LangGraph · stateful graph</div>
          <svg viewBox="0 0 280 140" style={{ width: "100%" }}>
            {[{x:50,y:35},{x:140,y:35},{x:230,y:70},{x:140,y:105}].map((n, i) => {
              const reached = step > i;
              return <circle key={i} cx={n.x} cy={n.y} r="20" fill={reached ? "#e3f1e8" : "#fbfbfa"} stroke={reached ? "#2e7d4f" : "#c7c7c0"} strokeWidth="1.5" style={{ transition: "all 0.3s" }} />;
            })}
            {/* Edges */}
            <line x1={70} y1={35} x2={120} y2={35} stroke="#2e7d4f" strokeWidth="1.5" />
            <line x1={158} y1={48} x2={212} y2={62} stroke="#2e7d4f" strokeWidth="1.5" />
            <line x1={212} y1={80} x2={158} y2={95} stroke="#2e7d4f" strokeWidth="1.5" />
            <path d="M 120 105 Q 60 105 50 55" fill="none" stroke="#2e7d4f" strokeWidth="1.5" strokeDasharray="3 3" />
            {[{x:50,y:35,t:"plan"},{x:140,y:35,t:"act"},{x:230,y:70,t:"check"},{x:140,y:105,t:"loop"}].map((n, i) => (
              <text key={i} x={n.x} y={n.y+4} textAnchor="middle" fontSize="10" fontFamily="JetBrains Mono, monospace" fill={step > i ? "#2e7d4f" : "#a3a39d"}>{n.t}</text>
            ))}
          </svg>
          <div style={{ marginTop: 10, fontSize: 12, color: "#6b6b66", lineHeight: 1.5 }}>
            ✓ stateful · ✓ checkpoint/resume · ✓ loops + branches · ✓ subgraphs
          </div>
        </div>
      </div>
    </div>
  );
};

/* ===== 4. Five workflow patterns ===== */
const PatternsSim = () => {
  const PATTERNS = ["Prompt Chain","Routing","Parallel","Orchestrator-Workers","Evaluator-Optimizer"];
  const [active, setActive] = useState(0);
  const renderPattern = (i) => {
    const c = "#2d5fb8";
    if (i === 0) return (
      <svg viewBox="0 0 360 80" style={{ width: "100%" }}>
        {[0,1,2,3].map(j => <rect key={j} x={20+j*85} y={25} width="60" height="32" rx="5" fill="#e8f0fe" stroke={c} />)}
        {[0,1,2,3].map(j => <text key={j} x={50+j*85} y={45} textAnchor="middle" fontSize="11" fontFamily="JetBrains Mono, monospace" fill={c}>step{j+1}</text>)}
        {[0,1,2].map(j => <line key={j} x1={80+j*85} y1={41} x2={105+j*85} y2={41} stroke={c} strokeWidth="1.5" />)}
      </svg>
    );
    if (i === 1) return (
      <svg viewBox="0 0 360 160" style={{ width: "100%" }}>
        <rect x={20} y={62} width="80" height="36" rx="5" fill="#e8f0fe" stroke={c} /><text x={60} y={84} textAnchor="middle" fontSize="11" fontFamily="JetBrains Mono, monospace" fill={c}>router</text>
        {["tech","sales","billing"].map((t,j) => (
          <g key={j}>
            <rect x={200} y={20+j*45} width="100" height="32" rx="5" fill="#e8f0fe" stroke={c} />
            <text x={250} y={40+j*45} textAnchor="middle" fontSize="11" fontFamily="JetBrains Mono, monospace" fill={c}>{t}</text>
            <line x1={100} y1={80} x2={200} y2={36+j*45} stroke={c} strokeWidth="1.5" strokeDasharray="3 3" />
          </g>
        ))}
      </svg>
    );
    if (i === 2) return (
      <svg viewBox="0 0 360 160" style={{ width: "100%" }}>
        <rect x={20} y={62} width="60" height="36" rx="5" fill="#e8f0fe" stroke={c} /><text x={50} y={84} textAnchor="middle" fontSize="11" fontFamily="JetBrains Mono, monospace" fill={c}>split</text>
        <rect x={280} y={62} width="60" height="36" rx="5" fill="#e8f0fe" stroke={c} /><text x={310} y={84} textAnchor="middle" fontSize="11" fontFamily="JetBrains Mono, monospace" fill={c}>merge</text>
        {[0,1,2].map(j => (
          <g key={j}>
            <rect x={150} y={15+j*50} width="80" height="32" rx="5" fill="#e8f0fe" stroke={c} />
            <text x={190} y={35+j*50} textAnchor="middle" fontSize="10" fontFamily="JetBrains Mono, monospace" fill={c}>worker{j+1}</text>
            <line x1={80} y1={80} x2={150} y2={31+j*50} stroke={c} strokeWidth="1.5" />
            <line x1={230} y1={31+j*50} x2={280} y2={80} stroke={c} strokeWidth="1.5" />
          </g>
        ))}
      </svg>
    );
    if (i === 3) return (
      <svg viewBox="0 0 360 160" style={{ width: "100%" }}>
        <rect x={140} y={20} width="80" height="36" rx="5" fill="#fbeadc" stroke="#c7521c" /><text x={180} y={42} textAnchor="middle" fontSize="11" fontFamily="JetBrains Mono, monospace" fill="#c7521c">orchestrator</text>
        {[0,1,2,3].map(j => (
          <g key={j}>
            <rect x={20+j*85} y={100} width="60" height="36" rx="5" fill="#e8f0fe" stroke={c} />
            <text x={50+j*85} y={122} textAnchor="middle" fontSize="11" fontFamily="JetBrains Mono, monospace" fill={c}>w{j+1}</text>
            <line x1={180} y1={56} x2={50+j*85} y2={100} stroke="#c7521c" strokeWidth="1.5" strokeDasharray="3 3" />
          </g>
        ))}
      </svg>
    );
    if (i === 4) return (
      <svg viewBox="0 0 360 140" style={{ width: "100%" }}>
        <rect x={30} y={50} width="90" height="36" rx="5" fill="#e8f0fe" stroke={c} /><text x={75} y={72} textAnchor="middle" fontSize="11" fontFamily="JetBrains Mono, monospace" fill={c}>generate</text>
        <rect x={235} y={50} width="90" height="36" rx="5" fill="#fbeadc" stroke="#c7521c" /><text x={280} y={72} textAnchor="middle" fontSize="11" fontFamily="JetBrains Mono, monospace" fill="#c7521c">evaluate</text>
        <line x1={120} y1={68} x2={235} y2={68} stroke={c} strokeWidth="1.5" />
        <path d="M 280 86 Q 280 120 75 120 Q 75 100 75 86" fill="none" stroke="#c7521c" strokeWidth="1.5" strokeDasharray="3 3" />
        <text x={180} y={132} textAnchor="middle" fontSize="10" fontFamily="JetBrains Mono, monospace" fill="#c7521c">loop until ✓</text>
      </svg>
    );
  };
  return (
    <div>
      <div style={{ display: "flex", gap: 6, marginBottom: 16, flexWrap: "wrap" }}>
        {PATTERNS.map((p, i) => (
          <button key={i} onClick={() => setActive(i)} style={{
            padding: "6px 12px", borderRadius: 4,
            border: "1px solid", borderColor: active === i ? "#1a1a1a" : "#e7e7e2",
            background: active === i ? "#1a1a1a" : "#fff",
            color: active === i ? "#fff" : "#3d3d3a",
            fontSize: 12, fontFamily: "Inter Tight, sans-serif", cursor: "pointer",
          }}>{p}</button>
        ))}
      </div>
      <div style={{ background: "#fff", border: "1px solid #e7e7e2", borderRadius: 8, padding: 20 }}>
        {renderPattern(active)}
      </div>
    </div>
  );
};

/* ===== 5. Iterative loop simulation ===== */
const IterativeLoopSim = () => {
  const ITERATIONS = [
    { draft: "Just shipped a thing! 🚀", score: 4, feedback: "Too generic, no humor, no specifics." },
    { draft: "Shipped a side-quest in 3hrs that ate 3 days. Such is software.", score: 7, feedback: "Closer — but missing format hook." },
    { draft: "ETA: 3 hours. Reality: 3 days. The eternal scope-tax of a 'quick fix.'", score: 9, feedback: "✓ Approved — humor, specificity, format all hit." },
  ];
  const STEPS = ITERATIONS.length * 2 + 1;
  const { step, containerRef } = useStepper({ steps: STEPS, intervalMs: 1400 });
  const iter = Math.min(Math.floor(step / 2), ITERATIONS.length - 1);
  const phase = step % 2 === 0 ? "generate" : "evaluate";
  const cur = ITERATIONS[iter];
  return (
    <div ref={containerRef}>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
        <div style={{ background: "#fff", border: "1px solid #e7e7e2", borderRadius: 8, padding: 16, minHeight: 200 }}>
          <div style={{ fontFamily: "JetBrains Mono, monospace", fontSize: 11, color: phase === "generate" ? "#2d5fb8" : "#6b6b66", marginBottom: 8, textTransform: "uppercase" }}>generator{phase === "generate" && " · drafting…"}</div>
          <div style={{ fontSize: 14, color: "#1a1a1a", lineHeight: 1.5 }}>{cur.draft}</div>
          <div style={{ marginTop: 12, fontSize: 11, fontFamily: "JetBrains Mono, monospace", color: "#a3a39d" }}>iteration {iter+1} / 3</div>
        </div>
        <div style={{ background: "#fff", border: "1px solid #e7e7e2", borderRadius: 8, padding: 16, minHeight: 200 }}>
          <div style={{ fontFamily: "JetBrains Mono, monospace", fontSize: 11, color: phase === "evaluate" ? "#c7521c" : "#6b6b66", marginBottom: 8, textTransform: "uppercase" }}>evaluator{phase === "evaluate" && " · scoring…"}</div>
          {step >= iter * 2 + 1 && (
            <>
              <div style={{ fontSize: 24, fontFamily: "Source Serif 4, serif", color: cur.score >= 8 ? "#2e7d4f" : "#c7521c", fontWeight: 500 }}>{cur.score}/10</div>
              <div style={{ fontSize: 13, color: "#3d3d3a", marginTop: 6, fontStyle: "italic" }}>"{cur.feedback}"</div>
            </>
          )}
        </div>
      </div>
      <div style={{ marginTop: 14, padding: "10px 14px", background: iter === 2 && step >= 5 ? "#e3f1e8" : "#f4f4f1", border: "1px solid", borderColor: iter === 2 && step >= 5 ? "#b8dcc4" : "#e7e7e2", borderRadius: 6, fontSize: 13, fontFamily: "JetBrains Mono, monospace", color: iter === 2 && step >= 5 ? "#2e7d4f" : "#6b6b66" }}>
        {iter === 2 && step >= 5 ? "✓ approved — exit loop · max_iterations not reached" : `loop continues · max_iterations: 5`}
      </div>
    </div>
  );
};

/* ===== 6. Persistence / Checkpointer ===== */
const PersistenceSim = () => {
  const STEPS = [
    { thread: "thread_A", action: "User: 'My name is Sam.'", state: { messages: 1 }, saved: true },
    { thread: "thread_A", action: "User: 'What's my name?'", state: { messages: 3 }, saved: true, hint: "Bot recalls 'Sam' from checkpoint" },
    { thread: "thread_B", action: "Different user opens new session", state: { messages: 0 }, saved: true, hint: "Fresh state — checkpoints isolated by thread_id" },
    { thread: "thread_A", action: "Sam returns next day · server restarted", state: { messages: 3 }, saved: true, hint: "MemorySaver (RAM) lost · use Postgres in prod" },
  ];
  const { step, containerRef } = useStepper({ steps: STEPS.length, intervalMs: 2000 });
  const cur = STEPS[step];
  return (
    <div ref={containerRef}>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
        <div style={{ background: "#fff", border: "1px solid #e7e7e2", borderRadius: 8, padding: 16 }}>
          <div style={{ fontFamily: "JetBrains Mono, monospace", fontSize: 11, color: "#6b6b66", marginBottom: 10, textTransform: "uppercase" }}>active session</div>
          <div style={{ padding: "10px 14px", background: cur.thread === "thread_A" ? "#e8f0fe" : "#ede4f7", border: `1px solid ${cur.thread === "thread_A" ? "#c5d8f5" : "#d4c1ed"}`, borderRadius: 6, marginBottom: 10 }}>
            <div style={{ fontFamily: "JetBrains Mono, monospace", fontSize: 11, color: cur.thread === "thread_A" ? "#1d3f7d" : "#6b3fa0", fontWeight: 600 }}>config: {`{"thread_id": "${cur.thread}"}`}</div>
          </div>
          <div style={{ fontSize: 13, color: "#1a1a1a" }}>{cur.action}</div>
          {cur.hint && <div style={{ marginTop: 10, fontSize: 12, color: "#6b6b66", fontStyle: "italic" }}>→ {cur.hint}</div>}
        </div>
        <div style={{ background: "#fff", border: "1px solid #e7e7e2", borderRadius: 8, padding: 16 }}>
          <div style={{ fontFamily: "JetBrains Mono, monospace", fontSize: 11, color: "#6b6b66", marginBottom: 10, textTransform: "uppercase" }}>checkpointer storage</div>
          {["thread_A","thread_B"].map(t => {
            const has = STEPS.slice(0, step+1).some(s => s.thread === t && s.saved);
            const isCur = cur.thread === t;
            return (
              <div key={t} style={{
                padding: "8px 12px", marginBottom: 8,
                background: has ? "#fff" : "#fbfbfa",
                border: `1px solid ${isCur ? "#1a1a1a" : "#e7e7e2"}`,
                borderRadius: 4, fontSize: 12, fontFamily: "JetBrains Mono, monospace",
                opacity: has ? 1 : 0.4,
              }}>
                <div style={{ color: "#1a1a1a", fontWeight: 600 }}>▸ {t}</div>
                <div style={{ color: "#6b6b66", marginTop: 2 }}>messages: {has && cur.thread === t ? cur.state.messages : has ? "—" : "(empty)"}</div>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
};

window.EvolutionSim = EvolutionSim;
window.CoreComponentsSim = CoreComponentsSim;
window.ChainVsGraphSim = ChainVsGraphSim;
window.PatternsSim = PatternsSim;
window.IterativeLoopSim = IterativeLoopSim;
window.PersistenceSim = PersistenceSim;
