// ConceptE_Workflow — Beat 2. A clean horizontal left→right chain of 4 nodes.
// Agent 1 (Extract) is the same card from Beat 1 (rendered by AgentScene).
// We overlay a role chip under it so it reads as the first node in the chain.
//
// Layout (world coords):
//   N1 Extract  (300, 470)    <-- AgentScene draws this one
//   N2 Classify (480, 470)    agent node (compact card w/ sparkle)
//   N3 Review   (660, 470)    human node (circular avatar w/ initials)
//   N4 Approve  (840, 470)    agent node (final)
//
// Nodes appear in sequence with a small lift+fade; connectors reveal with a
// shrinking dash, then a looping packet travels each edge.

const WF_NODES = [
  { id: "n1", kind: "agent", role: "Extract",  x: 410, y: 410, delay:    0 },
  { id: "n2", kind: "agent", role: "Classify", x: 590, y: 410, delay:  300 },
  { id: "n3", kind: "human", role: "Review",   x: 770, y: 410, delay:  600, initials: "JM" },
  { id: "n4", kind: "agent", role: "Approve",  x: 950, y: 410, delay:  900 },
];
const WF_EDGES = [
  { from: "n1", to: "n2", delay:  200 },
  { from: "n2", to: "n3", delay:  500 },
  { from: "n3", to: "n4", delay:  800 },
];

function WorkflowGraph({ t }) {
  if (t < CE.T12[0]) return null;

  const byId = Object.fromEntries(WF_NODES.map(n => [n.id, n]));

  const nodeP = (n) => {
    const t0 = n.id === "n1" ? CE.T12[0] : CE.B2[0] + n.delay;
    return localE(t, [t0, t0 + 500], easeOut);
  };

  return (
    <g>
      {/* Connectors (behind nodes) */}
      {WF_EDGES.map((e, i) => {
        const from = byId[e.from], to = byId[e.to];
        const edgeStart = CE.B2[0] + e.delay;
        const revealP = localE(t, [edgeStart, edgeStart + 400], easeOut);
        if (revealP <= 0) return null;

        // inset the line so it doesn't poke into node bodies
        const PAD = 42;
        const sx = from.x + PAD, sy = from.y;
        const ex = to.x - PAD,   ey = to.y;
        const midx = sx + (ex - sx) * revealP;

        // packet — loops after reveal
        const packetLoop = 1600;
        const pp = ((t - (edgeStart + 500)) % packetLoop) / packetLoop;
        const showPacket = t > edgeStart + 500 && revealP >= 1;
        const px = sx + (ex - sx) * pp;

        return (
          <g key={i}>
            {/* rail */}
            <line x1={sx} y1={sy} x2={ex} y2={ey}
                  stroke="#000" strokeOpacity="0.18" strokeWidth="1.5" strokeDasharray="3 5"/>
            {/* lit segment */}
            <line x1={sx} y1={sy} x2={midx} y2={ey}
                  stroke="#397ae7" strokeWidth="2" strokeLinecap="round"/>
            {/* arrow head at destination */}
            {revealP > 0.95 && (
              <path d={`M ${ex} ${ey} L ${ex - 5} ${ey - 3.5} L ${ex - 5} ${ey + 3.5} Z`} fill="#397ae7"/>
            )}
            {/* packet */}
            {showPacket && (
              <g transform={`translate(${px}, ${ey})`}>
                <circle r="5" fill="#fff" stroke="#397ae7" strokeWidth="1.5"/>
                <circle r="2" fill="#397ae7"/>
              </g>
            )}
          </g>
        );
      })}

      {/* Nodes */}
      {WF_NODES.map((n) => {
        const p = nodeP(n);
        if (p <= 0) return null;
        // lift + fade in
        const ty = lerp(10, 0, p);

        // n1 is drawn by AgentScene; just render the role chip here
        if (n.id === "n1") {
          return (
            <g key={n.id} transform={`translate(${n.x}, ${n.y + 70 + ty})`} style={{ opacity: p }}>
              <RoleChip label={n.role} kind="agent"/>
            </g>
          );
        }

        return (
          <g key={n.id} style={{ opacity: p }}>
            <g transform={`translate(${n.x}, ${n.y + ty})`}>
              {n.kind === "agent"
                ? <CompactAgentNode/>
                : <HumanAvatarNode initials={n.initials}/>}
            </g>
            <g transform={`translate(${n.x}, ${n.y + 70 + ty})`}>
              <RoleChip label={n.role} kind={n.kind}/>
            </g>
          </g>
        );
      })}
    </g>
  );
}

// --- Compact agent node: mini version of the extraction card (~60x48) ---
function CompactAgentNode() {
  const W = 72, H = 54;
  return (
    <g>
      <rect x={-W/2 + 2} y={-H/2 + 3} width={W} height={H} rx="7" fill="rgba(0,0,0,0.12)"/>
      <rect x={-W/2} y={-H/2} width={W} height={H} rx="7" fill="#fff" stroke="#000" strokeWidth="2"/>
      {/* header strip */}
      <rect x={-W/2} y={-H/2} width={W} height="14" rx="7" fill="#dfeaff"/>
      <rect x={-W/2} y={-H/2 + 7} width={W} height="7" fill="#dfeaff"/>
      <line x1={-W/2} y1={-H/2 + 14} x2={W/2} y2={-H/2 + 14} stroke="#000" strokeWidth="1.5"/>
      {/* sparkle */}
      <g transform={`translate(${-W/2 + 8}, ${-H/2 + 7})`}>
        <path d="M 0 -3 L 1 -1 L 3 0 L 1 1 L 0 3 L -1 1 L -3 0 L -1 -1 Z" fill="#397ae7"/>
      </g>
      {/* body content lines */}
      <rect x={-W/2 + 6} y={-H/2 + 20} width={W - 12} height="4" rx="1" fill="#faf7ec" stroke="#000" strokeWidth="1"/>
      <rect x={-W/2 + 6} y={-H/2 + 28} width={W - 20} height="4" rx="1" fill="#faf7ec" stroke="#000" strokeWidth="1"/>
      <rect x={-W/2 + 6} y={-H/2 + 36} width={W - 14} height="4" rx="1" fill="#faf7ec" stroke="#000" strokeWidth="1"/>
      {/* status dot */}
      <circle cx={W/2 - 8} cy={-H/2 + 7} r="2.5" fill="#95e17c" stroke="#000" strokeWidth="1"/>
    </g>
  );
}

// --- Human avatar: circle with initials, soft purple ---
function HumanAvatarNode({ initials = "JM" }) {
  return (
    <g>
      {/* drop shadow */}
      <circle cx="2" cy="3" r="30" fill="rgba(0,0,0,0.12)"/>
      {/* avatar */}
      <circle cx="0" cy="0" r="30" fill="#e6dfff" stroke="#000" strokeWidth="2"/>
      <text x="0" y="6" fontFamily="Neue Montreal, sans-serif" fontSize="18" fontWeight="500"
            textAnchor="middle" fill="#6d49e0">{initials}</text>
      {/* "person" indicator badge — head + shoulders glyph, corner-mounted */}
      <g transform="translate(22, -22)">
        <circle cx="0" cy="0" r="10" fill="#6d49e0" stroke="#000" strokeWidth="1.5"/>
        {/* head */}
        <circle cx="0" cy="-2.6" r="2.6" fill="#fff"/>
        {/* shoulders */}
        <path d="M -5 5 Q -5 0.8 0 0.8 Q 5 0.8 5 5 Z" fill="#fff"/>
      </g>
    </g>
  );
}

// --- Role chip ---
// Sized for legibility at the B2 camera frame (~810px wide). Previously
// the chip used 9px text which rendered ~6-7px on screen and was barely
// readable in the white card. Bumped to 13px/26h with proportionally
// larger horizontal padding.
function RoleChip({ label, kind }) {
  const bg = kind === "agent" ? "#dfeaff" : "#e6dfff";
  const color = kind === "agent" ? "#397ae7" : "#6d49e0";
  const w = label.length * 9 + 26;
  return (
    <g>
      <rect x={-w / 2} y="0" width={w} height="26" rx="13" fill={bg} stroke="#000" strokeWidth="1.5"/>
      <text x="0" y="17.5" fontFamily="Neue Montreal, sans-serif" fontSize="13" fontWeight="500"
            textAnchor="middle" fill={color}>{label}</text>
    </g>
  );
}

Object.assign(window, { WorkflowGraph });
