// WorkshopDrawer — agent-native right pane. Mode-aware transcript with inline tool-call cards.
// Cross-cutting hero: Plan = footprint preview, Strike = signed ed25519 write.

const { useState: uWS, useEffect: uWE } = React;

// --- seeded transcripts per mode ---------------------------------------------
// Tenant-aware seed builder. Tritan-flavored hardcoded WO ids used to live
// in the line/traveler seeds, leaking into Aetherion/Mittelstand sessions
// via the non-Tritan fallback at the bottom of WorkshopDrawer. Derive the
// WO id from tenant.work_orders[0] so non-Tritan tenants see their own
// batch ids instead of Tritan's turbine WO.
function buildWorkshopSeeds(tenant) {
  const _wo = (tenant && tenant.work_orders && tenant.work_orders[0] && tenant.work_orders[0].id) || "WO-—";
  return {
  forge: [
    { kind: "user", text: "show me the design-to-manufacturing gap on HTU-220.10.02 rev C" },
    {
      kind: "agent",
      text: "Diffed E-BOM rev C against last released M-BOM. The transform produced 38 consumable injections and one new test station. Lints flagged 6 issues — 2 critical worth a look.",
      calls: [
        {
          id: "tc-001",
          name: "forge.transform_ebom_to_mbom",
          status: "complete",
          sig: "ed25519:0xa3f29b71…1c4d",
          params: { part: "HTU-220.10.02", rev: "C", config: "as-designed", inject_consumables: true, inject_tests: true },
          result: { items_in: 112, items_out: 157, consumables_added: 38, tests_added: 7, took_ms: 412 },
        },
        {
          id: "tc-002",
          name: "forge.run_dfm_lints",
          status: "complete",
          sig: "ed25519:0x7e11d40c…9b2a",
          params: { part: "HTU-220.10.02", rev: "C", ruleset: "dfm/v3.2" },
          result: { critical: 2, minor: 4, top: ["L-8 cure window vs press throughput", "datum B drift on STA-019 fixture"] },
        },
      ],
    },
    { kind: "user", text: "create the ECO and run the supplier alt search" },
    {
      kind: "agent",
      text: "Drafted ECO-2611 covering laminate L-7 → L-8 and the harness reroute. The chip below is unsigned — Strike to commit, or Plan to preview the footprint.",
      calls: [
        {
          id: "tc-003",
          name: "forge.create_eco",
          status: "pending",
          sig: "ed25519:0x — unsigned",
          params: { title: "L-7→L-8 + harness reroute", parts: ["HTU-220.10.02", "HTU-220.40.02"], baseline: "rev-C" },
          result: null,
        },
        {
          id: "tc-004",
          name: "supplier.find_alternates",
          status: "running",
          sig: "ed25519:0x — pending",
          params: { sub: "SUB-A12", region: ["NA", "EU"], lead_max_days: 21 },
          result: null,
        },
      ],
    },
    { kind: "user", text: "what's the cost cascade if I substitute SUB-A12 with SUB-A12B?" },
    {
      kind: "agent",
      text: "Net unit delta +$340, lead-time -1.2d, weight neutral. Cascade lifts ST-20 takt by 0.4%.",
      calls: [
        {
          id: "tc-005",
          name: "forge.cost_rollup",
          status: "complete",
          sig: "ed25519:0xb9402af1…8e77",
          params: { swap: { from: "SUB-A12", to: "SUB-A12B" }, scope: "HTU-220.*", currency: "USD" },
          result: { unit_delta: 340.18, lead_delta_days: -1.2, weight_delta_kg: 0.0, takt_delta_pct: 0.4 },
        },
      ],
    },
  ],

  plan: [
    { kind: "user", text: "what if I move CDR by 2 weeks?" },
    {
      kind: "agent",
      text: "Replanned the OAM program at +14d. Critical path shifts from ST-30 to ST-40 (electrical). Monte Carlo says P50 ship slips 9d, P95 slips 22d.",
      calls: [
        {
          id: "tc-101",
          name: "plan.replan_program",
          status: "complete",
          sig: "ed25519:0xc81f2a30…44da",
          params: { program: "OAM", milestone: "CDR", delta_days: 14 },
          result: { new_critical_path: "ST-40", float_consumed_days: 11, downstream_milestones_shifted: 7 },
        },
        {
          id: "tc-102",
          name: "plan.monte_carlo_forecast",
          status: "complete",
          sig: "ed25519:0xf1c0bb4e…2218",
          params: { samples: 5000, seed: "OAM-2026-04" },
          result: { p50_days: 9, p80_days: 16, p95_days: 22, confidence: "tight" },
        },
      ],
    },
    { kind: "user", text: "show me the capacity impact" },
    {
      kind: "agent",
      text: "Cell-02 absorbs the slip; Cell-04 stays under-utilized at 62%. No capex required, but you'll need 2 extra harness techs for week 31.",
      calls: [
        {
          id: "tc-103",
          name: "plan.allocate_capacity",
          status: "complete",
          sig: "ed25519:0x4d1e8a90…77c1",
          params: { window: "wk29-wk34", balance: "absorb-slip" },
          result: { cell_02_util: 0.94, cell_04_util: 0.62, headcount_delta: { harness: +2 } },
        },
      ],
    },
    { kind: "user", text: "commit the move" },
    {
      kind: "agent",
      text: "Baseline-shift draft is staged. Plan to footprint, Strike to sign.",
      calls: [
        {
          id: "tc-104",
          name: "plan.commit_baseline",
          status: "pending",
          sig: "ed25519:0x — unsigned",
          params: { program: "OAM", baseline: "B-04", reason: "CDR +14d absorb" },
          result: null,
        },
      ],
    },
  ],

  build: [
    { kind: "user", text: "draft the routing for HTU-220.10.02 rev C" },
    {
      kind: "agent",
      text: "Routing draft is 22 stations across 4 cells. Tooling check ran in parallel — STA-019 is missing a CMM-3 cal cert.",
      calls: [
        {
          id: "tc-201",
          name: "build.draft_routing",
          status: "complete",
          sig: "ed25519:0x09d4e2bb…aa10",
          params: { part: "HTU-220.10.02", rev: "C", strategy: "balanced-takt" },
          result: { stations: 22, cells: 4, total_hours: 38.4, longest_op_min: 92 },
        },
        {
          id: "tc-202",
          name: "build.check_tooling",
          status: "complete",
          sig: "ed25519:0x6622f11a…5bc4",
          params: { stations: "ST-10..ST-50", cal_window_days: 90 },
          result: { ready: 21, blocked: 1, blockers: [{ st: "STA-019", reason: "CMM-3 cal cert expired 2026-04-09" }] },
        },
      ],
    },
    { kind: "user", text: "release once tooling clears" },
    {
      kind: "agent",
      text: "Release is gated on STA-019. Ready to fire — Strike will publish to the line, Plan will dry-run the rollout.",
      calls: [
        {
          id: "tc-203",
          name: "build.release_routing",
          status: "pending",
          sig: "ed25519:0x — unsigned",
          params: { routing_id: "RT-HTU-220-C", gate: "tooling.clear:STA-019", auto_release: true },
          result: null,
        },
      ],
    },
  ],

  line: [
    { kind: "user", text: "show readiness for tomorrow's run" },
    {
      kind: "agent",
      text: _wo + " is 91% green. SUB-A12 is short by 14 units — single risk to start. Pulled an expedite quote from Hexcel.",
      calls: [
        {
          id: "tc-301",
          name: "line.run_readiness_check",
          status: "complete",
          sig: "ed25519:0x2210e7cd…b09f",
          params: { wo: _wo, date: "2026-04-29" },
          result: { ready_pct: 0.91, shorts: [{ pn: "SUB-A12", qty: 14 }], operators: "ok", tooling: "ok" },
        },
        {
          id: "tc-302",
          name: "supplier.expedite_quote",
          status: "complete",
          sig: "ed25519:0xee03b8ff…1d50",
          params: { pn: "SUB-A12", qty: 14, eta_required_h: 20 },
          result: { vendor: "Hexcel", cost_delta_usd: 340, eta_h: 18, accepts_po: true },
        },
      ],
    },
    { kind: "user", text: "expedite and reassign operator" },
    {
      kind: "agent",
      text: "T. Nasser moved to STA-014 for the run; harness backup queued. Expedite is staged but not yet signed.",
      calls: [
        {
          id: "tc-303",
          name: "line.assign_operator",
          status: "complete",
          sig: "ed25519:0x55a90c12…34ee",
          params: { wo: _wo, station: "STA-014", operator: "T. Nasser" },
          result: { confirmed: true, prior_assignment: "STA-021 (reassigned to D. Olin)" },
        },
        {
          id: "tc-304",
          name: "supplier.commit_expedite",
          status: "pending",
          sig: "ed25519:0x — unsigned",
          params: { vendor: "Hexcel", pn: "SUB-A12", qty: 14, po_value_usd: 340 },
          result: null,
        },
      ],
    },
  ],

  traveler: [
    { kind: "user", text: "what does STA-014 history look like for this part?" },
    {
      kind: "agent",
      text: "Last 30 batches at STA-014 averaged 19 minutes, σ=2.4. Two outliers — both correlated to fixture-7 wear.",
      calls: [
        {
          id: "tc-401",
          name: "traveler.station_history",
          status: "complete",
          sig: "ed25519:0x771a44c8…0ee3",
          params: { station: "STA-014", part: "HTU-220.10.02", n: 30 },
          result: { avg_min: 19, sigma_min: 2.4, outliers: 2, fixture_corr: "fix-7" },
        },
      ],
    },
    { kind: "user", text: "any NCRs that correlate to this routing?" },
    {
      kind: "agent",
      text: "One NCR last week at STA-019 — CFRP datum B drift. Already covered by ECO-2451; rev C absorbs it.",
      calls: [
        {
          id: "tc-402",
          name: "traveler.correlate_ncr",
          status: "complete",
          sig: "ed25519:0xa01ff3d6…77b8",
          params: { wo: _wo, lookback_days: 14 },
          result: { ncrs: 1, top: { id: "NCR-0418", st: "STA-019", cause: "datum-B drift", eco: "ECO-2451" } },
        },
        {
          id: "tc-403",
          name: "traveler.capture_measurement",
          status: "running",
          sig: "ed25519:0x — pending",
          params: { wo: _wo, station: "STA-014", probe: "CMM-3", spec: "datum-A flat 0.05mm" },
          result: null,
        },
      ],
    },
  ],
  };
}

// Module-level fallback seeds keyed by mode shape so any caller that still
// expects the old WORKSHOP_SEEDS const (e.g. WorkshopDrawer's defensive
// `|| WORKSHOP_SEEDS.forge`) keeps working. Built with no tenant, so WO
// substitutes to "WO-—" — safe for any tenant context.
const WORKSHOP_SEEDS = buildWorkshopSeeds(null);

// --- helpers -----------------------------------------------------------------
function statusTone(s) {
  if (s === "complete") return "ok";
  if (s === "running") return "info";
  if (s === "failed") return "err";
  return ""; // pending
}

function modePrefix(mode) {
  return `${mode}://workshop`;
}

// --- inline tool-call card ---------------------------------------------------
function ToolCallCard({ call, onPlan, onStrike }) {
  const [open, setOpen] = uWS(false);
  const [local, setLocal] = uWS({ status: call.status, sig: call.sig, result: call.result });
  const tone = statusTone(local.status);
  const isPending = local.status === "pending";
  const isRunning = local.status === "running";

  return (
    <div style={{
      border: "1px solid var(--line)",
      borderRadius: 5,
      background: "var(--bg-1)",
      fontFamily: "var(--font-mono)",
      fontSize: 12,
      margin: "6px 0",
      overflow: "hidden",
    }}>
      {/* header */}
      <div
        role="button"
        tabIndex={0}
        onClick={() => setOpen(!open)}
        onKeyDown={(e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); setOpen(!open); } }}
        style={{
          padding: "8px 10px",
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
          gap: 8,
          cursor: "pointer",
          background: open ? "var(--bg-2)" : "transparent",
        }}
      >
        <div style={{ display: "flex", alignItems: "center", gap: 6, minWidth: 0 }}>
          <span style={{ color: "var(--ink-3)", width: 10, textAlign: "center" }}>
            {open ? "▾" : "▸"}
          </span>
          {I("Settings", { size: 11 })}
          <span style={{ color: "var(--accent)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
            {call.name}
          </span>
        </div>
        <Pill tone={tone}>
          {isRunning ? <span className="pulse">{local.status}</span> : local.status}
        </Pill>
      </div>

      {/* body */}
      {open && (
        <div style={{
          padding: 10,
          borderTop: "1px solid var(--line-soft)",
          background: "var(--bg-inset)",
          color: "var(--ink-2)",
        }}>
          <div style={{ marginBottom: 8 }}>
            <div style={{ color: "var(--ink-3)", fontSize: 12, marginBottom: 3, textTransform: "uppercase", letterSpacing: 0.06 }}>
              params
            </div>
            <pre style={{
              margin: 0,
              fontFamily: "var(--font-mono)",
              fontSize: 12,
              lineHeight: 1.5,
              color: "var(--ink-2)",
              whiteSpace: "pre-wrap",
              wordBreak: "break-all",
            }}>
              {JSON.stringify(call.params ?? {}, null, 2)}
            </pre>
          </div>
          <div>
            <div style={{ color: "var(--ink-3)", fontSize: 12, marginBottom: 3, textTransform: "uppercase", letterSpacing: 0.06 }}>
              result
            </div>
            <pre style={{
              margin: 0,
              fontFamily: "var(--font-mono)",
              fontSize: 12,
              lineHeight: 1.5,
              color: local.result ? "var(--ink-2)" : "var(--ink-3)",
              whiteSpace: "pre-wrap",
              wordBreak: "break-all",
            }}>
              {local.result ? JSON.stringify(local.result, null, 2) : "// not yet — Strike to execute"}
            </pre>
          </div>
        </div>
      )}

      {/* footer */}
      <div style={{
        padding: "6px 10px",
        borderTop: "1px solid var(--line-soft)",
        display: "flex",
        alignItems: "center",
        justifyContent: "space-between",
        gap: 8,
      }}>
        <span style={{
          color: "var(--ink-3)",
          fontSize: 12,
          overflow: "hidden",
          textOverflow: "ellipsis",
          whiteSpace: "nowrap",
          minWidth: 0,
        }}>
          {local.sig}
        </span>
        <div style={{ display: "flex", alignItems: "center", gap: 4, flexShrink: 0 }}>
          {isPending && (
            <>
              {(() => {
                const _planBtnStyle = {
                  height: 20,
                  padding: "0 8px",
                  fontFamily: "var(--font-mono)",
                  fontSize: 12,
                  letterSpacing: 0.04,
                  textTransform: "uppercase",
                  border: "1px solid var(--line)",
                  background: "var(--bg-2)",
                  color: "var(--ink-2)",
                  borderRadius: 3,
                  cursor: "pointer",
                };
                const _strikeBtnStyle = {
                  height: 20,
                  padding: "0 8px",
                  fontFamily: "var(--font-mono)",
                  fontSize: 12,
                  fontWeight: 600,
                  letterSpacing: 0.04,
                  textTransform: "uppercase",
                  border: "1px solid var(--accent-2)",
                  background: "var(--accent)",
                  color: "var(--accent-ink)",
                  borderRadius: 3,
                  cursor: "pointer",
                };
                return (
                  <>
                    <button
                      onClick={(e) => {
                        e.stopPropagation();
                        setLocal({
                          status: "complete",
                          sig: "ed25519:preview…" + String(call.id).slice(-4),
                          result: { footprint_preview: true, writes: false, call_id: call.id },
                        });
                        onPlan && onPlan(call.id);
                      }}
                      style={_planBtnStyle}
                      title="footprint preview · no writes"
                    >
                      Plan
                    </button>
                    <button
                      onClick={(e) => {
                        e.stopPropagation();
                        setLocal({
                          status: "complete",
                          sig: "ed25519:signed…" + String(call.id).slice(-4),
                          result: { signed: true, writes: true, call_id: call.id },
                        });
                        onStrike && onStrike(call.id);
                      }}
                      style={_strikeBtnStyle}
                      title="signed ed25519 write"
                    >
                      Strike
                    </button>
                  </>
                );
              })()}
            </>
          )}
          {isRunning && (
            <span className="pulse" style={{ fontSize: 12, color: "var(--info)" }}>
              ◐ executing…
            </span>
          )}
        </div>
      </div>
    </div>
  );
}

// --- turn renderers ----------------------------------------------------------
function UserTurn({ text }) {
  const _userBubbleStyle = {
    maxWidth: "80%",
    background: "var(--bg-2)",
    border: "1px solid var(--line-soft)",
    borderRadius: 6,
    padding: "8px 10px",
    fontSize: 12,
    color: "var(--ink)",
    lineHeight: 1.4,
  };
  return (
    <div style={{ display: "flex", justifyContent: "flex-end", margin: "12px 0" }}>
      <div style={_userBubbleStyle}>
        {text}
      </div>
    </div>
  );
}

function AgentTurn({ text, calls, onPlan, onStrike }) {
  return (
    <div style={{ margin: "12px 0" }}>
      <div className="mono" style={{
        fontSize: 12,
        color: "var(--accent)",
        textTransform: "uppercase",
        letterSpacing: 0.08,
        marginBottom: 4,
      }}>
        Forge
      </div>
      {text && (
        <div style={{ fontSize: 12.5, lineHeight: 1.5, color: "var(--ink-2)" }}>
          {text}
        </div>
      )}
      {calls && calls.map(c => (
        <ToolCallCard key={c.id} call={c} onPlan={onPlan} onStrike={onStrike} />
      ))}
    </div>
  );
}

// --- main drawer -------------------------------------------------------------
function WorkshopDrawer({ open, mode = "forge", onClose, onPlan, onStrike }) {
  const [input, setInput] = uWS("");

  uWE(() => {
    if (!open) return;
    const onKey = (e) => {
      if (e.key === "Escape") { onClose && onClose(); }
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open, onClose]);

  // Tenant-aware seed selection. For Tritan (pump CDMO), synthesize transcripts from MODE_FCP_TEMPLATES
  // so the drawer reflects pump operations instead of leaking HTU-220 turbine references.
  const _wsTenant = (typeof getActiveTenant === "function") ? getActiveTenant() : null;
  const _wsIsTritan = _wsTenant && _wsTenant.tenant && _wsTenant.tenant.id === "tritan";
  const _wsTritanSeeds = _wsIsTritan && typeof window !== "undefined" && window.MODE_FCP_TEMPLATES
    ? (function buildTritanSeeds() {
        const t = window.MODE_FCP_TEMPLATES;
        const tagline = {
          forge:    "Show me the design-to-cost gap on M-27418 vs predecessor M-26102.",
          plan:     "Lock copper at today's price for the 8-week Helios production window.",
          build:    "Release routing rev C — gates updated post-PFMEA scrub.",
          line:     "Castings short by 12 units. Expedite from Athena or dual-source?",
          traveler: "Capture stator bore on TPX-H-0011 — out of tol vs spec.",
          auditor:  "Filter ledger to WO-44219 only. Export the audit pack.",
        };
        const result = {};
        Object.keys(t).forEach(function(m) {
          const tmpls = t[m] || [];
          result[m] = [
            { kind: "user", text: tagline[m] || ("Show " + m + " options for the M-27418 program.") },
            {
              kind: "agent",
              text: "Inspected active tenant (Tritan Pumps). Surfaced the relevant tool-call templates for " + m + " mode — pick one to plan, then strike.",
              calls: tmpls.slice(0, 2).map(function(x, i) {
                return {
                  id: "tc-" + m + "-" + (i+1),
                  name: x.template.split("(")[0],
                  status: i === 0 ? "complete" : "draft",
                  sig: i === 0 ? "ed25519:0x" + (m + "0000").slice(0,4) + "…" + (m + "9999").slice(-4) : null,
                  params: { tenant: "tritan", mode: m },
                  result: i === 0 ? { effect: "preview-ready", took_ms: 180 + i*40 } : null,
                };
              }),
            },
          ];
        });
        return result;
      })()
    : null;
  // Non-Tritan tenants get tenant-derived seeds so Aetherion/Mittelstand see
  // their own work-order id instead of Tritan's hardcoded turbine WO.
  const _activeSeeds = _wsTritanSeeds || buildWorkshopSeeds(_wsTenant);
  const turns = _activeSeeds[mode] || _activeSeeds.forge || WORKSHOP_SEEDS.forge;

  const handleSend = () => {
    setInput("");
  };

  const _drawerStyle = {
    position: "fixed",
    top: 0,
    right: 0,
    height: "100vh",
    width: 440,
    zIndex: 50,
    background: "var(--bg-1)",
    borderLeft: "1px solid var(--line-strong)",
    display: "flex",
    flexDirection: "column",
    transform: open ? "translateX(0)" : "translateX(100%)",
    transition: "transform 200ms ease",
    pointerEvents: open ? "auto" : "none",
  };
  const _drawerHeaderStyle = {
    height: 44,
    padding: "10px 14px",
    borderBottom: "1px solid var(--line)",
    display: "flex",
    alignItems: "center",
    justifyContent: "space-between",
    flexShrink: 0,
  };
  const _drawerHeaderLabelStyle = {
    fontSize: 12,
    color: "var(--accent)",
    overflow: "hidden",
    textOverflow: "ellipsis",
    whiteSpace: "nowrap",
  };
  const _drawerCloseBtnStyle = {
    width: 22,
    height: 22,
    border: "1px solid var(--line)",
    background: "var(--bg-2)",
    color: "var(--ink-2)",
    borderRadius: 3,
    cursor: "pointer",
    display: "inline-flex",
    alignItems: "center",
    justifyContent: "center",
    padding: 0,
  };
  const _drawerInputBarStyle = {
    height: 52,
    padding: "10px 12px",
    borderTop: "1px solid var(--line-soft)",
    display: "flex",
    alignItems: "center",
    gap: 8,
    flexShrink: 0,
    background: "var(--bg-1)",
  };
  const _drawerModeBadgeStyle = {
    fontFamily: "var(--font-mono)",
    fontSize: 12,
    padding: "3px 7px",
    background: "var(--accent)",
    color: "var(--accent-ink)",
    borderRadius: 3,
    textTransform: "lowercase",
    letterSpacing: 0.04,
    fontWeight: 600,
  };

  return (
    <div
      role="dialog"
      aria-hidden={!open}
      style={_drawerStyle}
    >
      {/* HEADER */}
      <div style={_drawerHeaderStyle}>
        <div style={{ display: "flex", alignItems: "center", gap: 8, minWidth: 0 }}>
          <span className="mono" style={_drawerHeaderLabelStyle}>
            {modePrefix(mode)}
          </span>
          <Pill tone="ok" dot={true}>live</Pill>
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
          <span className="kbd">⌘\</span>
          <button
            onClick={onClose}
            title="close (Esc)"
            style={_drawerCloseBtnStyle}
          >
            {I("X", { size: 12 })}
          </button>
        </div>
      </div>

      {/* TRANSCRIPT */}
      <div style={{
        flex: 1,
        overflowY: "auto",
        padding: 12,
        minHeight: 0,
      }}>
        {turns.map((t) => (
          t.kind === "user"
            ? <UserTurn key={t.text} text={t.text} />
            : <AgentTurn key={t.text} text={t.text} calls={t.calls} onPlan={onPlan} onStrike={onStrike} />
        ))}
        <div style={{ height: 8 }} />
      </div>

      {/* INPUT BAR */}
      <div style={_drawerInputBarStyle}>
        <span style={_drawerModeBadgeStyle}>
          {mode}
        </span>
        {(() => {
          const _drawerInputStyle = {
            flex: 1,
            background: "transparent",
            border: 0,
            outline: 0,
            color: "var(--ink)",
            fontFamily: "var(--font-ui)",
            fontSize: 12.5,
            minWidth: 0,
          };
          return (
            <input
              id="forge-workshop-prompt"
              name="forge-workshop-prompt"
              aria-label="Ask Forge"
              value={input}
              onChange={(e) => setInput(e.target.value)}
              onKeyDown={(e) => { if (e.key === "Enter") handleSend(); }}
              placeholder="Ask Forge to…"
              style={_drawerInputStyle}
            />
          );
        })()}
        <Btn variant="primary" size="sm" onClick={handleSend}>Send</Btn>
      </div>
    </div>
  );
}

Object.assign(window, { WorkshopDrawer });
