// Station Flow — horizontal pipeline showing the order of agents that
// will work on a task at this station, with a validator step between
// each agent. Each agent step has a per-task toggle to skip its
// post-validator (used when an agent is consistently reliable).
//
// Live status comes from the existing pills on the modal — this view is
// a STATIC PLAN, not a progress indicator.

const SF_PRIMARY = "indigo";

// Resolve the flow for a task. Falls back to the station's defaultFlow
// when the task hasn't customized it. Returns
//   [{ agentId, agent, validateAfter }]
const resolveFlow = (task, station) => {
  if (!station) return [];
  const customSteps = task?.flow?.steps;
  const baseSteps = customSteps && customSteps.length
    ? customSteps
    : (station.defaultFlow || station.agents.map((a) => a.id)).map((id) => ({ agentId: id, validateAfter: true }));
  return baseSteps
    .map((s) => {
      const agent = station.agents.find((a) => a.id === s.agentId);
      if (!agent) return null;
      return { ...s, agent };
    })
    .filter(Boolean);
};

// One agent chip in the pipeline.
const FlowAgentChip = ({ agent }) => (
  <div className="inline-flex items-center gap-2 bg-white border-2 border-neutral-300 rounded-full pl-1 pr-3 py-1 shadow-sm">
    <div className="w-7 h-7 rounded-full bg-indigo-100 text-indigo-700 flex items-center justify-center text-xs font-bold ring-2 ring-white">
      {agent.name.charAt(0)}
    </div>
    <div className="flex flex-col leading-tight">
      <span className="text-[9px] font-bold uppercase tracking-widest text-neutral-400">Agent</span>
      <span className="text-xs font-bold text-neutral-900">{agent.name}{agent.role && agent.role !== agent.name && (<span className="text-neutral-400 font-medium"> · {agent.role}</span>)}</span>
    </div>
  </div>
);

// Validator chip (always at the start). Prop is still named `manager` to keep
// the chip's interface stable; callers pass primaryValidator(station) into it.
const FlowManagerChip = ({ manager }) => {
  if (!manager) return null;
  return (
  <div className="inline-flex items-center gap-2 bg-amber-50 border-2 border-amber-300 rounded-full pl-1 pr-3 py-1 shadow-sm">
    <div className="w-7 h-7 rounded-full bg-amber-200 text-amber-900 flex items-center justify-center text-xs font-bold ring-2 ring-white">
      {manager.name?.charAt(0)}
    </div>
    <div className="flex flex-col leading-tight">
      <span className="text-[9px] font-bold uppercase tracking-widest text-amber-700">Validator</span>
      <span className="text-xs font-bold text-neutral-900">{manager.name}{manager.role && manager.role !== manager.name && (<span className="text-neutral-400 font-medium"> · {manager.role}</span>)}</span>
    </div>
  </div>
  );
};

// Validator step — small chip with a check icon. Toggleable.
const FlowValidatorChip = ({ enabled, onToggle, disabled = false }) => {
  const isOn = enabled !== false;
  return (
    <button
      type="button"
      onClick={disabled ? undefined : onToggle}
      disabled={disabled}
      title={isOn ? "Validator runs after this agent. Click to skip." : "Validator skipped after this agent. Click to re-enable."}
      className={`inline-flex items-center gap-1.5 rounded-full pl-2 pr-2.5 py-1.5 border-2 leading-none transition ${
        disabled ? "cursor-default" : "cursor-pointer"
      } ${
        isOn
          ? "bg-amber-50 border-amber-300 text-amber-800 hover:bg-amber-100"
          : "bg-neutral-50 border-neutral-300 border-dashed text-neutral-400 hover:bg-neutral-100"
      }`}
    >
      {isOn ? (
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round" aria-hidden>
          <polyline points="20 6 9 17 4 12" />
        </svg>
      ) : (
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden>
          <line x1="5" y1="12" x2="19" y2="12" />
        </svg>
      )}
      <span className="text-[10px] font-bold uppercase tracking-widest">
        {isOn ? "Validator" : "Skip"}
      </span>
    </button>
  );
};

// Connector arrow between steps.
const FlowArrow = () => (
  <div className="flex items-center text-neutral-300 shrink-0" aria-hidden>
    <svg width="20" height="14" viewBox="0 0 20 14" fill="none">
      <line x1="0" y1="7" x2="16" y2="7" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
      <polyline points="12 3, 16 7, 12 11" stroke="currentColor" strokeWidth="2" fill="none" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  </div>
);

// Final "next station" / shipped chip.
const FlowEndChip = ({ label, icon }) => (
  <div className="inline-flex items-center gap-2 bg-emerald-50 border-2 border-emerald-300 rounded-full px-3 py-2 shadow-sm">
    <div className="w-6 h-6 rounded-full bg-emerald-500 text-white flex items-center justify-center" aria-hidden>
      {icon || (
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round">
          <polyline points="20 6 9 17 4 12" />
        </svg>
      )}
    </div>
    <span className="text-[11px] font-bold uppercase tracking-widest text-emerald-800">{label}</span>
  </div>
);

const StationFlow = ({ task, station, onToggleValidator, nextStationTitle }) => {
  if (!station) return null;
  const steps = resolveFlow(task, station);
  const isCustomized = !!(task?.flow?.steps && task.flow.steps.length);

  return (
    <section className="bg-white border-2 border-neutral-200 rounded-2xl p-6">
      <div className="flex items-center justify-between gap-4 mb-1 flex-wrap">
        <div className="flex items-center gap-2">
          <span className="text-[11px] font-bold uppercase tracking-[0.18em] text-neutral-500">Station Flow</span>
          {isCustomized && (
            <span className="text-[10px] font-bold uppercase tracking-widest text-indigo-700 bg-indigo-50 border border-indigo-200 px-1.5 py-0.5 rounded">
              Customized for this task
            </span>
          )}
        </div>
        {onToggleValidator && (
          <span className="text-[11px] text-neutral-500">
            Click a <span className="font-bold text-amber-700">Validator</span> step to skip it for this task.
          </span>
        )}
      </div>
      <p className="text-xs text-neutral-500 mb-4 max-w-2xl leading-relaxed">
        Order the {window.Bridge?.primaryValidator(station)?.name?.split(" ")[0]} (validator) will run for this station. Validator runs after every agent by default{onToggleValidator ? " — turn it off for an agent that delivers consistently." : "."}
      </p>

      <div className="overflow-x-auto -mx-2 px-2 pb-2 custom-scrollbar">
        <div className="inline-flex items-center gap-2 min-w-max">
          <FlowManagerChip manager={window.Bridge?.primaryValidator(station)} />
          <FlowArrow />
          {steps.map((step, idx) => (
            <React.Fragment key={`${step.agentId}-${idx}`}>
              <FlowAgentChip agent={step.agent} />
              <FlowArrow />
              <FlowValidatorChip
                enabled={step.validateAfter}
                onToggle={() => onToggleValidator && onToggleValidator(idx)}
              />
              <FlowArrow />
            </React.Fragment>
          ))}
          <FlowEndChip label={nextStationTitle ? `Next: ${nextStationTitle}` : "Shipped"} />
        </div>
      </div>

      {steps.some((s) => s.validateAfter === false) && (
        <div className="mt-4 text-[11px] text-neutral-500 flex items-center gap-2">
          <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden>
            <circle cx="12" cy="12" r="10" />
            <line x1="12" y1="8" x2="12" y2="12" />
            <line x1="12" y1="16" x2="12.01" y2="16" />
          </svg>
          Validator is skipped after {steps.filter((s) => s.validateAfter === false).length} agent(s). Issues from those agents won't be caught until the next validator runs.
        </div>
      )}
    </section>
  );
};

window.StationFlow = StationFlow;
window.resolveFlow = resolveFlow;
