// Current Workflow header — four states keyed by props.
// - No workflow: prompt the user to run the architect or load a prior run.
// - Running: stream events as they arrive.
// - Proposed: show the architect's plan + Confirm/Discard.
// - Confirmed: collapsed one-liner; click to expand.

const { useState: useStateWH, useEffect: useEffectWH } = React;

const ConfidenceChip = ({ confidence }) => {
  const cls = confidence === "high" ? "bg-emerald-50 text-emerald-700 border-emerald-200"
            : confidence === "low"  ? "bg-amber-50 text-amber-700 border-amber-200"
            :                          "bg-sky-50 text-sky-700 border-sky-200";
  return (
    <span className={`text-[10px] font-bold uppercase tracking-widest px-2 py-1 rounded-full border ${cls}`}>
      confidence: {confidence || "unknown"}
    </span>
  );
};

const StationRow = ({ s }) => (
  <div className={`flex items-start gap-3 p-3 rounded-lg border ${s.__unknown ? "bg-red-50 border-red-200" : "bg-white border-neutral-200"}`}>
    <span className="text-[10px] font-bold uppercase tracking-widest text-neutral-500 mt-1">{s.plan?.position ?? "?"}</span>
    <div className="flex-1 min-w-0">
      <div className="font-bold text-neutral-900">{s.title}</div>
      {s.plan?.rationale && <div className="text-xs text-neutral-600 mt-1 leading-snug">{s.plan.rationale}</div>}
      {s.__unknown && <div className="text-xs text-red-700 mt-1 font-bold">Station id "{s.id}" is not in the station library.</div>}
    </div>
  </div>
);

const InterpretationRow = ({ oi }) => (
  <div className="text-xs text-neutral-700 p-2 bg-amber-50/40 border border-amber-200 rounded">
    I read <strong>"{oi.i_read}"</strong> as <em>{oi.as}</em>{oi.alternative && <> — alt: <em>{oi.alternative}</em></>}.
    {oi.why_i_chose_this && <div className="text-neutral-500 mt-0.5">Why: {oi.why_i_chose_this}</div>}
  </div>
);

const RejectedRow = ({ r }) => (
  <div className="text-xs text-neutral-600 p-2 bg-neutral-50 border border-neutral-200 rounded">
    <strong>{r.id}</strong>: {r.reason}
  </div>
);

const WorkflowHeader = ({
  state,                    // "empty" | "running" | "proposed" | "confirmed"
  proposedWorkflow,
  workflow,
  runEvents,                // [{ event, data }] while state === "running"
  runElapsedSec,            // number while state === "running"
  unknownIds,               // string[] when state === "proposed"
  onStartArchitect,         // (story: string) => void
  onOpenRunsDrawer,         // () => void
  onConfirm,                // () => void
  onDiscard,                // () => void
  onExpandConfirmed,        // () => void
  workflowRunState,         // "idle" | "running" | "done"
  workflowRunCurrentRole,   // current role name while running
  workflowRunDecision,      // decision string when done ("accept"|"revise"|"escalate")
  onRunWorkflow,            // () => void
}) => {
  const [story, setStory] = useStateWH("");
  const [showRejected, setShowRejected] = useStateWH(false);
  const [showEvents, setShowEvents] = useStateWH(false);

  if (state === "empty") {
    return (
      <section className="bg-white border-y border-neutral-200 px-8 py-6">
        <div className="max-w-3xl mx-auto">
          <h2 className="text-lg font-black text-neutral-800 mb-2">No workflow loaded</h2>
          <p className="text-sm text-neutral-600 mb-4">Paste a story to run the architect, or load a prior run.</p>
          <label htmlFor="architect-story" className="sr-only">Story for the architect</label>
          <textarea
            id="architect-story"
            name="architect-story"
            value={story}
            onChange={(e) => setStory(e.target.value)}
            rows={4}
            className="w-full text-sm font-mono p-3 border border-neutral-300 rounded-lg focus:outline-none focus:border-indigo-400 focus:ring-2 focus:ring-indigo-100"
            placeholder="e.g. I want a confirm dialog on the delete buttons in my Rails admin panel. It should require typing the record name to confirm. Use the existing Tailwind setup."
          />
          <div className="flex gap-3 mt-3">
            <button
              type="button"
              disabled={!story.trim()}
              onClick={() => onStartArchitect(story.trim())}
              className="px-4 py-2 rounded-lg bg-indigo-600 text-white font-bold text-sm hover:bg-indigo-700 disabled:bg-neutral-300 disabled:cursor-not-allowed"
            >
              Run architect
            </button>
            <button
              type="button"
              onClick={onOpenRunsDrawer}
              className="px-4 py-2 rounded-lg bg-white border border-neutral-300 text-neutral-700 font-bold text-sm hover:bg-neutral-50"
            >
              Load prior run
            </button>
          </div>
        </div>
      </section>
    );
  }

  if (state === "running") {
    return (
      <section className="bg-white border-y border-neutral-200 px-8 py-6">
        <div className="max-w-3xl mx-auto">
          <div className="flex items-center gap-3 mb-3">
            <span className="inline-block w-2 h-2 rounded-full bg-indigo-500 animate-pulse" />
            <span className="text-sm font-bold text-neutral-800">Architect running…</span>
            <span className="text-xs text-neutral-500">{runElapsedSec}s elapsed</span>
          </div>
          <button
            type="button"
            onClick={() => setShowEvents((v) => !v)}
            className="text-xs font-bold uppercase tracking-widest text-neutral-500 hover:text-neutral-700 mb-2"
          >
            {showEvents ? "▼" : "▶"} Event stream ({runEvents.length})
          </button>
          {showEvents && (
            <div className="bg-neutral-900 text-neutral-100 font-mono text-xs p-3 rounded-lg max-h-64 overflow-auto">
              {runEvents.map((e, i) => (
                <div key={i} className={
                  e.event === "stderr" ? "text-neutral-400" :
                  e.event === "error" ? "text-red-400" :
                  "text-neutral-100"
                }>
                  <span className="opacity-50">[{e.event}]</span> {typeof e.data === "string" ? e.data : JSON.stringify(e.data).slice(0, 200)}
                </div>
              ))}
            </div>
          )}
        </div>
      </section>
    );
  }

  if (state === "proposed" && proposedWorkflow) {
    const meta = proposedWorkflow.workflowMeta;
    const stations = proposedWorkflow.stations;
    const hasUnknown = unknownIds && unknownIds.length > 0;
    return (
      <section className="bg-white border-y border-neutral-200 px-8 py-6">
        <div className="max-w-3xl mx-auto flex flex-col gap-4">
          {hasUnknown && (
            <div className="bg-red-50 border-2 border-red-300 rounded-lg p-3 text-sm text-red-900">
              <strong>Plan references unknown station{unknownIds.length > 1 ? "s" : ""}:</strong> {unknownIds.join(", ")}.
              Fix <code>station-library.json</code> or re-run the architect. Confirm is disabled.
            </div>
          )}
          <div className="flex items-center gap-3 flex-wrap">
            <h2 className="text-lg font-black text-neutral-800">Proposed workflow</h2>
            <ConfidenceChip confidence={meta?.confidence} />
            <span className="text-xs text-neutral-500">{stations.length} station{stations.length === 1 ? "" : "s"}</span>
          </div>
          {meta?.confidenceRationale && <p className="text-xs text-neutral-600 italic">{meta.confidenceRationale}</p>}
          {meta?.workflowDefinitionOfDone && (
            <div className="text-sm text-neutral-800 bg-indigo-50/40 border border-indigo-200 rounded-lg p-3">
              <div className="text-[10px] font-bold uppercase tracking-widest text-indigo-700 mb-1">Workflow done when</div>
              {meta.workflowDefinitionOfDone}
            </div>
          )}
          <div className="flex flex-col gap-2">
            {stations.map((s) => <StationRow key={s.id} s={s} />)}
          </div>
          {meta?.openInterpretations?.length > 0 && (
            <div className="flex flex-col gap-2">
              <div className="text-[10px] font-bold uppercase tracking-widest text-amber-700">Open interpretations ({meta.openInterpretations.length})</div>
              {meta.openInterpretations.map((oi, i) => <InterpretationRow key={i} oi={oi} />)}
            </div>
          )}
          {meta?.stationsConsideredAndRejected?.length > 0 && (
            <div>
              <button type="button" onClick={() => setShowRejected((v) => !v)} className="text-[10px] font-bold uppercase tracking-widest text-neutral-500 hover:text-neutral-700">
                {showRejected ? "▼" : "▶"} {meta.stationsConsideredAndRejected.length} station{meta.stationsConsideredAndRejected.length === 1 ? "" : "s"} considered and rejected
              </button>
              {showRejected && (
                <div className="flex flex-col gap-2 mt-2">
                  {meta.stationsConsideredAndRejected.map((r, i) => <RejectedRow key={i} r={r} />)}
                </div>
              )}
            </div>
          )}
          <div className="flex gap-3">
            <button
              type="button"
              disabled={hasUnknown}
              onClick={onConfirm}
              className="px-4 py-2 rounded-lg bg-indigo-600 text-white font-bold text-sm hover:bg-indigo-700 disabled:bg-neutral-300 disabled:cursor-not-allowed"
            >
              Confirm
            </button>
            <button
              type="button"
              onClick={onDiscard}
              className="px-4 py-2 rounded-lg bg-white border border-neutral-300 text-neutral-700 font-bold text-sm hover:bg-neutral-50"
            >
              Discard
            </button>
          </div>
        </div>
      </section>
    );
  }

  if (state === "confirmed" && workflow) {
    const decisionCls =
      workflowRunDecision === "accept" ? "bg-emerald-50 text-emerald-700 border-emerald-200" :
      workflowRunDecision === "revise" ? "bg-amber-50 text-amber-700 border-amber-200" :
      workflowRunDecision === "escalate" ? "bg-red-50 text-red-700 border-red-200" :
      "bg-neutral-100 text-neutral-600 border-neutral-200";
    return (
      <section className="bg-white border-y border-neutral-200 px-8 py-3">
        <div className="max-w-3xl mx-auto flex items-center gap-3 text-sm flex-wrap">
          <span className="font-bold text-neutral-800">Workflow:</span>
          <span className="text-neutral-700">{workflow.stations.length} station{workflow.stations.length === 1 ? "" : "s"}</span>
          <ConfidenceChip confidence={workflow.workflowMeta?.confidence} />
          <button type="button" onClick={onExpandConfirmed} className="text-xs font-bold text-indigo-600 hover:text-indigo-800">
            Details
          </button>
          <div className="ml-auto flex items-center gap-2">
            {workflowRunState === "idle" && (
              <button
                type="button"
                onClick={onRunWorkflow}
                className="px-3 py-1.5 rounded-lg bg-emerald-600 text-white font-bold text-xs hover:bg-emerald-700"
              >
                Run Station 1
              </button>
            )}
            {workflowRunState === "running" && (
              <span className="flex items-center gap-1.5 text-xs text-sky-700 font-bold">
                <span className="w-1.5 h-1.5 rounded-full bg-sky-500 animate-pulse shrink-0" />
                {workflowRunCurrentRole ? workflowRunCurrentRole + "…" : "starting…"}
              </span>
            )}
            {workflowRunState === "done" && workflowRunDecision && (
              <span className={`text-[10px] font-bold uppercase tracking-widest px-2 py-1 rounded-full border ${decisionCls}`}>
                {workflowRunDecision}
              </span>
            )}
          </div>
        </div>
      </section>
    );
  }

  return null;
};

window.WorkflowHeader = WorkflowHeader;
