/* eslint-disable */
// Staffing Partner v2 — Candidates view (soft aesthetic)

(function () {
const {
  Icon, Avatar,
  V2, V2Card, V2Button, V2Badge, V2TextField, V2PillToggle,
  StepBadge, V2SectionHeader, V2StatTile, V2TableShell, V2TH, V2Progress,
} = window;
const { CANDIDATES, JOBS, CLIENTS, AGENTS } = window;
const { useState, useMemo } = React;

const MILESTONES = [
  { key: "submitted",    label: "Submitted",    sub: "under review" },
  { key: "hireart-qual", label: "HireArt Qual", sub: "screening + assessment" },
  { key: "client-qual",  label: "Client Qual",  sub: "interviews + review" },
  { key: "offer",        label: "Offer",        sub: "extended / awaiting" },
  { key: "hired",        label: "Hired",        sub: "onboarding" },
];

function milestoneIdx(key) { return MILESTONES.findIndex(m => m.key === key); }

// ---- Mini horizontal pipeline ---------------------------------------
function V2MiniPipeline({ stage, needsAction }) {
  if (stage === "rejected") {
    return <V2Badge tone="red" icon="x-circle">Rejected</V2Badge>;
  }
  const idx = milestoneIdx(stage);
  const cur = MILESTONES[idx];
  return (
    <div style={{ display: "inline-flex", flexDirection: "column", gap: 6, minWidth: 180 }}>
      <div style={{ display: "flex", gap: 4 }}>
        {MILESTONES.map((m, i) => {
          const done = i < idx;
          const at = i === idx;
          let bg = "#EFEFEF";
          if (done) bg = V2.primary;
          else if (at) bg = needsAction ? "var(--red-60)" : V2.primary;
          return (
            <div key={m.key} style={{
              flex: 1, height: 4, borderRadius: 999, background: bg,
            }} />
          );
        })}
      </div>
      <div style={{
        display: "flex", alignItems: "center", gap: 6,
        fontSize: 12, fontWeight: 600, color: V2.text,
      }}>
        <StepBadge n={idx + 1} state={needsAction ? "active" : "active"} size={18} />
        {cur.label}
        <span style={{ color: V2.textDim, fontWeight: 500 }}>· {idx + 1}/{MILESTONES.length}</span>
      </div>
    </div>
  );
}

// ---- Action-required block (soft, like the screenshot's pinned card) ---
function V2ActionRequired({ candidates, onOpen }) {
  const list = candidates.filter(c => c.needsAction);
  if (list.length === 0) return null;
  return (
    <V2Card padding={0} style={{ marginBottom: 24, overflow: "hidden" }}>
      <div style={{
        display: "flex", alignItems: "center", gap: 10,
        padding: "14px 20px",
        background: "#FFF8E8",
        borderBottom: `1px solid ${V2.hairline}`,
      }}>
        <span style={{
          width: 28, height: 28, borderRadius: 999,
          background: "var(--yellow-40)",
          display: "inline-flex", alignItems: "center", justifyContent: "center",
        }}>
          <Icon name="alert-triangle" size={14} />
        </span>
        <div style={{ fontSize: 14, fontWeight: 600, color: V2.text }}>
          {list.length} candidate{list.length === 1 ? "" : "s"} need{list.length === 1 ? "s" : ""} your action
        </div>
        <span style={{ fontSize: 12, color: V2.textMuted }}>· don't let these expire</span>
      </div>
      <div>
        {list.map((c, i) => {
          const job = JOBS.find(j => j.id === c.jobId);
          const agent = AGENTS.find(a => a.id === c.agentId);
          return (
            <div key={c.id} onClick={() => onOpen?.(c)} style={{
              display: "grid",
              gridTemplateColumns: "minmax(220px, 1.1fr) minmax(180px, 1fr) minmax(220px, 1.4fr) auto",
              alignItems: "center", gap: 18,
              padding: "14px 20px",
              borderBottom: i < list.length - 1 ? `1px solid ${V2.hairlineSoft}` : "none",
              cursor: "pointer",
            }}
            onMouseEnter={e => e.currentTarget.style.background = "#FAFAFA"}
            onMouseLeave={e => e.currentTarget.style.background = "transparent"}>
              <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                <Avatar name={c.name} size={36} bg={`var(--${c.color}-20)`} />
                <div>
                  <div style={{ fontWeight: 600, fontSize: 14, color: V2.text }}>{c.name}</div>
                  <div style={{ fontSize: 12, color: V2.textDim }}>via {agent.name}</div>
                </div>
              </div>
              <div style={{ fontSize: 13 }}>
                <div style={{ color: V2.text, fontWeight: 500 }}>{job.title}</div>
                <div style={{ color: V2.textDim, fontSize: 12, fontVariantNumeric: "tabular-nums" }}>Req {job.req}</div>
              </div>
              <div style={{ fontSize: 13, color: V2.text }}>
                <div style={{ fontWeight: 500 }}>{c.substep}</div>
                <div style={{ fontSize: 12, color: V2.textMuted, marginTop: 2 }}>Next: {c.nextStep}</div>
              </div>
              <V2Button size="sm" variant="primary" iconEnd="arrow-right">Resolve</V2Button>
            </div>
          );
        })}
      </div>
    </V2Card>
  );
}

// ---- Milestone legend (numbered horizontal stepper, like screenshot) -
function V2MilestoneLegend() {
  return (
    <V2Card padding={20} style={{ marginBottom: 24 }}>
      <div style={{ display: "flex", alignItems: "stretch", gap: 0 }}>
        {MILESTONES.map((m, i) => (
          <React.Fragment key={m.key}>
            <div style={{ flex: 1, padding: "0 4px", minWidth: 0 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                <StepBadge n={i + 1} state="active" size={28} />
                <div style={{ minWidth: 0 }}>
                  <div style={{ fontSize: 13, fontWeight: 600, color: V2.text, lineHeight: 1.2 }}>{m.label}</div>
                  <div style={{ fontSize: 11, color: V2.textMuted, marginTop: 2, lineHeight: 1.3 }}>{m.sub}</div>
                </div>
              </div>
            </div>
            {i < MILESTONES.length - 1 && (
              <div style={{
                alignSelf: "center", color: V2.textDim,
                fontSize: 16, padding: "0 4px",
              }}>›</div>
            )}
          </React.Fragment>
        ))}
      </div>
    </V2Card>
  );
}

// ---- Filters --------------------------------------------------------
function V2CandidateFilters({ q, setQ, stage, setStage, agent, setAgent, actionOnly, setActionOnly, counts }) {
  const opts = [
    { value: "all",          label: "All", count: counts.all },
    ...MILESTONES.map(m => ({ value: m.key, label: m.label, count: counts[m.key] || 0 })),
    { value: "rejected",     label: "Rejected", count: counts.rejected || 0 },
  ];
  return (
    <div style={{ display: "flex", gap: 12, alignItems: "center", flexWrap: "wrap", marginBottom: 18 }}>
      <div style={{ flex: "0 0 280px" }}>
        <V2TextField placeholder="Search candidates…" value={q} onChange={e => setQ(e.target.value)} iconStart="search" />
      </div>
      <V2PillToggle value={stage} onChange={setStage} options={opts} />
      <V2Button
        variant={actionOnly ? "ghost-purple" : "ghost"}
        size="md"
        iconStart="alert-triangle"
        onClick={() => setActionOnly(!actionOnly)}
        style={actionOnly ? { background: V2.primarySoft, color: V2.primary } : {}}
      >Action required</V2Button>
      <div style={{ marginLeft: "auto", display: "flex", gap: 6, alignItems: "center" }}>
        <span style={{ fontSize: 12, color: V2.textDim, fontWeight: 500 }}>Agent</span>
        <select value={agent} onChange={e => setAgent(e.target.value)} style={{
          padding: "7px 12px",
          border: `1px solid ${V2.hairline}`,
          borderRadius: 8,
          background: V2.surface, fontSize: 13, fontWeight: 500,
          color: V2.text, fontFamily: "var(--font-body)", cursor: "pointer",
        }}>
          <option value="all">All agents</option>
          {AGENTS.map(a => <option key={a.id} value={a.id}>{a.name}</option>)}
        </select>
      </div>
    </div>
  );
}

// ---- Candidate row (soft) -------------------------------------------
function V2CandidateRow({ c, isLast, onOpen }) {
  const job = JOBS.find(j => j.id === c.jobId);
  const client = CLIENTS[job.client];
  const agent = AGENTS.find(a => a.id === c.agentId);
  return (
    <tr onClick={() => onOpen?.(c)} style={{
      borderBottom: isLast ? "none" : `1px solid ${V2.hairlineSoft}`,
      cursor: "pointer",
    }}
    onMouseEnter={e => e.currentTarget.style.background = "#FAFAFA"}
    onMouseLeave={e => e.currentTarget.style.background = "transparent"}>
      <td style={{ padding: "16px 18px" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <Avatar name={c.name} size={36} bg={`var(--${c.color}-20)`} />
          <div>
            <div style={{ fontWeight: 600, fontSize: 14, color: V2.text }}>{c.name}</div>
            <div style={{ fontSize: 12, color: V2.textDim }}>via {agent.name} · {c.submitted}</div>
          </div>
        </div>
      </td>
      <td style={{ padding: "16px 18px" }}>
        <div style={{ fontWeight: 500, fontSize: 13, color: V2.text }}>{job.title}</div>
        <div style={{ fontSize: 12, color: V2.textDim }}>{client.name} · Req {job.req}</div>
      </td>
      <td style={{ padding: "16px 18px" }}>
        <V2MiniPipeline stage={c.stage} needsAction={c.needsAction} />
      </td>
      <td style={{ padding: "16px 18px", maxWidth: 260 }}>
        <div style={{
          fontSize: 13, fontWeight: 500,
          color: c.needsAction ? "var(--red-100)" : V2.text,
          display: "inline-flex", alignItems: "center", gap: 5,
        }}>
          {c.needsAction && <Icon name="alert-triangle" size={12} />}
          {c.substep}
        </div>
        <div style={{ fontSize: 12, color: V2.textMuted, marginTop: 2 }}>Next: {c.nextStep}</div>
      </td>
      <td style={{ padding: "16px 18px", textAlign: "right", fontVariantNumeric: "tabular-nums", fontSize: 13, fontWeight: 600, color: V2.text }}>
        {c.rate ? `$${c.rate.toFixed(2)}` : <span style={{ color: V2.textDim, fontWeight: 400 }}>—</span>}
      </td>
      <td style={{ padding: "16px 18px", textAlign: "right" }}>
        <V2Button size="sm" variant="secondary" iconEnd="arrow-right">View</V2Button>
      </td>
    </tr>
  );
}

function V2CandidatesView({ tweaks, onOpenCandidate }) {
  const [q, setQ] = useState("");
  const [stage, setStage] = useState("all");
  const [agent, setAgent] = useState("all");
  const [actionOnly, setActionOnly] = useState(false);

  const counts = useMemo(() => {
    const c = { all: CANDIDATES.length, rejected: 0 };
    MILESTONES.forEach(m => c[m.key] = 0);
    CANDIDATES.forEach(x => { c[x.stage] = (c[x.stage] || 0) + 1; });
    return c;
  }, []);

  const filtered = useMemo(() => {
    const qL = q.toLowerCase().trim();
    return CANDIDATES.filter(c => {
      if (stage !== "all" && c.stage !== stage) return false;
      if (agent !== "all" && c.agentId !== agent) return false;
      if (actionOnly && !c.needsAction) return false;
      if (!qL) return true;
      const job = JOBS.find(j => j.id === c.jobId);
      return [c.name, c.substep, job.title].some(s => s.toLowerCase().includes(qL));
    });
  }, [q, stage, agent, actionOnly]);

  const stats = useMemo(() => ({
    total: CANDIDATES.filter(c => c.stage !== "rejected" && c.stage !== "hired").length,
    needsAction: CANDIDATES.filter(c => c.needsAction).length,
    offerStage: CANDIDATES.filter(c => c.stage === "offer").length,
    hired: CANDIDATES.filter(c => c.stage === "hired").length,
  }), []);

  return (
    <div>
      <V2SectionHeader
        eyebrow="Candidates"
        title="In flight across jobs"
        sub="Every candidate your agency has submitted, grouped by milestone. Don't wait for an email update."
      />
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 16, marginBottom: 24 }}>
        <V2StatTile label="In flight" value={stats.total} sub="across pipelines" tone="blue" icon="users" />
        <V2StatTile label="Action required" value={stats.needsAction} sub="needs your input" tone="red" icon="alert-triangle" />
        <V2StatTile label="At offer stage" value={stats.offerStage} sub="awaiting acceptance" tone="purple" icon="document-text" />
        <V2StatTile label="Hired this quarter" value={stats.hired} sub="placed successfully" tone="green" icon="check-circle" />
      </div>

      <V2ActionRequired candidates={CANDIDATES} onOpen={onOpenCandidate} />
      <V2MilestoneLegend />

      <V2CandidateFilters
        q={q} setQ={setQ}
        stage={stage} setStage={setStage}
        agent={agent} setAgent={setAgent}
        actionOnly={actionOnly} setActionOnly={setActionOnly}
        counts={counts}
      />

      <V2TableShell>
        <table style={{ width: "100%", borderCollapse: "collapse", fontFamily: "var(--font-body)" }}>
          <thead>
            <tr>
              <V2TH>Candidate</V2TH>
              <V2TH>Job</V2TH>
              <V2TH>Pipeline</V2TH>
              <V2TH>Current step</V2TH>
              <V2TH right>Rate</V2TH>
              <V2TH></V2TH>
            </tr>
          </thead>
          <tbody>
            {filtered.map((c, i) => (
              <V2CandidateRow key={c.id} c={c} isLast={i === filtered.length - 1} onOpen={onOpenCandidate} />
            ))}
          </tbody>
        </table>
      </V2TableShell>
    </div>
  );
}

Object.assign(window, { V2CandidatesView });
})();
