// Agent Jobs — pipeline page (job-card rows)
const { useState: useStateJobs, useMemo: useMemoJobs } = React;

function fmtMoney(n) {
  if (n >= 1000) return `$${(n/1000).toFixed(1)}K`;
  return `$${n}`;
}
function fmtMoneyExact(n) { return `$${n.toLocaleString()}`; }

function aggregateLine(jobs) {
  const onJob = jobs.filter(j => j.state === 'on_the_job');
  const pipeline = jobs.filter(j => ['discovered','scoping','onboarding'].includes(j.state));
  const totalCost = onJob.reduce((s,j) => s + (j.monthly_cost_usd || 0), 0);
  return `${onJob.length} in production  ·  ${pipeline.length} in pipeline  ·  ${fmtMoney(totalCost)}/mo total  ·  last started 4 days ago`;
}

const FUNCTION_LABEL = {
  finance: 'Finance', customer: 'Customer', sales: 'Sales',
  ops: 'Ops', legal: 'Legal', engineering: 'Engineering',
};

// Stage indices for the strip
const STAGE_ORDER = ['discovered','scoping','onboarding','on_the_job'];
const STAGE_SHORT = {
  discovered: 'Triage',
  scoping: 'Setup',
  onboarding: 'Onboarding',
  on_the_job: 'Production',
};

// =================================================================
// Per-stage center cell — the "current stage" data row inside the card
// =================================================================

function StageCenterDiscovered({ j }) {
  // Unused now — Triage uses TriageCard which replaces JobCard entirely.
  return null;
}

function TriageCard({ j }) {
  const peopleVisible = j.people.slice(0, 3);
  const peopleMore = j.people.length - peopleVisible.length;
  const toolsVisible = j.tools.slice(0, 3);
  const toolsMore = j.tools.length - toolsVisible.length;
  return (
    <div className="triage-card">
      <div className="triage-main">
        <div className="tc-head">
          <h3 className="tc-title">{j.title}</h3>
          <span className={`tc-source tc-source-${j.source.kind}`}>{j.source.label}</span>
        </div>
        <p className="tc-desc">{j.description}</p>
        <p className="tc-why">{j.why}</p>

        <div className="tc-stats">
          <span className="tc-stat">
            <span className="tc-stat-label">People</span>
            <span className="tc-people-stack">
              {peopleVisible.map((p, i) => (
                <span key={i} className="tc-person-avatar">{p}</span>
              ))}
            </span>
            {peopleMore > 0 && <span className="tc-stat-more">+{peopleMore}</span>}
          </span>
          <span className="tc-stat-sep" aria-hidden="true">·</span>
          <span className="tc-stat">
            <span className="tc-stat-label">Tools</span>
            <span className="tc-tool-stack">
              {toolsVisible.map((t, i) => (
                <span key={t} className="tc-tool-dot-wrap" title={t}>
                  <IntegrationDot name={t}/>
                </span>
              ))}
            </span>
            {toolsMore > 0 && <span className="tc-stat-more">+{toolsMore}</span>}
          </span>
        </div>
      </div>

      <div className="triage-side">
        <div>
          <div className="tc-side-label">Expected value</div>
          <div className="tc-value-headline">{j.value.headline}</div>
        </div>
        <div className="tc-side-footer">
          <span className="tc-updated">Last updated {j.last_updated}</span>
          <span className="tc-open">Open <span className="tc-arrow">→</span></span>
        </div>
      </div>
    </div>
  );
}

function StageCenterScoping({ j }) {
  // Unused — Setup uses SetupCard which replaces JobCard entirely.
  return null;
}

const SETUP_STATUS_LABEL = {
  drafting: 'Drafting',
  awaiting_input: 'Awaiting your input',
  ready: 'Ready to onboard agent',
};

function SetupProgressLine({ label, done, total }) {
  const complete = done >= total;
  return (
    <li className="sp-line">
      <span className="sp-label">{label}</span>
      <span className={`sp-value ${complete ? 'sp-value-complete' : ''}`}>
        <span className="sp-num">{done}</span>
        <span className="sp-of"> of </span>
        <span className="sp-num">{total}</span>
      </span>
    </li>
  );
}

function SetupCard({ j }) {
  const sp = j.setup_progress;
  const boundariesDefined = sp.boundaries === 'Defined';
  return (
    <div className="setup-card">
      <div className="setup-main">
        <div className="sc-head">
          <h3 className="sc-title">{j.title}</h3>
          <span className={`sc-status sc-status-${j.setup_status}`}>{SETUP_STATUS_LABEL[j.setup_status]}</span>
        </div>
        <p className="sc-desc">{j.setup_description}</p>
        {j.setup_status === 'awaiting_input' && j.setup_needs && (
          <p className="sc-needs"><span className="sc-arrow-in">→</span> {j.setup_needs}</p>
        )}
      </div>

      <div className="setup-side">
        <div>
          <div className="sc-side-label">Setup progress</div>
          <ul className="setup-progress">
            <SetupProgressLine label="Tools connected to Membrane" done={sp.tools.done} total={sp.tools.total}/>
            <SetupProgressLine label="Triggers for finding work" done={sp.triggers.done} total={sp.triggers.total}/>
            <SetupProgressLine label="People assigned" done={sp.people.done} total={sp.people.total}/>
            <li className="sp-line">
              <span className="sp-label">Agent boundaries</span>
              <span className={`sp-value ${boundariesDefined ? 'sp-value-complete' : 'sp-value-pending'}`}>{sp.boundaries}</span>
            </li>
          </ul>
        </div>
        <div className="sc-side-footer">
          <span className="sc-updated">Last updated {j.setup_updated_at}</span>
          <span className="sc-open">Open <span className="sc-arrow">→</span></span>
        </div>
      </div>
    </div>
  );
}

const ONBOARD_STATUS_LABEL = {
  connecting_integrations: 'Connecting integrations',
  loading_context: 'Loading context',
  ready_for_trial: 'Ready for trial',
};

function OnboardCard({ j }) {
  const integrations = j.integrations || [];
  const toolsTotal = integrations.length;
  const toolsConnected = integrations.filter(i => i.status === 'connected').length;
  const toolsDone = toolsConnected === toolsTotal && toolsTotal > 0;

  const ctxLoaded = (j.loaded_context || []).length;
  const ctxDone = j.onboarding_status === 'loading_context'
    ? false
    : (j.onboarding_status === 'ready_for_trial' || ctxLoaded > 0 && j.onboarding_status !== 'connecting_integrations');
  const ctxComplete = j.onboarding_status === 'ready_for_trial';

  const permsDone = !!j.permissions_summary;

  const ready = j.onboarding_status === 'ready_for_trial';
  const status = j.onboarding_status;

  const toolsVisible = integrations.slice(0, 5);
  const toolsMore = toolsTotal - toolsVisible.length;

  return (
    <div className="setup-card">
      <div className="setup-main">
        <div className="sc-head">
          <h3 className="sc-title">{j.title}</h3>
          <span className={`sc-status sc-status-onb-${status}`}>{ONBOARD_STATUS_LABEL[status]}</span>
        </div>
        <p className="sc-desc">{j.onboarding_description}</p>
        {ready && (
          <p className="sc-needs"><span className="sc-arrow-in">→</span> Onboarding complete — review and start the 14-day trial.</p>
        )}

        <div className="pc-tools-block">
          <div className="pc-side-label">Tools</div>
          <div className="pc-tools">
            {toolsVisible.map((it, i) => (
              <span key={i} className="pc-tool-dot-wrap" title={`${it.name} · ${it.status}`}>
                <IntegrationDot name={it.name} status={it.status}/>
              </span>
            ))}
            {toolsMore > 0 && <span className="pc-tools-more">+{toolsMore}</span>}
          </div>
        </div>
      </div>

      <div className="setup-side">
        <div>
          <div className="sc-side-label">Onboarding progress</div>
          <ul className="setup-progress">
            <SetupProgressLine label="Tools connected" done={toolsConnected} total={toolsTotal}/>
            <li className="sp-line">
              <span className="sp-label">Context loaded</span>
              <span className={`sp-value ${ctxComplete ? 'sp-value-complete' : 'sp-value-pending'}`}>
                {ctxComplete ? `${ctxLoaded} sources` : (ctxLoaded > 0 ? `${ctxLoaded} loading` : 'Pending')}
              </span>
            </li>
            <li className="sp-line">
              <span className="sp-label">Permissions defined</span>
              <span className={`sp-value ${permsDone ? 'sp-value-complete' : 'sp-value-pending'}`}>
                {permsDone ? 'Defined' : 'Pending'}
              </span>
            </li>
          </ul>
        </div>
        <div className="sc-side-footer">
          <span className="sc-updated">Last updated {j.onboarding_updated_at}</span>
          <span className="sc-open">Open <span className="sc-arrow">→</span></span>
        </div>
      </div>
    </div>
  );
}

function ProductionCard({ j }) {
  const isAnomaly = j.anomaly || j.operational_status === 'anomaly';
  const inTrial = !!j.trial_period;
  const toolsVisible = (j.integrations || []).slice(0, 5);
  const toolsMore = (j.integrations || []).length - toolsVisible.length;

  let badgeLabel = null;
  let badgeKind = '';
  if (inTrial) {
    badgeLabel = `Trial period · Day ${j.trial_day} of ${j.trial_duration_days}`;
    badgeKind = j.trial_day >= j.trial_duration_days ? 'trial-decision' : 'trial';
  } else if (j.operational_status === 'anomaly') {
    badgeLabel = 'Anomaly';
    badgeKind = 'anomaly';
  } else if (j.operational_status === 'paused') {
    badgeLabel = 'Paused';
    badgeKind = 'paused';
  } else {
    badgeLabel = 'Running';
    badgeKind = 'running';
  }

  const throughputUnit = inTrial ? 'so far' : '/mo';
  const cost = j.monthly_cost_usd || 0;
  const perUnit = (j.monthly_cases && cost) ? (cost / j.monthly_cases) : null;

  return (
    <div className={`prod-card ${isAnomaly ? 'prod-card-anomaly' : ''}`}>
      <div className="prod-main">
        <div className="pc-head">
          <h3 className="pc-title">{j.title}</h3>
          <span className={`pc-status pc-status-${badgeKind}`}>{badgeLabel}</span>
        </div>

        {inTrial && j.decision_ready && (
          <p className="pc-needs"><span className="pc-arrow-in">→</span> Trial complete — review performance and decide to hire, extend, or reject.</p>
        )}
        {isAnomaly && j.anomaly_note && (
          <p className="pc-anomaly-note"><span className="pc-anomaly-icon">⚠</span> {j.anomaly_note}</p>
        )}

        <div className="pc-tools-block">
          <div className="pc-side-label">Tools</div>
          <div className="pc-tools">
            {toolsVisible.map((it, i) => (
              <span key={i} className="pc-tool-dot-wrap" title={it.name}>
                <IntegrationDot name={it.name}/>
              </span>
            ))}
            {toolsMore > 0 && <span className="pc-tools-more">+{toolsMore}</span>}
          </div>
        </div>
      </div>

      <div className="prod-side">
        <div>
          <div className="pc-side-label">{inTrial ? 'Trial performance' : 'Live performance'}</div>
          <ul className="pc-metrics">
            <li className="pcm-line">
              <span className="pcm-label">Throughput</span>
              <span className="pcm-value">
                <span className="pcm-num">{(j.monthly_cases || 0).toLocaleString()}</span>
                <span className="pcm-unit"> {throughputUnit}</span>
              </span>
            </li>
            <li className="pcm-line">
              <span className="pcm-label">Quality</span>
              <span className="pcm-value">
                <span className="pcm-num">{Math.round((j.monthly_resolution_rate || j.resolution_rate || 0) * 100)}%</span>
              </span>
            </li>
            {inTrial ? (
              <li className="pcm-line">
                <span className="pcm-label">Human corrections</span>
                <span className={`pcm-value ${j.human_corrections === 0 ? 'pcm-value-good' : (j.human_corrections > 5 ? 'pcm-value-warn' : '')}`}>
                  <span className="pcm-num">{j.human_corrections}</span>
                </span>
              </li>
            ) : (
              <li className="pcm-line">
                <span className="pcm-label">Monthly cost</span>
                <span className="pcm-value">
                  <span className="pcm-num">{fmtMoneyExact(cost)}</span>
                  {perUnit !== null && <span className="pcm-unit"> · ${perUnit.toFixed(2)}/{j.unit_label}</span>}
                </span>
              </li>
            )}
          </ul>
        </div>
        <div className="pc-side-footer">
          <span className="pc-updated">Last updated {j.last_updated}</span>
          <span className="pc-open">Open <span className="pc-arrow">→</span></span>
        </div>
      </div>
    </div>
  );
}

function StageCenterScoping_OLD({ j }) {
  return (
    <div className="center-row">
      <div className="center-field cf-grow">
        <div className="cf-label">Inputs → Outputs</div>
        <div className="cf-value"><span className="flow-text">{j.inputs_outputs_summary}</span></div>
      </div>
      <div className="center-field">
        <div className="cf-label">Won't do</div>
        <div className="cf-value">
          {j.boundaries.map((b,i) => <span key={i} className="bound-pill">{b}</span>)}
        </div>
      </div>
      <div className="center-field">
        <div className="cf-label">Status</div>
        <div className="cf-value"><ScopingStatusPill status={j.scoping_status}/></div>
      </div>
    </div>
  );
}

function StageCenterOnboarding({ j }) {
  return (
    <div className="center-row">
      <div className="center-field">
        <div className="cf-label">Connecting to</div>
        <div className="cf-value"><IntegrationStack items={j.integrations}/></div>
      </div>
      <div className="center-field cf-grow">
        <div className="cf-label">Loading</div>
        <div className="cf-value muted-val">{j.loaded_context.join(' · ')}</div>
      </div>
      <div className="center-field">
        <div className="cf-label">Status</div>
        <div className="cf-value"><OnboardingStatusPill status={j.onboarding_status}/></div>
      </div>
    </div>
  );
}

function StageCenterTrial({ j }) {
  const complete = j.trial_day >= j.trial_duration_days;
  const corrColor = j.human_corrections === 0 ? 'success' : (j.human_corrections > 5 ? 'warn' : '');
  return (
    <div className="center-row">
      <div className="center-field cf-grow">
        <div className="cf-label">Trial progress</div>
        <div className="cf-value">
          <div className="trial-progress">
            <div className="trial-progress-label">Day {j.trial_day} of {j.trial_duration_days}</div>
            <ProgressBar value={j.trial_day} total={j.trial_duration_days} complete={complete}/>
          </div>
        </div>
      </div>
      <div className="center-field">
        <div className="cf-label">Cases</div>
        <div className="cf-value cf-strong">{j.cases_handled} <span className="muted-val">of {j.cases_expected}</span></div>
      </div>
      <div className="center-field">
        <div className="cf-label">Resolution</div>
        <div className="cf-value cf-strong">{Math.round(j.resolution_rate * 100)}%</div>
      </div>
      <div className="center-field">
        <div className="cf-label">Corrections</div>
        <div className={`cf-value ${corrColor === 'success' ? 'cf-success' : corrColor === 'warn' ? 'cf-warn' : ''}`}>
          {j.human_corrections}
        </div>
      </div>
    </div>
  );
}

function StageCenterOTJ({ j }) {
  return (
    <div className="center-row">
      <div className="center-field">
        <div className="cf-label">Stack</div>
        <div className="cf-value"><IntegrationStack items={j.integrations}/></div>
      </div>
      <div className="center-field">
        <div className="cf-label">Throughput</div>
        <div className="cf-value cf-strong">{j.monthly_cases.toLocaleString()} <span className="muted-val">/mo</span></div>
      </div>
      <div className="center-field">
        <div className="cf-label">Quality</div>
        <div className="cf-value cf-strong">{Math.round(j.monthly_resolution_rate * 100)}%</div>
      </div>
      <div className="center-field">
        <div className="cf-label">Status</div>
        <div className="cf-value">
          <StatusDot state={j.operational_status}/>
          {j.anomaly_note && <div className="anomaly-note">{j.anomaly_note}</div>}
        </div>
      </div>
    </div>
  );
}

const STAGE_CENTER = {
  discovered: StageCenterDiscovered,
  scoping: StageCenterScoping,
  onboarding: StageCenterOnboarding,
  in_trial: StageCenterTrial,
  on_the_job: StageCenterOTJ,
};

// =================================================================
// Right-side summary metric per row
// =================================================================

function RowSummary({ j }) {
  if (j.state === 'discovered') {
    return (
      <div className="row-summary">
        <div className="rs-label">Surfaced</div>
        <div className="rs-value">{j.surfaced_at}</div>
      </div>
    );
  }
  if (j.state === 'scoping') {
    return (
      <div className="row-summary">
        <div className="rs-label">Updated</div>
        <div className="rs-value">{j.scoping_updated_at}</div>
      </div>
    );
  }
  if (j.state === 'onboarding') {
    const connected = (j.integrations || []).filter(i => i.status === 'connected').length;
    return (
      <div className="row-summary">
        <div className="rs-label">Integrations</div>
        <div className="rs-value">{connected} of {j.integrations.length}</div>
      </div>
    );
  }
  if (j.state === 'in_trial') {
    const complete = j.trial_day >= j.trial_duration_days;
    return (
      <div className="row-summary">
        <div className="rs-label">{complete ? 'Decision' : 'Avg time'}</div>
        <div className="rs-value">{complete ? 'Ready' : `${j.avg_resolution_minutes} min`}</div>
      </div>
    );
  }
  if (j.state === 'on_the_job') {
    const perUnit = j.monthly_cost_usd / j.monthly_cases;
    return (
      <div className="row-summary row-summary-cost">
        <div className="rs-label">Monthly cost</div>
        <div className="rs-cost">{fmtMoneyExact(j.monthly_cost_usd)}<span className="rs-cost-unit">/mo</span></div>
        <div className="rs-cost-secondary">${perUnit.toFixed(2)}/{j.unit_label}</div>
      </div>
    );
  }
  return null;
}

// =================================================================
// Stage strip — 5 cells showing pipeline position
// =================================================================

function StageStrip({ j }) {
  const currentIdx = STAGE_ORDER.indexOf(j.state);
  return (
    <div className="stage-strip">
      {STAGE_ORDER.map((sid, i) => {
        const isCurrent = i === currentIdx;
        const isPast = i < currentIdx;
        return (
          <div key={sid} className={`strip-cell ${isCurrent ? 'is-current' : ''} ${isPast ? 'is-past' : ''}`}>
            {isCurrent && <span className="strip-marker"/>}
            <div className="strip-label">{STAGE_SHORT[sid]}</div>
            <div className="strip-state">
              {isPast && <span className="strip-check">✓</span>}
              {isCurrent && <span className="strip-current-dot"/>}
            </div>
          </div>
        );
      })}
    </div>
  );
}

// =================================================================
// Job card — one per row
// =================================================================

function JobCard({ j }) {
  const Center = STAGE_CENTER[j.state];
  const isAnomaly = j.anomaly || j.operational_status === 'anomaly';
  return (
    <div className={`job-card ${isAnomaly ? 'job-card-anomaly' : ''}`}>
      <div className="job-card-main">
        <div className="job-card-heading">
          <h3 className="job-title">{j.title}</h3>
          {isAnomaly && <span className="anomaly-flag">⚠ anomaly</span>}
        </div>
        <div className="job-meta-row">
          {j.state === 'on_the_job' && j.started_at && (
            <span className="meta-chip"><span className="meta-icon">●</span> Running since {j.started_at}</span>
          )}
          {j.state === 'in_trial' && (
            <span className="meta-chip"><span className="meta-icon">▸</span> Trial day {j.trial_day} of {j.trial_duration_days}</span>
          )}
          {j.state === 'discovered' && (
            <span className="meta-chip"><span className="meta-icon">✦</span> Surfaced {j.surfaced_at}</span>
          )}
          {j.state === 'scoping' && (
            <span className="meta-chip"><span className="meta-icon">◆</span> Updated {j.scoping_updated_at}</span>
          )}
          {j.state === 'onboarding' && (
            <span className="meta-chip"><span className="meta-icon">⇄</span> Connecting to {j.integrations.length} systems</span>
          )}
          {(j.function_tags || []).map(t => (
            <span key={t} className="meta-chip">{FUNCTION_LABEL[t] || t}</span>
          ))}
          <span className="meta-chip">Unit: {j.unit_label}</span>
        </div>
        <Center j={j}/>
      </div>
      <div className="job-card-side">
        <RowSummary j={j}/>
      </div>
    </div>
  );
}

// =================================================================
// Group section
// =================================================================

function StageGroup({ stage, jobs, filtered, collapsed, onToggle, isFirst, isLast }) {
  return (
    <section className={`stage-group ${collapsed ? 'is-collapsed' : ''}`} data-stage-anchor={stage.id}>
      <div className="stage-rail" aria-hidden="true">
        <span className="rail-dot">{stage.n}</span>
      </div>
      <div className="stage-content">
        <button className="group-header" onClick={onToggle}>
          <span className="group-name">{stage.name}</span>
          <span className="group-dash">—</span>
          <span className="group-sub">{stage.sub}</span>
          <span className="group-count">{jobs.length}</span>
          <span className={`group-chev ${collapsed ? 'is-collapsed' : ''}`} aria-hidden="true">
            <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
              <path d="M4 6L8 10L12 6" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          </span>
        </button>
        {!collapsed && (
          <>
            <p className="group-desc">
              {stage.desc}
              {stage.id === 'discovered' && (
                <em className="group-desc-note"> Values shown are estimates based on observed activity.</em>
              )}
            </p>
            <div className="group-body">
              {jobs.length === 0
                ? <div className="group-empty">{filtered ? 'No matching jobs in this stage.' : stage.empty}</div>
                : jobs.map(j => {
                    if (j.state === 'discovered') return <TriageCard key={j.id} j={j}/>;
                    if (j.state === 'scoping') return <SetupCard key={j.id} j={j}/>;
                    if (j.state === 'onboarding') return <OnboardCard key={j.id} j={j}/>;
                    if (j.state === 'on_the_job') return <ProductionCard key={j.id} j={j}/>;
                    return <JobCard key={j.id} j={j}/>;
                  })}
            </div>
          </>
        )}
      </div>
    </section>
  );
}

// =================================================================
// Header / filter bar
// =================================================================

function FilterChip({ active, onClick, children }) {
  return <button className={`filter-chip ${active ? 'filter-chip-active' : ''}`} onClick={onClick}>{children}</button>;
}

// =================================================================
// Page
// =================================================================

function AgentJobsPage({ renderTopBar }) {
  const [search, setSearch] = useStateJobs('');
  const [fnFilter, setFnFilter] = useStateJobs('All');
  const [statusFilter, setStatusFilter] = useStateJobs('All');
  const [view, setView] = useStateJobs('pipeline'); // pipeline | table
  const [collapsed, setCollapsed] = useStateJobs({}); // stage id -> bool

  const filtered = useMemoJobs(() => {
    let rows = JOBS;
    if (search) {
      const q = search.toLowerCase();
      rows = rows.filter(j => j.title.toLowerCase().includes(q) || (j.detection_signal || '').toLowerCase().includes(q));
    }
    if (fnFilter !== 'All') {
      rows = rows.filter(j => (j.function_tags || []).some(t => t.toLowerCase() === fnFilter.toLowerCase()));
    }
    if (statusFilter === 'Anomalies') {
      rows = rows.filter(j => j.operational_status === 'anomaly' || j.anomaly);
    } else if (statusFilter === 'Needs my attention') {
      rows = rows.filter(j => j.setup_status === 'awaiting_input' || j.onboarding_status === 'ready_for_trial' || (j.trial_period && j.trial_day >= j.trial_duration_days) || j.state === 'discovered' || j.anomaly);
    } else if (statusFilter === 'Running normally') {
      rows = rows.filter(j => j.operational_status === 'running');
    }
    return rows;
  }, [search, fnFilter, statusFilter]);

  const isFiltered = search !== '' || fnFilter !== 'All' || statusFilter !== 'All';

  const sortStage = (id, rows) => {
    if (id === 'scoping') {
      const order = { awaiting_input: 0, ready: 1, drafting: 2 };
      return [...rows].sort((a,b) => order[a.setup_status] - order[b.setup_status]);
    }
    if (id === 'onboarding') {
      return [...rows].sort((a,b) => (b.onboarding_status === 'ready_for_trial') - (a.onboarding_status === 'ready_for_trial'));
    }
    if (id === 'in_trial') {
      return [...rows].sort((a,b) => {
        if (a.anomaly && !b.anomaly) return -1;
        if (b.anomaly && !a.anomaly) return 1;
        return (b.trial_day / b.trial_duration_days) - (a.trial_day / a.trial_duration_days);
      });
    }
    if (id === 'on_the_job') {
      return [...rows].sort((a,b) => {
        // 1. Trials with decision ready
        const aDec = a.trial_period && a.decision_ready ? 0 : 1;
        const bDec = b.trial_period && b.decision_ready ? 0 : 1;
        if (aDec !== bDec) return aDec - bDec;
        // 2. Anomalies
        const aAnom = a.operational_status === 'anomaly' ? 0 : 1;
        const bAnom = b.operational_status === 'anomaly' ? 0 : 1;
        if (aAnom !== bAnom) return aAnom - bAnom;
        // 3. Other trials
        const aTrial = a.trial_period ? 0 : 1;
        const bTrial = b.trial_period ? 0 : 1;
        if (aTrial !== bTrial) return aTrial - bTrial;
        // 4. By cost desc
        return (b.monthly_cost_usd || 0) - (a.monthly_cost_usd || 0);
      });
    }
    return rows;
  };

  return (
    <>
      {renderTopBar(null)}
      <div className="content content-jobs">
        <div className="jobs-toolbar">
          <div className="jobs-toolbar-row">
            <StagePipeline stages={STAGES} jobs={JOBS}/>
            <div className="toolbar-actions">
              <button className="toolbar-btn" title="Search jobs (⌘F)">
                <Icons.Search size={13}/>
                <span>Search</span>
              </button>
              <button className="toolbar-btn" title="Filter">
                <Icons.Filter size={13}/>
                <span>Filter</span>
              </button>
            </div>
          </div>
        </div>

        <div className="groups-wrap">
          {STAGES.map((stage, idx) => {
            const rows = sortStage(stage.id, filtered.filter(j => j.state === stage.id));
            return (
              <StageGroup
                key={stage.id}
                stage={stage}
                jobs={rows}
                filtered={isFiltered}
                collapsed={!!collapsed[stage.id]}
                onToggle={() => setCollapsed(c => ({ ...c, [stage.id]: !c[stage.id] }))}
                isFirst={idx === 0}
                isLast={idx === STAGES.length - 1}
              />
            );
          })}
        </div>

        <div className="archive-link">
          <a href="#archive">View archive →</a>
        </div>
      </div>
    </>
  );
}

window.AgentJobsPage = AgentJobsPage;
