// Task States gallery — six states, HC-012 visual model.
// Each card is wrapped in a mini dotted StationArea. Working and validating
// states show an engaged AgentChip above the card (color-per-agent border).
// Human-review shows the orange override border + "Awaiting review" badge.
// Approved shows the emerald "Shipped" badge in the done lane.
// Stuck shows the red override border + diagnosis + Retry/Rework buttons.

const STATE_SPECS = [
  {
    key: "queued",
    label: "01 — Queued",
    headline: "Waiting in the lane",
    description: "Task has arrived at the station. No agent assigned yet. The card sits with a neutral border inside the dotted StationArea.",
    cues: [
      "Neutral grey border (no agent = no color)",
      "No chip above the card",
      "Dotted station-area border marks the lane",
    ],
  },
  {
    key: "working",
    label: "02 — Working",
    headline: "Agent has picked it up",
    description: "An agent is actively working the task. The card border matches that agent's assigned color. An engaged chip hovers above the card, connected by a tether.",
    cues: [
      "Color-per-agent border (violet, teal, fuchsia, etc.)",
      "Engaged agent chip above the card",
      "Tether line connects chip to card top edge",
    ],
  },
  {
    key: "validating",
    label: "03 — Validating",
    headline: "Validator is reviewing",
    description: "Agent submitted work. The validator's amber chip appears above the card and the card border turns amber while review is in progress.",
    cues: [
      "Amber border (validator color is always amber)",
      "Validator chip (amber) above the card",
      "Agent chip moves to the idle pool in the agents row",
    ],
  },
  {
    key: "human-review",
    label: "04 — Awaiting Review",
    headline: "Human review needed",
    description: "The validator escalated to a human. The card gets an orange border + ring and an 'Awaiting review' badge. No chip is docked — the human is the actor.",
    cues: [
      "Orange border + ring (human-review color override)",
      "'Awaiting review' badge inside the card header",
      "No chip docked above (human is the actor)",
    ],
  },
  {
    key: "approved",
    label: "05 — Approved",
    headline: "Cleared all stations",
    description: "Task passed validation at every station and landed in the Shipped Product lane. The emerald 'Shipped' badge replaces all actor controls.",
    cues: [
      "Emerald 'Shipped' badge in the action bar",
      "No chips or tethers — work is done",
      "Lives in the Shipped Product lane at the end",
    ],
  },
  {
    key: "stuck",
    label: "06 — Stuck",
    headline: "Auto-remediation exhausted",
    description: "The lead retried, the orchestrator tried to reroute, and both gave up. The card turns red with the orchestrator's diagnosis and waits for a human to retry the station or send it back for rework.",
    cues: [
      "Red border + ring (stuck danger color)",
      "Orchestrator diagnosis shown in the card",
      "Retry / Rework buttons — the one human escape hatch",
    ],
  },
];

// One demo task per state. All parented to the design station so chip colors are
// consistent — UI Designer gets sky, UX Researcher gets rose, Design Lead is amber.
const designStation = STATIONS.find((s) => s.id === "design");

const DEMO_TASKS_BY_STATE = {
  queued: {
    id: "gal-q01",
    title: "Onboarding Checklist",
    description: "Add a 4-step checklist to the empty home state for new accounts.",
    area: "design",
    status: "queue",
    assigneeId: null,
    history: [],
  },
  working: {
    id: "gal-w01",
    title: "Landing Page Redesign",
    description: "Update hero section and metrics cards above the fold.",
    area: "design",
    status: "working",
    assigneeId: "d1",
    history: [],
  },
  validating: {
    id: "gal-v01",
    title: "Search Filter Chips",
    description: "Multi-faceted filter chips with clear-all and saved presets.",
    area: "design",
    status: "validating",
    assigneeId: "d2",
    history: [],
  },
  "human-review": {
    id: "gal-hr01",
    title: "Notifications v2",
    description: "Rework grouping and digest cadence — needs more wireframes.",
    area: "design",
    status: "human-review",
    assigneeId: null,
    history: [],
    humanReviewThread: [
      {
        id: "hr-gal-1",
        author: "Dalton",
        avatar: "D",
        when: "5 minutes ago",
        text: "The digest grouping rules don't account for billing alerts — those must still trip immediately.",
      },
    ],
  },
  approved: {
    id: "gal-s01",
    title: "Profile Settings",
    description: "Account, security, and preferences split into tabs.",
    area: "done",
    status: "queue",
    assigneeId: null,
    history: [],
  },
  stuck: {
    id: "gal-st01",
    title: "Database Migration",
    description: "Migrate users table to v2 with backwards-compatible reads.",
    area: "design",
    status: "stuck",
    assigneeId: null,
    history: [],
    stuckReason: "Routed back from Development twice — no upstream station can resolve the missing migration runbook. Orchestrator found no valid route.",
  },
};

// Derive chip agent from task state + station.
function chipAgentFor(spec, task, station) {
  const { colorFor } = window.AgentColors || {};
  if (!colorFor || !station) return null;
  if (task.status === "working" || task.status === "rejected") {
    return station.agents.find((a) => a.id === task.assigneeId) || null;
  }
  if (task.status === "validating") {
    return window.Bridge?.primaryValidator(station) || null;
  }
  return null;
}

const StateColumn = ({ spec }) => {
  const AgentChip = window.AgentChip;
  const { colorFor } = window.AgentColors || {};
  const task = DEMO_TASKS_BY_STATE[spec.key];
  const station = spec.key === "approved" ? undefined : designStation;

  const chipAgent = chipAgentFor(spec, task, station);
  // borderColor: null for queued/approved (handled by TaskCard), explicit color for others.
  // TaskCard internally overrides to 'orange' for human-review regardless of borderColor.
  let borderColor = null;
  if (chipAgent && colorFor) borderColor = colorFor(chipAgent);

  const dotColor =
    spec.key === "queued" ? "bg-neutral-400" :
    spec.key === "working" ? "bg-sky-500" :
    spec.key === "validating" ? "bg-amber-500" :
    spec.key === "human-review" ? "bg-orange-500" :
    spec.key === "stuck" ? "bg-red-500" :
    "bg-emerald-500";

  return (
    <div className="shrink-0 w-[320px] flex flex-col">
      {/* Column header */}
      <div className="px-2 mb-3">
        <div className={`inline-flex items-center text-[10px] font-bold uppercase tracking-[0.18em] px-2 py-1 rounded-md border ${
          spec.key === "queued" ? "bg-neutral-100 text-neutral-700 border-neutral-200" :
          spec.key === "working" ? "bg-sky-50 text-sky-700 border-sky-200" :
          spec.key === "validating" ? "bg-amber-50 text-amber-700 border-amber-200" :
          spec.key === "human-review" ? "bg-orange-50 text-orange-700 border-orange-200" :
          spec.key === "stuck" ? "bg-red-50 text-red-700 border-red-200" :
          "bg-emerald-50 text-emerald-700 border-emerald-200"
        }`}>
          {spec.label}
        </div>
        <h3 className="text-lg font-bold text-neutral-900 mt-2 leading-tight">{spec.headline}</h3>
        <p className="text-sm text-neutral-500 mt-1.5 leading-snug">{spec.description}</p>
      </div>

      {/* Mini StationArea — dotted border matches the real station areas */}
      <div className="relative border-2 border-dashed border-neutral-300 rounded-2xl px-4 pt-3 pb-4 bg-white/60 flex flex-col items-center min-h-[280px]">
        {/* Conveyor belt line */}
        <div className="absolute top-1/2 left-3 right-3 border-t-2 border-dashed border-neutral-200 z-0" />

        {/* Engaged agent chip above the card */}
        {chipAgent && AgentChip && (
          <div className="relative z-20 mb-2 self-center">
            <AgentChip agent={chipAgent} state="engaged" taskId={task.id} />
          </div>
        )}

        {/* Task card */}
        <div className="relative z-10 w-full flex justify-center">
          <TaskCard task={task} station={station} demo borderColor={borderColor} />
        </div>
      </div>

      {/* Visual cues spec */}
      <div className="mt-4 px-2">
        <div className="text-[10px] font-bold uppercase tracking-[0.18em] text-neutral-400 mb-2">Visual cues</div>
        <ul className="flex flex-col gap-1.5">
          {spec.cues.map((c, i) => (
            <li key={i} className="text-xs text-neutral-700 flex items-start gap-2 leading-snug">
              <span className={`mt-1 w-1.5 h-1.5 rounded-full shrink-0 ${dotColor}`} />
              {c}
            </li>
          ))}
        </ul>
      </div>
    </div>
  );
};

const Transition = () => (
  <div className="shrink-0 self-center flex flex-col items-center text-neutral-300 pt-16">
    <ArrowRight size={28} strokeWidth={2.5} />
  </div>
);

const TaskStatesGallery = () => {
  return (
    <section className="border-b border-neutral-200 bg-white">
      <div className="px-8 pt-8 pb-4">
        <div className="flex items-end justify-between gap-6 flex-wrap">
          <div>
            <div className="text-[11px] font-bold uppercase tracking-[0.22em] text-indigo-600 mb-2">Reference</div>
            <h2 className="text-2xl font-black text-neutral-900 tracking-tight leading-tight">The six states a task can be in</h2>
            <p className="text-sm text-neutral-500 mt-2 max-w-2xl leading-relaxed">
              Every task on the assembly line is in exactly one of these states. The card's border color, the agent chip above (color-per-agent), the orange override for human review, and the red override when a task is stuck all communicate where the task sits in the flow.
            </p>
          </div>
          <div className="flex items-center gap-3 text-xs text-neutral-500">
            <span className="inline-flex items-center gap-1.5"><span className="w-2 h-2 rounded-full bg-sky-500" /> Agent (color-per-agent)</span>
            <span className="inline-flex items-center gap-1.5"><span className="w-2 h-2 rounded-full bg-amber-500" /> Validator (always amber)</span>
            <span className="inline-flex items-center gap-1.5"><span className="w-2 h-2 rounded-full bg-orange-500" /> Human review (always orange)</span>
            <span className="inline-flex items-center gap-1.5"><span className="w-2 h-2 rounded-full bg-red-500" /> Stuck (needs a human)</span>
          </div>
        </div>
      </div>

      <div className="overflow-x-auto custom-scrollbar">
        <div className="flex gap-4 px-8 pb-10 min-w-max items-start">
          {STATE_SPECS.map((spec, idx) => (
            <React.Fragment key={spec.key}>
              <StateColumn spec={spec} />
              {idx < STATE_SPECS.length - 1 && <Transition />}
            </React.Fragment>
          ))}
        </div>
      </div>
    </section>
  );
};

window.TaskStatesGallery = TaskStatesGallery;
