/* anim-deploy.jsx — Queue-backed worker animation */

const DeploySim = () => {
  // Requests come in, queue holds them, 3 workers pull and process.
  // We animate over discrete ticks.
  const TOTAL_TICKS = 14;
  const REQUESTS = [
    { id: "r01", arrive: 0, dur: 3 },
    { id: "r02", arrive: 0, dur: 2 },
    { id: "r03", arrive: 1, dur: 4 },
    { id: "r04", arrive: 1, dur: 2 },
    { id: "r05", arrive: 2, dur: 3 },
    { id: "r06", arrive: 3, dur: 5 },
    { id: "r07", arrive: 4, dur: 2 },
    { id: "r08", arrive: 5, dur: 3 },
    { id: "r09", arrive: 6, dur: 2 },
  ];

  const { step, playing, toggle, next, prev, reset, containerRef } = useStepper({ steps: TOTAL_TICKS, intervalMs: 800 });

  // Compute schedule deterministically up to current tick
  const schedule = useMemo(() => {
    const workers = [{ id: "w1", task: null }, { id: "w2", task: null }, { id: "w3", task: null }];
    const queue = [];
    const done = [];
    const log = [];
    for (let t = 0; t <= step; t++) {
      // arrivals
      REQUESTS.filter(r => r.arrive === t).forEach(r => queue.push({ ...r, arrived: t }));
      // tick workers
      workers.forEach(w => {
        if (w.task) {
          w.task.elapsed += 1;
          if (w.task.elapsed >= w.task.dur) {
            done.push({ ...w.task, finished: t });
            w.task = null;
          }
        }
      });
      // assign
      workers.forEach(w => {
        if (!w.task && queue.length > 0) {
          w.task = { ...queue.shift(), elapsed: 0, started: t };
        }
      });
    }
    return { workers, queue, done };
  }, [step]);

  return (
    <div ref={containerRef}>
      <div style={{ display: "grid", gridTemplateColumns: "260px 1fr 200px", gap: 20, alignItems: "stretch" }}>
        {/* Queue */}
        <Box title="QUEUE" sub={`${schedule.queue.length} pending`}>
          <div style={{ padding: 12, display: "flex", flexDirection: "column", gap: 6, minHeight: 220 }}>
            {schedule.queue.length === 0 && <div style={{ color: "#a3a39d", fontStyle: "italic", fontSize: 12 }}>— empty —</div>}
            {schedule.queue.map((r, i) => (
              <div key={r.id} style={{
                background: "#fbf0d2", border: "1px solid #ecd690",
                borderRadius: 4, padding: "6px 10px",
                fontFamily: "JetBrains Mono, monospace", fontSize: 11,
                color: "#b8861a",
                animation: i === schedule.queue.length - 1 ? "slideIn 0.3s" : undefined,
              }}>
                ▸ {r.id} <span style={{ color: "#a3a39d" }}>· waited {step - r.arrived}t</span>
              </div>
            ))}
          </div>
        </Box>

        {/* Workers */}
        <Box title="WORKERS · auto-scaled" sub={`${schedule.workers.filter(w => w.task).length}/3 busy`}>
          <div style={{ padding: 12, display: "flex", flexDirection: "column", gap: 8, minHeight: 220 }}>
            {schedule.workers.map(w => (
              <div key={w.id} style={{
                border: "1px solid #e7e7e2", borderRadius: 4,
                background: w.task ? "#e8f0fe" : "#fbfbfa",
                borderColor: w.task ? "#c5d8f5" : "#e7e7e2",
                padding: "10px 12px",
                transition: "all 0.3s",
              }}>
                <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                  <div style={{
                    width: 8, height: 8, borderRadius: "50%",
                    background: w.task ? "#2d5fb8" : "#c7c7c0",
                  }}></div>
                  <span style={{ fontFamily: "JetBrains Mono, monospace", fontSize: 12, color: "#1a1a1a" }}>{w.id}</span>
                  <span style={{ fontFamily: "JetBrains Mono, monospace", fontSize: 11, color: "#6b6b66", marginLeft: "auto" }}>
                    {w.task ? `running ${w.task.id}` : "idle"}
                  </span>
                </div>
                {w.task && (
                  <div style={{ marginTop: 6, height: 4, background: "#fff", borderRadius: 2, overflow: "hidden" }}>
                    <div style={{
                      height: "100%", width: `${(w.task.elapsed / w.task.dur) * 100}%`,
                      background: "#2d5fb8", transition: "width 0.5s",
                    }}></div>
                  </div>
                )}
              </div>
            ))}
          </div>
        </Box>

        {/* Done */}
        <Box title="COMPLETED" sub={`${schedule.done.length} total`}>
          <div style={{ padding: 12, display: "flex", flexDirection: "column", gap: 4, minHeight: 220, maxHeight: 240, overflow: "auto" }}>
            {schedule.done.length === 0 && <div style={{ color: "#a3a39d", fontStyle: "italic", fontSize: 12 }}>— none yet —</div>}
            {schedule.done.map(d => (
              <div key={d.id} style={{
                fontFamily: "JetBrains Mono, monospace", fontSize: 11,
                color: "#2e7d4f",
              }}>
                ✓ {d.id} <span style={{ color: "#a3a39d" }}>· {d.dur}t</span>
              </div>
            ))}
          </div>
        </Box>
      </div>

      <div style={{ marginTop: 16, fontSize: 11, color: "#6b6b66", fontFamily: "JetBrains Mono, monospace", textAlign: "center" }}>
        tick {String(step).padStart(2, "0")}/{TOTAL_TICKS - 1} &nbsp;·&nbsp; long-running agents decoupled from the request thread (Celery / Temporal pattern)
      </div>
    </div>
  );
};

const Box = ({ title, sub, children }) => (
  <div style={{ background: "#fbfbfa", border: "1px solid #e7e7e2", borderRadius: 8, overflow: "hidden", display: "flex", flexDirection: "column" }}>
    <div style={{
      padding: "10px 14px", borderBottom: "1px solid #e7e7e2",
      background: "#f4f4f1",
      display: "flex", justifyContent: "space-between", alignItems: "center",
      fontFamily: "JetBrains Mono, monospace", fontSize: 10,
      color: "#6b6b66", textTransform: "uppercase", letterSpacing: "0.06em",
    }}>
      <span>{title}</span>
      <span style={{ color: "#a3a39d" }}>{sub}</span>
    </div>
    {children}
  </div>
);

window.DeploySim = DeploySim;
