/* eslint-disable */
// Admin view — rewritten to match production HireArt onboarding tracker:
//   - Light gray top nav, no sidebar
//   - Production "Onboarding Tracker"-style table: small text, alternating rows, blue worker links
//   - "Statements of Work" filtered view of that same table
//   - Bulk re-engagement (Epic 2)
//   - Open-ended SOW handling

(function () {
const { Icon, Button, Badge, Avatar } = window;
const { Card } = window;
const { WORKERS, SOW_TEMPLATE_FIELDS, ACTIVITY, today, daysFromNow } = window;
const { SOWStatePill, Callout, PageHeader, SectionHeader, snakeToTitle } = window;
const { SOWForm } = window;
const { SOWPaper } = window;
const { useState, useMemo } = React;

// ---------- Top nav ----------
function AdminTopNav({ active, onNav }) {
  const items = [
    { k: "acct",      label: "Acct. Mgmt.", icon: "credit-card" },
    { k: "finance",   label: "Finance",     icon: "credit-card" },
    { k: "sales",     label: "Sales",       icon: "chart-bar-1" },
    { k: "screening", label: "Screening",   icon: "user" },
    { k: "sourcing",  label: "Sourcing",    icon: "filter" },
    { k: "staffing",  label: "Staffing",    icon: "users" },
    { k: "support",   label: "Support",     icon: "settings" },
    { k: "pricing",   label: "Pricing",     icon: "tag" },
  ];
  return (
    <header style={{
      background: "var(--neutral-20)",
      borderBottom: "1px solid var(--neutral-30)",
      padding: "10px 24px",
      display: "flex", alignItems: "center", gap: 8,
      fontFamily: "var(--font-body)",
    }}>
      <img src="assets/logos/logo-primary.svg" alt="HireArt" style={{ height: 22, marginRight: 8 }} />
      <nav style={{ display: "flex", gap: 4, flex: 1 }}>
        {items.map(it => {
          const isActive = active === it.k || (it.k === "staffing" && active === "sows");
          return (
            <button key={it.k} onClick={() => onNav(it.k)} style={{
              padding: "6px 10px",
              border: 0, background: "transparent",
              fontSize: 13.5, fontWeight: isActive ? 700 : 500,
              color: isActive ? "var(--neutral-100)" : "var(--neutral-90)",
              cursor: "pointer", display: "inline-flex", alignItems: "center", gap: 6,
              fontFamily: "var(--font-body)",
              borderBottom: isActive ? "2px solid var(--neutral-100)" : "2px solid transparent",
            }}>
              <Icon name={it.icon} size={14} />
              {it.label}
            </button>
          );
        })}
      </nav>
      <span style={{
        border: "1.5px solid var(--red-60)", color: "var(--red-80)",
        padding: "2px 10px", borderRadius: 100, fontSize: 11, fontWeight: 700, letterSpacing: "0.04em",
      }}>Production</span>
      <div style={{ fontSize: 12, color: "var(--blue-80)", fontWeight: 600, paddingLeft: 14, display: "inline-flex", alignItems: "center", gap: 4 }}>
        erica.hill@hireart.com <Icon name="chevron-down" size={12} />
      </div>
    </header>
  );
}

// ---------- Sub-tabs under Staffing ----------
function StaffingSubnav({ active, onNav }) {
  const tabs = [
    { k: "sows",     label: "Expiring badges" },
  ];
  return (
    <div style={{
      borderBottom: "1px solid var(--neutral-30)",
      background: "var(--neutral-10)",
      padding: "0 24px",
      display: "flex", gap: 0,
      fontFamily: "var(--font-body)",
    }}>
      {tabs.map(t => {
        const isActive = active === t.k;
        return (
          <button key={t.k} onClick={() => onNav(t.k)} style={{
            padding: "12px 18px", border: 0, background: "transparent",
            fontSize: 13.5, fontWeight: isActive ? 700 : 500,
            color: isActive ? "var(--neutral-100)" : "var(--neutral-70)",
            borderBottom: isActive ? "3px solid var(--neutral-100)" : "3px solid transparent",
            cursor: "pointer", marginBottom: -1,
          }}>{t.label}</button>
        );
      })}
    </div>
  );
}

// ---------- Filter bar (matches the production tracker style) ----------
// Now accepts a `credTypeOptions` prop so the same bar serves the generalized
// "expiring credentials" dashboard.
function FilterBar({ filters, onChange, onCSV, columnsCount = 7, credTypeOptions = [] }) {
  const ChipSelect = ({ label, value, options, onChange }) => (
    <div style={{ position: "relative" }}>
      <select value={value} onChange={e => onChange(e.target.value)} style={{
        appearance: "none", WebkitAppearance: "none",
        border: "1px solid var(--neutral-30)", borderRadius: 6,
        padding: "8px 28px 8px 12px",
        fontFamily: "var(--font-body)", fontSize: 13, fontWeight: 500,
        background: "var(--neutral-10)", color: "var(--neutral-100)",
        cursor: "pointer", minWidth: 140,
      }}>
        {options.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
      </select>
      <Icon name="chevron-down" size={12} style={{ position: "absolute", right: 10, top: "50%", transform: "translateY(-50%)", pointerEvents: "none", color: "var(--neutral-70)" }} />
    </div>
  );

  return (
    <div style={{
      display: "flex", alignItems: "center", gap: 8,
      padding: "12px 14px",
      border: "1px solid var(--neutral-30)", borderRadius: 8,
      background: "var(--neutral-10)",
      marginBottom: 12, flexWrap: "wrap",
    }}>
      <div style={{ position: "relative", flex: "1 1 280px", minWidth: 240 }}>
        <Icon name="search" size={14} style={{ position: "absolute", left: 12, top: "50%", transform: "translateY(-50%)", color: "var(--neutral-60)" }} />
        <input
          type="text" placeholder="Search by worker name or email..."
          value={filters.search} onChange={e => onChange({ ...filters, search: e.target.value })}
          style={{
            width: "100%", border: "1px solid var(--neutral-30)", borderRadius: 6,
            padding: "8px 12px 8px 32px", fontSize: 13, fontFamily: "var(--font-body)",
            background: "var(--neutral-10)", outline: "none",
          }} />
      </div>
      <ChipSelect label="Client" value={filters.client} options={[
        { value: "all", label: "Client: all" },
        { value: "Anthropic", label: "Client: Anthropic" },
      ]} onChange={v => onChange({ ...filters, client: v })} />
      <ChipSelect label="State" value={filters.state} options={[
        { value: "all", label: "State: all needing action" },
        { value: "expiring", label: "Expiring (≤30d)" },
        { value: "expired", label: "Expired" },
        { value: "pending-signature", label: "Pending signature" },
      ]} onChange={v => onChange({ ...filters, state: v })} />
      <ChipSelect label="Credential type" value={filters.credType} options={[
        { value: "all", label: "Credential: all types" },
        ...credTypeOptions.map(o => ({ value: o.value, label: o.label })),
      ]} onChange={v => onChange({ ...filters, credType: v })} />

      <button style={{
        border: "1px solid var(--neutral-30)", background: "var(--neutral-10)",
        padding: "8px 12px", borderRadius: 6, fontSize: 13, fontFamily: "var(--font-body)",
        color: "var(--neutral-90)", cursor: "pointer", display: "inline-flex", alignItems: "center", gap: 6,
      }}>
        Columns <span style={{ background: "var(--blue-60)", color: "white", borderRadius: 100, padding: "0 7px", fontSize: 11, fontWeight: 700 }}>{columnsCount}</span>
      </button>
      <button onClick={onCSV} style={{
        border: "1px solid var(--neutral-30)", background: "var(--neutral-10)",
        padding: "8px 12px", borderRadius: 6, fontSize: 13, fontFamily: "var(--font-body)",
        color: "var(--neutral-90)", cursor: "pointer",
      }}>Export CSV</button>
    </div>
  );
}

// ---------- Helpers for the deadline cell ----------
function endDateCell(validThru) {
  if (validThru == null) {
    return <span style={{ color: "var(--purple-80)", fontWeight: 600, fontSize: 12.5 }}>Open-ended</span>;
  }
  return <span style={{ fontSize: 13, fontVariantNumeric: "tabular-nums", color: "var(--neutral-100)", whiteSpace: "nowrap" }}>{shortDate(validThru)}</span>;
}

function timeUntilCell(days, validThru) {
  if (validThru == null) {
    return <span style={{ color: "var(--neutral-50)", fontSize: 12.5 }}>—</span>;
  }
  let fg;
  if (days < 0)        fg = "var(--red-100)";
  else if (days <= 14) fg = "var(--red-100)";
  else if (days <= 30) fg = "var(--yellow-100)";
  else                 fg = "var(--neutral-100)";
  return (
    <span style={{
      color: fg, fontWeight: 700,
      fontSize: 13, fontVariantNumeric: "tabular-nums", whiteSpace: "nowrap",
    }}>{days}</span>
  );
}

// Format "Nov 11, 2026" -> "11/11/26"
function shortDate(s) {
  if (!s) return "";
  const d = new Date(s);
  if (isNaN(d)) return s;
  return `${d.getMonth() + 1}/${d.getDate()}/${String(d.getFullYear()).slice(-2)}`;
}

// ---------- The big table (credential-agnostic) ----------
// Each row is one expiring credential. The same worker can appear multiple times
// (e.g. SOW + driver's license). Columns are general — Worker / Credential /
// State / End date / Days left / Actions.

// How a given credential type renews. Drives the "Expiration cadence" column.
//   - Re-sign annually   → must be re-acknowledged on a yearly cadence (handbooks, etc.)
//   - Annual Re-screen   → background-check-style yearly screening
//   - Custom Date        → expiration is a one-off date set on the credential itself
//                          (per-project SOWs, state-issued IDs, etc.)
function expirationCadence(r) {
  const muted = { color: "var(--neutral-70)" };
  if (r.type === "hireart_handbook")   return <span>Re-sign annually</span>;
  if (r.type === "background_check")   return <span>Annual Re-screen</span>;
  return <span style={muted}>Custom Date</span>;
}

function ExpiringTable({ rows, selected, onToggle, onToggleAll, onWorker, onReengageOne }) {
  const allSelected = rows.length > 0 && rows.every(r => selected.has(r.id));
  return (
    <div style={{ border: "1px solid var(--neutral-30)", borderRadius: 8, background: "var(--neutral-10)", overflow: "hidden" }}>
      <table style={{ width: "100%", borderCollapse: "collapse", fontFamily: "var(--font-body)" }}>
        <thead>
          <tr style={{ borderBottom: "1px solid var(--neutral-30)" }}>
            <th style={th(40)}>
              <input type="checkbox" checked={allSelected} onChange={onToggleAll} />
            </th>
            <th style={th()}>Worker</th>
            <th style={th()}>Credential</th>
            <th style={th()}>Expiration cadence</th>
            <th style={th()}>State</th>
            <th style={th()}>End date</th>
            <th style={th()}>Days left</th>
            <th style={{ ...th(), textAlign: "right" }}>Actions</th>
          </tr>
        </thead>
        <tbody>
          {rows.map((r, i) => {
            const days = r.expiresDate ? daysFromNow(r.expiresDate) : null;
            const isSel = selected.has(r.id);
            const credType = window.CREDENTIAL_TYPES[r.type] || {};
            return (
              <tr key={r.id} style={{
                background: isSel ? "var(--blue-20)" : (i % 2 ? "var(--neutral-20)" : "transparent"),
                borderBottom: "1px solid var(--neutral-30)",
              }}>
                <td style={td()}>
                  <input type="checkbox" checked={isSel} onChange={() => onToggle(r.id)} />
                </td>
                <td style={td()}>
                  <button onClick={() => onWorker(r.workerId)} style={linkBtn}>{r.workerName}</button>
                  <div style={{ fontSize: 11, color: "var(--neutral-70)", marginTop: 1 }}>{r.workerJob} · {r.client}</div>
                </td>
                <td style={td()}>
                  <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>
                    <Icon name={credType.icon || "document"} size={14} style={{ color: "var(--neutral-70)" }} />
                    <strong>{r.label}</strong>
                  </span>
                </td>
                <td style={{ ...td(), maxWidth: 280 }}>
                  <div style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", color: "var(--neutral-90)" }}>
                    {expirationCadence(r)}
                  </div>
                </td>
                <td style={td()}><SOWStatePillSmall state={r.status} /></td>
                <td style={td()}>{endDateCell(r.expires)}</td>
                <td style={td()}>{timeUntilCell(days, r.expires)}</td>
                <td style={{ ...td(), textAlign: "right" }}>
                  <button onClick={() => onReengageOne(r)} style={{
                    background: "transparent", border: "1px solid var(--neutral-30)",
                    padding: "4px 10px", borderRadius: 6,
                    fontSize: 12, fontFamily: "var(--font-body)", color: "var(--neutral-90)",
                    cursor: "pointer",
                  }}>Renew</button>
                </td>
              </tr>
            );
          })}
        </tbody>
      </table>
      <div style={{ padding: "10px 14px", display: "flex", justifyContent: "space-between", alignItems: "center", fontSize: 12, color: "var(--neutral-70)", borderTop: "1px solid var(--neutral-30)" }}>
        <div>Rows per page: <select style={{ border: "1px solid var(--neutral-30)", borderRadius: 4, padding: "2px 6px", marginLeft: 4 }}><option>20</option><option>50</option></select></div>
        <div><strong style={{ color: "var(--neutral-100)" }}>1 - {rows.length}</strong> of <strong style={{ color: "var(--neutral-100)" }}>{rows.length}</strong> expiring credentials</div>
        <div style={{ display: "inline-flex", gap: 4 }}>
          <span style={{ background: "var(--blue-60)", color: "white", padding: "2px 8px", borderRadius: 4, fontWeight: 700 }}>1</span>
        </div>
      </div>
    </div>
  );
}

const th = (w) => ({
  textAlign: "left", padding: "10px 14px",
  fontSize: 12, fontWeight: 600, color: "var(--neutral-80)",
  background: "var(--neutral-20)",
  width: w,
});
const td = () => ({ padding: "10px 14px", fontSize: 13, color: "var(--neutral-100)", verticalAlign: "top" });
// Smaller, single-line variant of the SOW state pill for dense table rows.
const SMALL_PILL_META = {
  "expiring":          { bg: "var(--yellow-20)", fg: "var(--yellow-100)", label: "Expiring" },
  "expired":           { bg: "var(--red-20)",    fg: "var(--red-100)",    label: "Expired"  },
  "pending-signature": { bg: "var(--blue-20)",   fg: "var(--blue-100)",   label: "Awaiting sig." },
  "active":            { bg: "var(--green-20)",  fg: "var(--green-100)",  label: "Active"   },
  "open-ended":        { bg: "var(--purple-20)", fg: "var(--purple-100)", label: "Open-ended" },
  "signed":            { bg: "var(--green-20)",  fg: "var(--green-100)",  label: "Signed"   },
  "in-progress":       { bg: "var(--blue-20)",   fg: "var(--blue-100)",   label: "In progress" },
  "not-started":       { bg: "var(--neutral-20)", fg: "var(--neutral-90)", label: "Not started" },
};
function SOWStatePillSmall({ state }) {
  const m = SMALL_PILL_META[state] || SMALL_PILL_META["not-started"];
  return (
    <span style={{
      display: "inline-flex", alignItems: "center", gap: 4,
      padding: "1px 8px", borderRadius: 100,
      background: m.bg, color: m.fg,
      fontSize: 11.5, fontWeight: 700, letterSpacing: "0.02em",
      lineHeight: 1.6, whiteSpace: "nowrap", fontFamily: "var(--font-body)",
    }}>
      <span style={{ width: 5, height: 5, borderRadius: 999, background: "currentColor" }} />
      {m.label}
    </span>
  );
}

const linkBtn = {
  background: "none", border: 0, padding: 0, cursor: "pointer",
  fontFamily: "var(--font-body)", fontSize: 13, fontWeight: 600,
  color: "var(--blue-80)", textDecoration: "none",
};

// ---------- The Expiring Credentials page ----------
function SOWTrackerView({ onWorker, onCreateSOW, onReengageOne, onReengageBulk }) {
  const [filters, setFilters] = useState({ search: "", client: "all", state: "all", credType: "all" });
  const [selected, setSelected] = useState(new Set());

  const ALL_CREDS = window.EXPIRING_CREDENTIALS || [];

  // Worklist: only credentials that need action (expiring ≤30d, expired, or pending sig).
  const inWorklist = c => ["expiring", "expired", "pending-signature"].includes(c.status);

  const filtered = useMemo(() => ALL_CREDS.filter(c => {
    if (!inWorklist(c)) return false;
    if (filters.search && !(c.workerName + " " + c.workerEmail + " " + c.label).toLowerCase().includes(filters.search.toLowerCase())) return false;
    if (filters.client !== "all" && c.client !== filters.client) return false;
    if (filters.state !== "all" && c.status !== filters.state) return false;
    if (filters.credType !== "all" && c.type !== filters.credType) return false;
    return true;
  }), [filters, ALL_CREDS]);

  const counts = useMemo(() => ({
    expiring: ALL_CREDS.filter(c => c.status === "expiring").length,
    expired:  ALL_CREDS.filter(c => c.status === "expired").length,
    pending:  ALL_CREDS.filter(c => c.status === "pending-signature").length,
    typeBreakdown: Object.entries(window.CREDENTIAL_TYPES || {}).map(([k, v]) => ({
      key: k, label: v.label, icon: v.icon,
      count: ALL_CREDS.filter(c => c.type === k && inWorklist(c)).length,
    })).filter(x => x.count > 0),
  }), [ALL_CREDS]);

  const credTypeOptions = Object.entries(window.CREDENTIAL_TYPES || {}).map(([k, v]) => ({
    value: k, label: v.label,
  }));

  const toggle = id => setSelected(s => {
    const n = new Set(s); n.has(id) ? n.delete(id) : n.add(id); return n;
  });
  const toggleAll = () => setSelected(s => {
    if (filtered.every(r => s.has(r.id))) {
      const n = new Set(s); filtered.forEach(r => n.delete(r.id)); return n;
    } else {
      const n = new Set(s); filtered.forEach(r => n.add(r.id)); return n;
    }
  });

  return (
    <div style={{ padding: "24px 24px 40px", maxWidth: 1400, margin: "0 auto" }}>
      <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", gap: 12, marginBottom: 16, flexWrap: "wrap" }}>
        <div>
          <h1 style={{ fontFamily: "var(--font-headline)", fontSize: 30, fontWeight: 700, margin: 0, color: "var(--neutral-100)" }}>Expiring badges</h1>
          <div style={{ fontSize: 13, color: "var(--neutral-70)", marginTop: 4 }}>
            {counts.expiring} expiring within 30 days · {counts.expired} already expired · {counts.pending} awaiting signature.{" "}
            <span style={{ color: "var(--neutral-60)" }}>Statements of Work, driver's licenses, handbook re-acks, and any other badge with an expiration date.</span>
          </div>
        </div>
      </div>

      {/* Quick chips showing the breakdown by credential type */}
      <div style={{ display: "flex", gap: 8, marginBottom: 12, flexWrap: "wrap" }}>
        {counts.typeBreakdown.map(t => {
          const isActive = filters.credType === t.key;
          return (
            <button key={t.key}
              onClick={() => setFilters({ ...filters, credType: isActive ? "all" : t.key })}
              style={{
                display: "inline-flex", alignItems: "center", gap: 6,
                padding: "6px 12px", borderRadius: 100,
                border: `1px solid ${isActive ? "var(--neutral-100)" : "var(--neutral-30)"}`,
                background: isActive ? "var(--neutral-100)" : "var(--neutral-10)",
                color: isActive ? "var(--neutral-10)" : "var(--neutral-100)",
                fontSize: 12.5, fontWeight: 600, fontFamily: "var(--font-body)",
                cursor: "pointer",
              }}>
              <Icon name={t.icon} size={13} />
              {t.label}
              <span style={{
                background: isActive ? "var(--neutral-90)" : "var(--neutral-30)",
                color: isActive ? "var(--neutral-10)" : "var(--neutral-90)",
                borderRadius: 100, padding: "0 7px", fontSize: 11, fontWeight: 700,
              }}>{t.count}</span>
            </button>
          );
        })}
      </div>

      <FilterBar filters={filters} onChange={setFilters} onCSV={() => {}} credTypeOptions={credTypeOptions} />

      {/* Bulk action bar — appears when rows are selected */}
      {selected.size > 0 && (
        <div style={{
          display: "flex", alignItems: "center", gap: 12,
          padding: "10px 14px", marginBottom: 12,
          background: "var(--blue-20)", border: "1px solid var(--blue-60)", borderRadius: 8,
          fontSize: 13,
        }}>
          <Icon name="check-square" size={16} style={{ color: "var(--blue-80)" }} />
          <strong style={{ color: "var(--blue-100)" }}>{selected.size} selected</strong>
          <span style={{ color: "var(--neutral-80)" }}>· bulk actions:</span>
          <button onClick={() => onReengageBulk([...selected])} style={{
            background: "var(--blue-60)", color: "white", border: 0,
            padding: "5px 12px", borderRadius: 6, fontSize: 12.5, fontWeight: 600, cursor: "pointer",
            display: "inline-flex", alignItems: "center", gap: 4, fontFamily: "var(--font-body)",
          }}>
            <Icon name="refresh" size={14} /> Renew {selected.size} credentials
          </button>
          <button style={{
            background: "transparent", color: "var(--neutral-90)", border: "1px solid var(--neutral-30)",
            padding: "5px 12px", borderRadius: 6, fontSize: 12.5, fontWeight: 500, cursor: "pointer",
            fontFamily: "var(--font-body)",
          }}>Send reminder email</button>
          <button onClick={() => setSelected(new Set())} style={{
            marginLeft: "auto",
            background: "transparent", color: "var(--blue-80)", border: 0,
            padding: 0, fontSize: 12.5, fontWeight: 600, cursor: "pointer", fontFamily: "var(--font-body)",
          }}>Clear</button>
        </div>
      )}

      <ExpiringTable
        rows={filtered}
        selected={selected}
        onToggle={toggle}
        onToggleAll={toggleAll}
        onWorker={onWorker}
        onReengageOne={(row) => onReengageOne(row.workerId)}
      />

      <div style={{ marginTop: 14, fontSize: 12, color: "var(--neutral-70)" }}>
        <Icon name="info" size={12} style={{ verticalAlign: "middle", marginRight: 4 }} />
        Workers with expired credentials aren't blocked from working — expiration is informational. The renewal flow is per-credential-type.
      </div>
    </div>
  );
}

// ---------- Bulk re-engage dialog ----------
function BulkReengageDialog({ workerIds, onClose, onConfirm }) {
  const ws = WORKERS.filter(w => workerIds.includes(w.id));
  const [extension, setExtension] = useState("6 months");
  const [openEnded, setOpenEnded] = useState(false);
  const [reuseScope, setReuseScope] = useState(true);

  return (
    <div style={{ position: "fixed", inset: 0, background: "rgba(20,20,20,0.5)", display: "flex", alignItems: "center", justifyContent: "center", zIndex: 100, padding: 24 }}>
      <div style={{ background: "var(--neutral-10)", borderRadius: 8, boxShadow: "var(--shadow-lg)", width: 640, maxWidth: "100%", maxHeight: "90vh", overflow: "auto" }}>
        <div style={{ padding: "16px 20px", borderBottom: "1px solid var(--neutral-30)", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
          <div>
            <div style={{ fontFamily: "var(--font-headline)", fontSize: 18, fontWeight: 700 }}>Bulk re-engage {ws.length} workers</div>
            <div style={{ fontSize: 12, color: "var(--neutral-70)", marginTop: 2 }}>One new SOW will be drafted per worker, reusing existing project + scope.</div>
          </div>
          <button onClick={onClose} style={{ background: "none", border: 0, cursor: "pointer", padding: 4 }}><Icon name="x" size={18} /></button>
        </div>
        <div style={{ padding: 20, display: "flex", flexDirection: "column", gap: 16 }}>
          <div>
            <label style={{ fontSize: 12, fontWeight: 600, marginBottom: 6, display: "block" }}>New end date</label>
            <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
              <select value={extension} onChange={e => setExtension(e.target.value)} disabled={openEnded} style={{
                border: "1px solid var(--neutral-30)", borderRadius: 6,
                padding: "8px 12px", fontFamily: "var(--font-body)", fontSize: 13,
                background: openEnded ? "var(--neutral-20)" : "var(--neutral-10)",
              }}>
                <option>3 months from previous end</option>
                <option>6 months</option>
                <option>1 year</option>
                <option>Custom date per worker</option>
              </select>
              <label style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: 13 }}>
                <input type="checkbox" checked={openEnded} onChange={e => setOpenEnded(e.target.checked)} />
                Open-ended (no end date)
              </label>
            </div>
          </div>
          <label style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 13, padding: "10px 12px", border: "1px solid var(--neutral-30)", borderRadius: 6, background: "var(--neutral-20)" }}>
            <input type="checkbox" checked={reuseScope} onChange={e => setReuseScope(e.target.checked)} />
            Reuse project, scope, deliverables, and acceptance criteria from each worker's previous SOW.
          </label>
          <div style={{ border: "1px solid var(--neutral-30)", borderRadius: 6, overflow: "hidden", maxHeight: 220, overflowY: "auto" }}>
            <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 12.5 }}>
              <thead>
                <tr style={{ background: "var(--neutral-20)" }}>
                  <th style={{ ...th(), padding: "8px 12px" }}>Worker</th>
                  <th style={{ ...th(), padding: "8px 12px" }}>Current end</th>
                  <th style={{ ...th(), padding: "8px 12px" }}>New end</th>
                </tr>
              </thead>
              <tbody>
                {ws.map(w => (
                  <tr key={w.id} style={{ borderTop: "1px solid var(--neutral-30)" }}>
                    <td style={{ padding: "6px 12px", fontWeight: 600 }}>{w.name}</td>
                    <td style={{ padding: "6px 12px", color: "var(--neutral-70)" }}>{w.sow.validThru || "open-ended"}</td>
                    <td style={{ padding: "6px 12px", color: "var(--neutral-90)" }}>{openEnded ? "open-ended" : "Nov 4, 2026"}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
        <div style={{ padding: "12px 20px", borderTop: "1px solid var(--neutral-30)", display: "flex", justifyContent: "flex-end", gap: 8, background: "var(--neutral-20)" }}>
          <Button color="secondary" size="md" onClick={onClose}>Cancel</Button>
          <Button color="primary-green" size="md" iconStart="send" onClick={onConfirm}>Send {ws.length} signing requests</Button>
        </div>
      </div>
    </div>
  );
}

// ---------- Single-worker re-engage dialog (carries open-ended support) ----------
function ReengageDialog({ workerId, onClose, onConfirm }) {
  const w = WORKERS.find(x => x.id === workerId);
  if (!w) return null;
  return (
    <div style={{ position: "fixed", inset: 0, background: "rgba(20,20,20,0.5)", display: "flex", alignItems: "center", justifyContent: "center", zIndex: 100, padding: 24 }}>
      <div style={{ background: "var(--neutral-10)", borderRadius: 8, boxShadow: "var(--shadow-lg)", width: 880, maxWidth: "100%", maxHeight: "90vh", overflow: "auto" }}>
        <div style={{ padding: "16px 20px", borderBottom: "1px solid var(--neutral-30)", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
          <div>
            <div style={{ fontFamily: "var(--font-headline)", fontSize: 18, fontWeight: 700, display: "flex", alignItems: "center", gap: 8 }}>
              <span style={{ fontSize: 22 }} aria-hidden="true">🎉</span>
              Renew {w.name}
            </div>
          </div>
          <button onClick={onClose} style={{ background: "none", border: 0, cursor: "pointer", padding: 4 }}><Icon name="x" size={18} /></button>
        </div>
        <div style={{ padding: 20 }}>
          <SOWForm
            worker={w} mode="reengage" fields={SOW_TEMPLATE_FIELDS}
            initialValues={w.sow.mergeValues}
            onSubmit={onConfirm} onCancel={onClose}
            submitLabel="Send"
          />
        </div>
      </div>
    </div>
  );
}

// ---------- Worker detail (kept, but restyled to match the production palette) ----------
function WorkerDetailView({ workerId, onBack, onReengage }) {
  const w = WORKERS.find(x => x.id === workerId);
  if (!w) return null;
  const days = w.sow.validThruDate ? daysFromNow(w.sow.validThruDate) : null;

  return (
    <div style={{ padding: "20px 24px 40px", maxWidth: 1400, margin: "0 auto" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 12, color: "var(--neutral-70)", marginBottom: 12 }}>
        <button onClick={onBack} style={{ ...linkBtn, fontSize: 12, color: "var(--blue-80)" }}>Statements of Work</button>
        <Icon name="chevron-right" size={12} />
        <span style={{ color: "var(--neutral-100)" }}>{w.name}</span>
      </div>

      <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: 16, marginBottom: 20 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
          <Avatar name={w.name} size={48} bg="var(--blue-20)" />
          <div>
            <h1 style={{ fontFamily: "var(--font-headline)", fontSize: 26, fontWeight: 700, margin: 0 }}>{w.name}</h1>
            <div style={{ fontSize: 13, color: "var(--neutral-70)", marginTop: 2 }}>
              {w.job} · {w.employmentType} · {w.client} · started {w.startDate}
            </div>
          </div>
        </div>
        <div style={{ display: "flex", gap: 8 }}>
          <Button color="secondary" size="md" iconStart="mail">Message</Button>
          {(w.sow.state === "expiring" || w.sow.state === "expired" || w.sow.state === "active" || w.sow.state === "open-ended") && (
            <Button color="primary-green" size="md" iconStart="refresh" onClick={() => onReengage(w.id)}>Re-engage</Button>
          )}
        </div>
      </div>

      {(w.sow.state === "expiring" || w.sow.state === "expired") && (
        <div style={{
          padding: "12px 16px", marginBottom: 20,
          background: w.sow.state === "expired" ? "var(--red-20)" : "var(--yellow-20)",
          border: `1px solid ${w.sow.state === "expired" ? "var(--red-60)" : "var(--yellow-60)"}`,
          borderRadius: 6, fontSize: 13,
          display: "flex", alignItems: "center", gap: 10, justifyContent: "space-between",
        }}>
          <div>
            <Icon name={w.sow.state === "expired" ? "alert-circle" : "alert-triangle"} size={16} style={{ verticalAlign: "middle", marginRight: 6 }} />
            <strong>{w.sow.state === "expired" ? `SOW expired ${Math.abs(days)} days ago` : `SOW expires in ${days} days`}.</strong>
            {" "}Worker isn't blocked, but you should issue a new SOW.
          </div>
          <Button color="primary-green" size="sm" iconStart="refresh" onClick={() => onReengage(w.id)}>Re-engage</Button>
        </div>
      )}

      <div style={{ display: "grid", gridTemplateColumns: "1.5fr 1fr", gap: 20, alignItems: "start" }}>
        <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
          <Card>
            <SectionHeader title="Active Statement of Work" hint={`Template: ${w.sow.template}`} />
            <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 13, marginTop: 4 }}>
              <tbody>
                <Row k="Project" v={w.sow.mergeValues.project_name} />
                <Row k="Status" v={<SOWStatePill state={w.sow.state} />} />
                <Row k="Start date" v={w.sow.validFrom} />
                <Row k="End date" v={w.sow.validThru || <span style={{ color: "var(--purple-80)", fontWeight: 600 }}>Open-ended</span>} />
                <Row k="Pay rate" v={w.sow.mergeValues.pay_rate} />
                <Row k="Signed" v={w.sow.signedAt || <em style={{ color: "var(--neutral-60)" }}>Pending</em>} />
              </tbody>
            </table>
          </Card>

          <Card>
            <SectionHeader title="Merge values" hint="What was sent to Dropbox Sign at signing time." />
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10, marginTop: 8 }}>
              {Object.entries(w.sow.mergeValues).map(([k, v]) => (
                <div key={k} style={{ padding: "8px 10px", background: "var(--neutral-20)", border: "1px solid var(--neutral-30)", borderRadius: 6, fontSize: 12 }}>
                  <div style={{ fontWeight: 600, color: "var(--neutral-70)", marginBottom: 2 }}>{snakeToTitle(k)}</div>
                  <div style={{ color: "var(--neutral-100)", maxHeight: 60, overflow: "hidden" }}>{v || <em style={{ color: "var(--neutral-50)" }}>(empty)</em>}</div>
                </div>
              ))}
            </div>
          </Card>

          <Card>
            <SectionHeader title="SOW history" />
            <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 13, marginTop: 4 }}>
              <thead>
                <tr style={{ background: "var(--neutral-20)" }}>
                  <th style={{ ...th(), padding: "6px 10px" }}>Signed</th>
                  <th style={{ ...th(), padding: "6px 10px" }}>End date</th>
                  <th style={{ ...th(), padding: "6px 10px" }}>Status</th>
                </tr>
              </thead>
              <tbody>
                {w.sow.history.map((h, i) => (
                  <tr key={i} style={{ borderTop: "1px solid var(--neutral-30)" }}>
                    <td style={{ padding: "6px 10px" }}>{h.signedAt || "Pending"}</td>
                    <td style={{ padding: "6px 10px" }}>{h.endDate || "open-ended"}</td>
                    <td style={{ padding: "6px 10px" }}><SOWStatePill state={h.status === "active" ? "active" : h.status === "expired" ? "expired" : h.status === "pending-signature" ? "pending-signature" : "active"} /></td>
                  </tr>
                ))}
              </tbody>
            </table>
          </Card>
        </div>

        <div style={{ position: "sticky", top: 16, display: "flex", flexDirection: "column", gap: 12 }}>
          <SectionHeader title="Signed PDF" hint={w.sow.signedAt ? "Stored in the Content system." : "Not yet signed."} />
          <SOWPaper mergeValues={w.sow.mergeValues} signed={!!w.sow.signedAt} />
          {w.sow.signedAt && <Button color="secondary" size="md" iconStart="download-1" isFullWidth>Download PDF</Button>}
        </div>
      </div>
    </div>
  );
}

function Row({ k, v }) {
  return (
    <tr style={{ borderTop: "1px solid var(--neutral-30)" }}>
      <td style={{ width: 140, color: "var(--neutral-70)", fontWeight: 600, padding: "8px 0", fontSize: 12.5 }}>{k}</td>
      <td style={{ padding: "8px 0", color: "var(--neutral-100)" }}>{v}</td>
    </tr>
  );
}

// ---------- Offer creation flow ----------
function OfferCreateView({ onBack, onSent }) {
  const [step, setStep] = useState(1);
  const [worker, setWorker] = useState({
    name: "Maya Chen", email: "maya.chen@example.com", job: "Software Engineer", payRate: "$92/hr", startDate: "May 4, 2026",
  });
  const stub = {
    sow: {
      template: "Anthropic — SOW v3", hellosignTemplateId: "tpl_4f3a",
      mergeValues: {
        worker_name: worker.name, project_name: "", start_date: worker.startDate, end_date: "",
        pay_rate: worker.payRate, project_overview: "", scope_of_work: "", deliverables: "", acceptance_criteria: "",
      },
    }
  };
  const [merge, setMerge] = useState(stub.sow.mergeValues);

  return (
    <div style={{ padding: "20px 24px 40px", maxWidth: 1400, margin: "0 auto" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 12, color: "var(--neutral-70)", marginBottom: 12 }}>
        <button onClick={onBack} style={{ ...linkBtn, fontSize: 12 }}>Statements of Work</button>
        <Icon name="chevron-right" size={12} />
        <span style={{ color: "var(--neutral-100)" }}>New offer · {worker.name}</span>
      </div>

      <h1 style={{ fontFamily: "var(--font-headline)", fontSize: 26, fontWeight: 700, margin: "0 0 6px" }}>
        {step === 1 ? "Offer details" : step === 2 ? "Statement of Work merge values" : "Review & send"}
      </h1>
      <div style={{ fontSize: 13, color: "var(--neutral-70)", marginBottom: 20 }}>
        Step {step} of 3
      </div>

      {step === 1 && (
        <Card>
          <SectionHeader title="Worker & role" />
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16, marginTop: 8 }}>
            <Field2 label="Worker name" value={worker.name} onChange={v => setWorker({ ...worker, name: v })} />
            <Field2 label="Email"       value={worker.email} onChange={v => setWorker({ ...worker, email: v })} />
            <Field2 label="Job title"   value={worker.job} onChange={v => setWorker({ ...worker, job: v })} />
            <Field2 label="Pay rate"    value={worker.payRate} onChange={v => setWorker({ ...worker, payRate: v })} />
            <Field2 label="Start date"  value={worker.startDate} onChange={v => setWorker({ ...worker, startDate: v })} />
          </div>
          <div style={{ display: "flex", justifyContent: "flex-end", marginTop: 20, gap: 8 }}>
            <Button color="secondary" size="md" onClick={onBack}>Cancel</Button>
            <Button color="primary-green" size="md" iconEnd="arrow-right" onClick={() => setStep(2)}>Continue to SOW</Button>
          </div>
        </Card>
      )}

      {step === 2 && (
        <SOWForm worker={stub} mode="offer" fields={SOW_TEMPLATE_FIELDS}
          initialValues={merge}
          onSubmit={({ values }) => { setMerge(values); setStep(3); }}
          onCancel={() => setStep(1)} submitLabel="Continue to review" />
      )}

      {step === 3 && (
        <div style={{ display: "grid", gridTemplateColumns: "1.2fr 1fr", gap: 24, alignItems: "start" }}>
          <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
            <Card>
              <SectionHeader title="Offer summary" />
              <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 13, marginTop: 4 }}>
                <tbody>
                  <Row k="Worker" v={`${worker.name} · ${worker.email}`} />
                  <Row k="Role" v={`${worker.job} · W-2 Contractor`} />
                  <Row k="Pay" v={worker.payRate} />
                  <Row k="Start" v={worker.startDate} />
                  <Row k="Project" v={merge.project_name} />
                  <Row k="End date" v={merge.end_date || <span style={{ color: "var(--purple-80)", fontWeight: 600 }}>Open-ended</span>} />
                </tbody>
              </table>
            </Card>
            <Callout tone="info" icon="info" title="What happens next">
              An offer email is sent to {worker.name}. The DocumentMergeContent row is created so when they hit the SOW signing step, the iframe is pre-filled.
            </Callout>
            <div style={{ display: "flex", justifyContent: "space-between" }}>
              <Button color="secondary" size="md" onClick={() => setStep(2)} iconStart="arrow-left">Back to SOW</Button>
              <Button color="primary-green" size="md" iconStart="send" onClick={onSent}>Send offer</Button>
            </div>
          </div>
          <div style={{ position: "sticky", top: 16 }}>
            <SectionHeader title="Live SOW preview" />
            <SOWPaper mergeValues={merge} signed={false} />
          </div>
        </div>
      )}
    </div>
  );
}

function Field2({ label, value, onChange, placeholder }) {
  return (
    <div>
      <div style={{ fontSize: 12, fontWeight: 600, marginBottom: 6 }}>{label}</div>
      <input type="text" value={value} onChange={e => onChange(e.target.value)} placeholder={placeholder} style={{
        width: "100%", border: "1px solid var(--neutral-30)", borderRadius: 6,
        padding: "8px 12px", fontFamily: "var(--font-body)", fontSize: 13,
        background: "var(--neutral-10)", outline: "none",
      }} />
    </div>
  );
}

// ---------- Documents & templates page ----------
function TemplatesView() {
  return (
    <div style={{ padding: "20px 24px 40px", maxWidth: 1400, margin: "0 auto" }}>
      <h1 style={{ fontFamily: "var(--font-headline)", fontSize: 26, fontWeight: 700, margin: "0 0 4px" }}>Documents & templates</h1>
      <div style={{ fontSize: 13, color: "var(--neutral-70)", marginBottom: 20 }}>
        Per-staffing-config Documents. Adding one with <code>document_type :statement_of_work</code> turns on the SOW badge for every worker on this config.
      </div>
      <div style={{ border: "1px solid var(--neutral-30)", borderRadius: 8, background: "var(--neutral-10)", overflow: "hidden" }}>
        <div style={{ padding: "12px 16px", borderBottom: "1px solid var(--neutral-30)", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
          <div>
            <div style={{ fontWeight: 700, fontSize: 14 }}>Anthropic — W-2 Contractor</div>
            <div style={{ fontSize: 12, color: "var(--neutral-70)" }}>Staffing config · 6 documents · 184 active workers</div>
          </div>
          <Badge color="green">Active</Badge>
        </div>
        <table style={{ width: "100%", borderCollapse: "collapse", fontFamily: "var(--font-body)" }}>
          <thead>
            <tr style={{ background: "var(--neutral-20)", borderBottom: "1px solid var(--neutral-30)" }}>
              {["Document", "document_type", "Dropbox Sign template", "Status"].map(h => (
                <th key={h} style={th()}>{h}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {[
              { doc: "Employee handbook", type: "hellosign_template", tpl: "tpl_handbook_v8" },
              { doc: "Code of ethics",     type: "hellosign_template", tpl: "tpl_ethics_v3" },
              { doc: "Federal W-4",        type: "hellosign_template", tpl: "tpl_fedw4_v2" },
              { doc: "Statement of Work — Anthropic v3", type: "statement_of_work", tpl: "tpl_4f3a", sow: true },
              { doc: "NDA — Anthropic specific", type: "hellosign_template", tpl: "tpl_anthropic_nda_v2" },
            ].map((r, i) => (
              <tr key={i} style={{ borderBottom: "1px solid var(--neutral-30)", background: r.sow ? "var(--green-20)" : (i % 2 ? "var(--neutral-20)" : "transparent") }}>
                <td style={td()}>
                  <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>
                    <Icon name="document" size={14} /> <strong>{r.doc}</strong>
                    {r.sow && <Badge color="green">New</Badge>}
                  </span>
                </td>
                <td style={td()}><code style={{ background: "var(--neutral-10)", border: "1px solid var(--neutral-30)", padding: "1px 6px", borderRadius: 4, fontFamily: "var(--font-mono)", fontSize: 12 }}>{r.type}</code></td>
                <td style={td()}><code style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--neutral-90)" }}>{r.tpl}</code></td>
                <td style={td()}><Badge color="green" dot>Active</Badge></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

Object.assign(window, {
  AdminTopNav, StaffingSubnav,
  SOWTrackerView, OfferCreateView, WorkerDetailView, TemplatesView,
  ReengageDialog, BulkReengageDialog,
});

})();
