/* eslint-disable */
// Staffing Partner — Candidates view

(function () {
const { Icon, Button, Badge, TextField, Avatar } = window;
const { CANDIDATES, JOBS, CLIENTS, AGENTS } = window;
const { SectionHeader, AgentChip } = window;
const { useState, useMemo } = React;

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

const SUB_STEPS = {
  "hireart-qual": ["Required work/education", "Screening", "Assessment", "MVR"],
  "client-qual":  ["Client Review", "Online Interview", "In-person Interview"],
};

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

// --- Mini pipeline (inline per-row) -----------------------------------
function MiniPipeline({ stage, needsAction }) {
  if (stage === "rejected") {
    return (
      <span style={{
        display: "inline-flex", alignItems: "center", gap: 5,
        padding: "3px 8px", border: "2px solid var(--neutral-100)",
        borderRadius: 100, background: "var(--red-20)",
        fontSize: 11, fontWeight: 700, color: "var(--red-100)",
        fontFamily: "var(--font-body)",
      }}>
        <Icon name="x-circle" size={12} />REJECTED
      </span>
    );
  }
  const idx = milestoneIdx(stage);
  const current = MILESTONES[idx];
  return (
    <div style={{ display: "inline-flex", flexDirection: "column", gap: 4, fontFamily: "var(--font-body)", minWidth: 180 }}>
      <div style={{
        display: "flex", width: "100%",
        border: "1.5px solid var(--neutral-100)", borderRadius: 100,
        overflow: "hidden", height: 10, background: "var(--neutral-10)",
      }}>
        {MILESTONES.map((m, i) => {
          const done = i < idx;
          const atCurrent = i === idx;
          let bg = "transparent";
          if (done) bg = "var(--neutral-100)";
          else if (atCurrent) bg = needsAction ? "var(--red-60)" : "var(--green-60)";
          return (
            <div key={m.key} style={{
              flex: 1, background: bg,
              borderRight: i < MILESTONES.length - 1 ? "1.5px solid var(--neutral-100)" : "none",
            }} />
          );
        })}
      </div>
      <div style={{
        display: "flex", alignItems: "center", gap: 5,
        fontSize: 11, fontWeight: 700, color: "var(--neutral-100)",
      }}>
        <span style={{
          display: "inline-flex", alignItems: "center", justifyContent: "center",
          width: 16, height: 16, borderRadius: 100,
          border: "1.5px solid var(--neutral-100)",
          background: needsAction ? "var(--red-60)" : "var(--green-60)",
          fontSize: 10, color: "var(--neutral-10)", fontWeight: 700,
        }}>{idx + 1}</span>
        {current.label}
        <span style={{ color: "var(--neutral-60)", fontWeight: 500 }}>
          · {idx + 1}/{MILESTONES.length}
        </span>
      </div>
    </div>
  );
}

// --- Milestone legend --------------------------------------------------
function MilestoneLegend() {
  return (
    <div style={{
      display: "flex", gap: 0, marginBottom: 18,
      border: "2px solid var(--neutral-100)", borderRadius: 10,
      overflow: "hidden", fontFamily: "var(--font-body)",
      background: "var(--neutral-10)",
    }}>
      {MILESTONES.map((m, i) => (
        <div key={m.key} style={{
          flex: 1, padding: "10px 14px",
          borderRight: i < MILESTONES.length - 1 ? "2px solid var(--neutral-100)" : "none",
          position: "relative",
        }}>
          <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
            <span style={{
              width: 20, height: 20, borderRadius: 100,
              background: "var(--neutral-100)",
              border: "2px solid var(--neutral-100)",
              fontSize: 11, fontWeight: 700, color: "var(--neutral-10)",
              display: "inline-flex", alignItems: "center", justifyContent: "center",
              fontFamily: "var(--font-body)",
            }}>{i + 1}</span>
            <div style={{ fontWeight: 700, fontSize: 13, color: "var(--neutral-100)" }}>{m.label}</div>
          </div>
          <div style={{ fontSize: 11, color: "var(--neutral-70)", marginTop: 2, marginLeft: 26 }}>{m.sub}</div>
          {i < MILESTONES.length - 1 && (
            <div style={{
              position: "absolute", right: -9, top: "50%", transform: "translateY(-50%)",
              width: 16, height: 16,
              display: "flex", alignItems: "center", justifyContent: "center",
              color: "var(--neutral-60)", zIndex: 1,
              background: "var(--neutral-10)",
              fontWeight: 700, fontSize: 12,
            }}>›</div>
          )}
        </div>
      ))}
    </div>
  );
}

// --- Action-required banner + list ------------------------------------
function ActionRequired({ candidates, onOpen }) {
  const actionCands = candidates.filter(c => c.needsAction);
  if (actionCands.length === 0) return null;
  return (
    <div style={{
      marginBottom: 18,
      border: "2px solid var(--neutral-100)", borderRadius: 12,
      background: "var(--yellow-20)",
      boxShadow: "var(--shadow-md)",
      fontFamily: "var(--font-body)", overflow: "hidden",
    }}>
      <div style={{
        display: "flex", alignItems: "center", gap: 10,
        padding: "12px 18px",
        borderBottom: "2px solid var(--neutral-100)",
        background: "var(--yellow-40)",
      }}>
        <Icon name="alert-triangle" size={18} />
        <span style={{ fontWeight: 700, fontSize: 14 }}>
          {actionCands.length} candidate{actionCands.length === 1 ? "" : "s"} need{actionCands.length === 1 ? "s" : ""} your action
        </span>
        <span style={{ fontSize: 12, color: "var(--neutral-80)" }}>
          · don't let these expire
        </span>
      </div>
      <div>
        {actionCands.map(c => {
          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.2fr) minmax(180px, 1fr) minmax(220px, 1.4fr) auto",
              alignItems: "center", gap: 18,
              padding: "10px 18px",
              borderBottom: "1.5px solid var(--neutral-30)",
              cursor: "pointer",
            }}>
              <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                <Avatar name={c.name} size={32} bg={`var(--${c.color}-20)`} />
                <div>
                  <div style={{ fontWeight: 700, fontSize: 14 }}>{c.name}</div>
                  <div style={{ fontSize: 11, color: "var(--neutral-70)" }}>via {agent.name}</div>
                </div>
              </div>
              <div style={{ fontSize: 12 }}>
                <div style={{ color: "var(--neutral-100)", fontWeight: 600 }}>{job.title}</div>
                <div style={{ color: "var(--neutral-60)", fontVariantNumeric: "tabular-nums" }}>Req {job.req}</div>
              </div>
              <div style={{ fontSize: 12, color: "var(--neutral-90)", fontWeight: 500 }}>
                {c.substep}
                <div style={{ fontSize: 11, color: "var(--neutral-70)", marginTop: 2 }}>
                  Next: {c.nextStep}
                </div>
              </div>
              <Button size="sm" color="primary-red" iconEnd="arrow-right">Resolve</Button>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// --- Filter bar -------------------------------------------------------
function CandidateFilters({ q, setQ, stage, setStage, agent, setAgent, actionOnly, setActionOnly, counts }) {
  const stagePill = (key, label) => {
    const active = stage === key;
    const tone = MILESTONES.find(m => m.key === key)?.tone;
    return (
      <button key={key} onClick={() => setStage(key)} style={{
        padding: "6px 12px", borderRadius: 100,
        border: "2px solid var(--neutral-100)",
        background: active ? (tone && tone !== "neutral" ? `var(--${tone}-40)` : "var(--neutral-100)") : "var(--neutral-10)",
        color: active && tone === "neutral" ? "var(--neutral-10)" : "var(--neutral-100)",
        fontWeight: 600, fontSize: 13, cursor: "pointer",
        fontFamily: "var(--font-body)",
        display: "inline-flex", alignItems: "center", gap: 6,
      }}>
        {label}
        {counts[key] != null && <span style={{
          fontSize: 11, fontWeight: 700, padding: "0 6px",
          background: active ? "rgba(0,0,0,0.15)" : "var(--neutral-20)",
          borderRadius: 100, fontVariantNumeric: "tabular-nums",
        }}>{counts[key]}</span>}
      </button>
    );
  };
  return (
    <div style={{ display: "flex", gap: 10, alignItems: "center", flexWrap: "wrap", marginBottom: 16 }}>
      <div style={{ flex: "0 0 280px" }}>
        <TextField placeholder="Search candidates…" value={q} onChange={e => setQ(e.target.value)} iconStart="search" />
      </div>
      {stagePill("all", "All")}
      {MILESTONES.map(m => stagePill(m.key, m.label))}
      {stagePill("rejected", "Rejected")}
      <div style={{ width: 1, height: 24, background: "var(--neutral-30)" }} />
      <label style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: 13, fontWeight: 600, cursor: "pointer", fontFamily: "var(--font-body)" }}>
        <input type="checkbox" checked={actionOnly} onChange={e => setActionOnly(e.target.checked)} />
        Action required only
      </label>
      <div style={{ marginLeft: "auto", display: "flex", gap: 6, alignItems: "center" }}>
        <span style={{ fontSize: 12, color: "var(--neutral-60)", fontWeight: 600 }}>Agent:</span>
        <select value={agent} onChange={e => setAgent(e.target.value)} style={{
          padding: "6px 10px", border: "2px solid var(--neutral-100)", borderRadius: 6,
          background: "var(--neutral-10)", fontSize: 13, fontWeight: 600,
          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>
  );
}

// --- Candidates table --------------------------------------------------
function CandidatesTable({ candidates, density = "normal", showSecondary, onOpen }) {
  const pad = density === "compact" ? "10px 14px" : "14px 14px";

  const Header = ({ children, right }) => (
    <th style={{
      textAlign: right ? "right" : "left",
      padding: "10px 14px",
      fontSize: 11, fontWeight: 700, letterSpacing: "0.08em",
      textTransform: "uppercase", color: "var(--neutral-70)",
      borderBottom: "2px solid var(--neutral-100)",
      background: "var(--neutral-20)", whiteSpace: "nowrap",
    }}>{children}</th>
  );

  return (
    <div style={{
      border: "2px solid var(--neutral-100)", borderRadius: 12,
      background: "var(--neutral-10)", overflow: "hidden",
      boxShadow: "var(--shadow-md)",
    }}>
      <table style={{ width: "100%", borderCollapse: "collapse", fontFamily: "var(--font-body)" }}>
        <thead>
          <tr>
            <Header>Candidate</Header>
            <Header>Agent</Header>
            <Header>Job</Header>
            <Header>Pipeline</Header>
            <Header>Current step</Header>
            {showSecondary && <Header right>Days</Header>}
            <Header right>Rate</Header>
            <Header></Header>
          </tr>
        </thead>
        <tbody>
          {candidates.map(c => {
            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 key={c.id} onClick={() => onOpen?.(c)} style={{
                borderBottom: "1.5px solid var(--neutral-30)",
                cursor: "pointer",
                background: c.needsAction ? "rgba(255,203,84,0.08)" : "transparent",
              }}>
                <td style={{ padding: pad }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                    <Avatar name={c.name} size={34} bg={`var(--${c.color}-20)`} />
                    <div>
                      <div style={{ fontWeight: 700, fontSize: 14, color: "var(--neutral-100)" }}>{c.name}</div>
                      <div style={{ fontSize: 11, color: "var(--neutral-60)" }}>Submitted {c.submitted}</div>
                    </div>
                  </div>
                </td>
                <td style={{ padding: pad }}>
                  <AgentChip agent={agent} />
                </td>
                <td style={{ padding: pad }}>
                  <div style={{ fontWeight: 600, fontSize: 13, color: "var(--neutral-100)" }}>{job.title}</div>
                  <div style={{ fontSize: 11, color: "var(--neutral-60)" }}>{client.name} · Req {job.req}</div>
                </td>
                <td style={{ padding: pad }}>
                  <MiniPipeline stage={c.stage} needsAction={c.needsAction} />
                </td>
                <td style={{ padding: pad, maxWidth: 280 }}>
                  <div style={{
                    fontSize: 12, fontWeight: 600,
                    color: c.needsAction ? "var(--red-100)" : "var(--neutral-100)",
                    display: "inline-flex", alignItems: "center", gap: 5,
                  }}>
                    {c.needsAction && <Icon name="alert-triangle" size={12} />}
                    {c.substep}
                  </div>
                  {showSecondary && (
                    <div style={{ fontSize: 11, color: "var(--neutral-60)", marginTop: 2 }}>
                      Next: {c.nextStep}
                    </div>
                  )}
                </td>
                {showSecondary && (
                  <td style={{ padding: pad, textAlign: "right", fontVariantNumeric: "tabular-nums", fontSize: 12, color: "var(--neutral-70)" }}>
                    {c.daysInStage}d
                  </td>
                )}
                <td style={{ padding: pad, textAlign: "right", fontVariantNumeric: "tabular-nums", fontSize: 13, fontWeight: 700 }}>
                  {c.rate ? `$${c.rate.toFixed(2)}` : <span style={{ color: "var(--neutral-50)", fontWeight: 400 }}>—</span>}
                </td>
                <td style={{ padding: pad, textAlign: "right" }}>
                  <Button size="sm" color="secondary" iconEnd="arrow-right">View</Button>
                </td>
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
}

// --- Main -------------------------------------------------------------
function CandidatesView({ tweaks, onOpenCandidate }) {
  const { density, showSecondary } = tweaks;
  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 qLower = 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 (!qLower) return true;
      const job = JOBS.find(j => j.id === c.jobId);
      return [c.name, c.substep, job.title].some(s => s.toLowerCase().includes(qLower));
    });
  }, [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>
      <SectionHeader
        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: 14, marginBottom: 22 }}>
        <MiniStat label="In flight" value={stats.total} tone="blue" />
        <MiniStat label="Action required" value={stats.needsAction} tone="red" icon="alert-triangle" />
        <MiniStat label="At offer stage" value={stats.offerStage} tone="purple" />
        <MiniStat label="Hired this quarter" value={stats.hired} tone="green" />
      </div>

      <ActionRequired candidates={CANDIDATES} onOpen={onOpenCandidate} />

      <MilestoneLegend />

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

      <CandidatesTable
        candidates={filtered}
        density={density}
        showSecondary={showSecondary}
        onOpen={onOpenCandidate}
      />
    </div>
  );
}

function MiniStat({ label, value, tone, icon }) {
  return (
    <div style={{
      padding: "14px 16px", border: "2px solid var(--neutral-100)",
      borderRadius: 10, background: "var(--neutral-10)",
      boxShadow: "var(--shadow-sm)", fontFamily: "var(--font-body)",
      position: "relative", overflow: "hidden",
    }}>
      <div style={{
        position: "absolute", top: 0, left: 0, width: 4, height: "100%",
        background: `var(--${tone}-60)`,
      }} />
      <div style={{ fontSize: 11, fontWeight: 700, textTransform: "uppercase", letterSpacing: "0.08em", color: "var(--neutral-70)", display: "inline-flex", alignItems: "center", gap: 4 }}>
        {icon && <Icon name={icon} size={12} />}{label}
      </div>
      <div style={{ fontFamily: "var(--font-display)", fontSize: 40, fontWeight: 700, color: "var(--neutral-100)", lineHeight: 1, marginTop: 6, fontVariantNumeric: "tabular-nums" }}>{value}</div>
    </div>
  );
}

Object.assign(window, { CandidatesView, MILESTONES });
})();
