/* eslint-disable */
// Manager UI — sidebar, topbar with global search pill (manager_layout_v2),
// onboarding index page (onboarding_index_manager_ui), search modal, CSV modal.
//
// Driven from outside via a `state` prop so the walkthrough timeline can show
// any combination of search-open / search-query / column-set / date-range / csv-modal / etc.

(function () {
const { ONBOARDINGS, parseStart, searchWorkspace, EXTRA_COLS } = window;

// ---- tokens ---------------------------------------------------------
const T = {
  page:        "#FFFFFF",
  bgSoft:      "#FAFAFA",
  hairline:    "#EAEAEA",
  hairlineSoft:"#F0F0F0",
  text:        "#141414",
  textMuted:   "#5F5F5F",
  textDim:     "#8A8A8A",
  primary:     "#493ED8",         // purple-60
  primaryRing: "rgba(73,62,216,0.18)",
  primarySoft: "#EEEBFB",
};

// ---- Icon helper (from <img src=svg> set) ---------------------------
function I({ name, size = 16, style = {} }) {
  return (
    <img src={`assets/icons/${name}.svg`} width={size} height={size}
      style={{ display: "inline-block", verticalAlign: "middle", flexShrink: 0, ...style }} />
  );
}

// ---- Status pill (matches screenshot: outlined rounded pill) --------
function StatusPill({ status }) {
  const map = {
    "Ready to Work":               { bg: "#DDEEFB", border: "#1858B6", fg: "#0F2D66" },
    "Fully Cleared Requirements":  { bg: "#DEF5E5", border: "#0E6A3E", fg: "#0E3D24" },
    "Screenings":                  { bg: "#FFF6CC", border: "#876B00", fg: "#3F2F00" },
    "Enrollment Complete":         { bg: "#E6E1FB", border: "#3D31C8", fg: "#241B7A" },
    "Offer Accepted":              { bg: "#E6F4EC", border: "#0E6A3E", fg: "#0E3D24" },
    "Offer Sent":                  { bg: "#FFFFFF", border: "#141414", fg: "#141414" },
    "Offer Initiated":             { bg: "#FFF0E0", border: "#9A4A00", fg: "#4A2200" },
    "Offer Rejected":              { bg: "#FCE2E2", border: "#A4252A", fg: "#5C1115" },
    "Revoked":                     { bg: "#F2F2F2", border: "#5A5A5A", fg: "#2A2A2A" },
  };
  const m = map[status] || map["Offer Sent"];
  return (
    <span style={{
      display: "inline-flex", alignItems: "center",
      padding: "2px 12px",
      borderRadius: 999,
      border: `1.5px solid ${m.border}`,
      background: m.bg, color: m.fg,
      fontSize: 12, fontWeight: 500,
      letterSpacing: "0.005em",
      whiteSpace: "nowrap",
    }}>{status}</span>
  );
}

// ---- Tiny progress bar w/ count -------------------------------------
function ProgressCount({ filled, total }) {
  if (total === 0) {
    return (
      <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
        <span style={{ width: 28, height: 4, borderRadius: 999, background: T.primarySoft, display: "block" }} />
        <span style={{ fontSize: 12, color: T.textMuted, fontVariantNumeric: "tabular-nums" }}>0 of 0</span>
      </div>
    );
  }
  const pct = Math.min(100, (filled / total) * 100);
  const isFull = filled === total;
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
      <div style={{
        width: 28, height: 4, borderRadius: 999, background: "#E6E1FB",
        position: "relative", overflow: "hidden",
      }}>
        <div style={{
          width: `${pct}%`, height: "100%",
          background: isFull ? "#1A2C9C" : "#3D31C8",
          borderRadius: 999,
        }} />
      </div>
      <span style={{ fontSize: 12, color: T.text, fontVariantNumeric: "tabular-nums" }}>
        {filled} of {total}
      </span>
    </div>
  );
}

// ---- View pill ------------------------------------------------------
function ViewBtn() {
  return (
    <button style={{
      padding: "5px 18px",
      borderRadius: 8,
      border: `1.5px solid ${T.text}`,
      background: "#FFF",
      fontFamily: "var(--font-body)",
      fontSize: 13, fontWeight: 500,
      color: T.text,
      boxShadow: "2px 2px 0 0 #141414",
      cursor: "pointer",
    }}>View</button>
  );
}

// ====================================================================
// LEFT NAV
// ====================================================================
function SideNav({ active = "onboardings" }) {
  const sections = [
    { items: [
      { key: "dashboard",   label: "Dashboard",       icon: "dashboard" },
    ]},
    { label: "Hiring", items: [
      { key: "jobs",            label: "Jobs",              icon: "briefcase" },
      { key: "interviews",      label: "Interview calendar",icon: "calendar-month" },
      { key: "onboardings",     label: "Onboardings",       icon: "user-plus" },
    ]},
    { label: "Finance", items: [
      { key: "timesheets",      label: "Timesheets",        icon: "clock" },
      { key: "pto",             label: "Paid time off",     icon: "settings-1" },
      { key: "expenses",        label: "Expenses",          icon: "file" },
      { key: "payments",        label: "One-time payments", icon: "credit-card" },
    ]},
    { label: "Management", items: [
      { key: "workers",         label: "Workers",           icon: "user-square" },
      { key: "timeoffcal",      label: "Time off calendar", icon: "grid-1" },
      { key: "documents",       label: "Documents",         icon: "file" },
      { key: "reports",         label: "Reports",           icon: "chart-bar-1" },
    ]},
    { label: "Admin", items: [
      { key: "orgsettings",     label: "Organization settings", icon: "users" },
      { key: "contact",         label: "Contact HireArt",       icon: "help-circle" },
    ]},
  ];
  return (
    <aside style={{
      width: 248, flexShrink: 0,
      background: "#FFFFFF",
      borderRight: `1px solid ${T.hairline}`,
      display: "flex", flexDirection: "column",
      fontFamily: "var(--font-body)",
      overflow: "auto",
    }}>
      <div style={{
        display: "flex", alignItems: "center", gap: 10,
        padding: "20px 22px 18px",
      }}>
        <img src="assets/logos/logo-primary.svg" alt="HireArt" style={{ height: 26 }} />
      </div>
      <div style={{ height: 1, background: T.hairlineSoft, margin: "0 16px" }} />
      <nav style={{ padding: "14px 16px 24px", flex: 1, display: "flex", flexDirection: "column", gap: 2 }}>
        {sections.map((sec, si) => (
          <React.Fragment key={si}>
            {sec.label && (
              <div style={{
                fontSize: 12, fontWeight: 700, letterSpacing: "0.06em",
                textTransform: "uppercase", color: T.text,
                padding: "18px 4px 10px",
              }}>{sec.label}</div>
            )}
            {sec.items.map(it => {
              const on = it.key === active;
              return (
                <div key={it.key} style={{
                  display: "flex", alignItems: "center", gap: 12,
                  padding: "10px 14px",
                  borderRadius: 10,
                  background: on ? "#F2F2F2" : "transparent",
                  border: on ? `1.5px solid ${T.text}` : "1.5px solid transparent",
                  fontWeight: on ? 700 : 500,
                  fontSize: 14.5,
                  color: T.text,
                  marginBottom: 2,
                }}>
                  <I name={it.icon} size={18} />
                  <span>{it.label}</span>
                </div>
              );
            })}
          </React.Fragment>
        ))}
      </nav>
    </aside>
  );
}

// ====================================================================
// TOP BAR — manager_layout_v2 includes the global search pill
// ====================================================================
function TopBar({ searchQuery = "" }) {
  return (
    <div style={{
      height: 60,
      display: "flex", alignItems: "center", gap: 16,
      padding: "0 28px",
      borderBottom: `1px solid ${T.hairline}`,
      background: "#FFF",
      fontFamily: "var(--font-body)",
    }}>
      {/* Global search pill */}
      <div style={{
        flex: 1, maxWidth: 520,
        display: "flex", alignItems: "center", gap: 10,
        padding: "8px 12px",
        borderRadius: 999,
        border: `2px solid ${T.primary}`,
        background: "#FFF",
        cursor: "pointer",
      }}>
        <I name="search" size={16} />
        <span style={{
          flex: 1, fontSize: 13.5, fontWeight: 600, color: T.text,
        }}>Search your workspace…</span>
        <span style={{
          fontSize: 11, fontWeight: 600, color: T.textMuted,
          padding: "1px 7px", borderRadius: 6,
          background: T.bgSoft,
          border: `1px solid ${T.hairline}`,
          fontVariantNumeric: "tabular-nums",
          letterSpacing: "0.02em",
        }}>⌘K</span>
      </div>
      <div style={{ flex: 1 }} />
      <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
        <button style={{
          background: "transparent", border: 0, cursor: "pointer",
          padding: 8, borderRadius: 8,
        }}>
          <I name="bell" size={18} />
        </button>
        <button style={{
          background: "transparent", border: 0, cursor: "pointer",
          padding: 8, borderRadius: 8,
        }}>
          <I name="settings-1" size={18} />
        </button>
      </div>
    </div>
  );
}

// ====================================================================
// GLOBAL SEARCH MODAL
// ====================================================================
function SearchModal({ visible, query = "", caretOn = true }) {
  const results = searchWorkspace(query);
  return (
    <div style={{
      position: "absolute", inset: 0,
      display: visible ? "flex" : "none",
      justifyContent: "center", alignItems: "flex-start",
      paddingTop: 80,
      background: "rgba(20,20,20,0.42)",
      zIndex: 50,
      fontFamily: "var(--font-body)",
    }}>
      <div style={{
        width: 720, maxWidth: "92%",
        background: "#FFF",
        borderRadius: 14,
        boxShadow: "0 24px 48px rgba(0,0,0,0.18)",
        padding: 18,
        display: "flex", flexDirection: "column",
        gap: 14,
      }}>
        {/* Search input row */}
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <div style={{
            flex: 1,
            display: "flex", alignItems: "center", gap: 10,
            border: `2px solid ${T.primary}`,
            borderRadius: 999,
            padding: "10px 16px",
            background: "#FFF",
          }}>
            <I name="search" size={18} />
            <div style={{
              flex: 1, fontSize: 16, fontWeight: 600, color: T.text,
              display: "flex", alignItems: "center",
              minHeight: 22,
            }}>
              {query ? (
                <span>{query}</span>
              ) : (
                <span style={{ color: "#A6A6A6", fontWeight: 500 }}>Search your workspace…</span>
              )}
              <span style={{
                display: "inline-block",
                width: 1.5, height: 18,
                marginLeft: 1,
                background: caretOn ? T.text : "transparent",
              }} />
            </div>
          </div>
          <button style={{
            background: "transparent", border: 0, cursor: "pointer",
            padding: 6, borderRadius: 8,
          }}>
            <I name="x" size={18} />
          </button>
        </div>

        {/* Results */}
        {results.length > 0 && (
          <div style={{
            borderTop: `1px solid ${T.hairlineSoft}`,
            paddingTop: 6,
            display: "flex", flexDirection: "column",
          }}>
            {results.map((r, i) => (
              <div key={i} style={{
                display: "flex", alignItems: "flex-start", gap: 12,
                padding: "12px 4px",
                borderBottom: i < results.length - 1 ? `1px solid ${T.hairlineSoft}` : "none",
              }}>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 15, fontWeight: 600, color: T.text }}>{r.name}</div>
                  <div style={{
                    fontSize: 13, color: T.textMuted, marginTop: 3,
                    overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap",
                  }}>{r.sub}</div>
                </div>
                <span style={{
                  display: "inline-flex", alignItems: "center",
                  padding: "2px 12px",
                  borderRadius: 999,
                  border: `1.5px solid ${r.kind === "worker" ? "#1858B6" : "#876B00"}`,
                  background: r.kind === "worker" ? "#DDEEFB" : "#FFF6CC",
                  color: r.kind === "worker" ? "#0F2D66" : "#3F2F00",
                  fontSize: 12, fontWeight: 500,
                }}>{r.kind === "worker" ? "Worker" : "Candidate"}</span>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

// ====================================================================
// COLUMNS DROPDOWN PANEL (for selecting extra columns)
// ====================================================================
const ALL_EXTRA = ["Location", "Criminal", "MVR", "Drug Test"];

function ColumnsDropdown({ open, selectedExtras = [] }) {
  if (!open) return null;
  const baseCols = [
    { name: "Worker Name", locked: true },
    { name: "Start Date",  locked: true },
    { name: "Job Title",   locked: true },
    { name: "Onboarding Status", locked: true },
    { name: "Required for Work",       locked: true },
    { name: "Fully Cleared Requirements", locked: true },
    { name: "Notes",       locked: true },
  ];
  const extra = ALL_EXTRA.map(n => ({ name: n, locked: false, on: selectedExtras.includes(n) }));
  const all = [...baseCols, ...extra];
  return (
    <div style={{
      position: "absolute",
      top: "100%", left: 0, marginTop: 6,
      width: 360,
      background: "#FFF",
      border: `1.5px solid ${T.text}`,
      borderRadius: 10,
      boxShadow: "4px 4px 0 0 #141414",
      padding: 8,
      zIndex: 30,
      fontFamily: "var(--font-body)",
    }}>
      <div style={{
        fontSize: 11, fontWeight: 600, color: T.textMuted,
        letterSpacing: "0.06em", textTransform: "uppercase",
        padding: "6px 10px",
      }}>Available columns</div>
      {all.map((c, i) => {
        const checked = c.locked || c.on;
        return (
          <div key={i} style={{
            display: "flex", alignItems: "center", gap: 10,
            padding: "8px 10px",
            borderRadius: 6,
            background: c.on ? "#F4F3FB" : "transparent",
          }}>
            <span style={{
              width: 16, height: 16, borderRadius: 4,
              border: `1.5px solid ${checked ? T.primary : "#BDBDBD"}`,
              background: checked ? T.primary : "#FFF",
              display: "inline-flex", alignItems: "center", justifyContent: "center",
              flexShrink: 0,
            }}>
              {checked && <I name="check" size={11} style={{ filter: "invert(1) brightness(2)" }} />}
            </span>
            <span style={{
              flex: 1, fontSize: 13.5, fontWeight: 500,
              color: c.locked ? T.textDim : T.text,
            }}>{c.name}</span>
            {c.locked && <span style={{ fontSize: 11, color: T.textDim }}>Default</span>}
          </div>
        );
      })}
    </div>
  );
}

// ====================================================================
// DATE PICKER POPUP (for Start Date filter)
// ====================================================================
function DatePicker({ open, monthLabel = "May 2026", highlightStart, highlightEnd, hoverDay }) {
  if (!open) return null;
  const days = [];
  // simplified May 2026 grid: May 1 = Friday
  const firstWeekday = 5;
  for (let i = 0; i < firstWeekday; i++) days.push(null);
  for (let d = 1; d <= 31; d++) days.push(d);

  return (
    <div style={{
      position: "absolute",
      top: "100%", left: 0, marginTop: 6,
      width: 280,
      background: "#FFF",
      border: `1.5px solid ${T.text}`,
      borderRadius: 10,
      boxShadow: "4px 4px 0 0 #141414",
      padding: 14,
      zIndex: 30,
      fontFamily: "var(--font-body)",
    }}>
      <div style={{
        display: "flex", alignItems: "center", justifyContent: "space-between",
        marginBottom: 12,
      }}>
        <span style={{ fontSize: 13, fontWeight: 600 }}>{monthLabel}</span>
        <span style={{ display: "flex", gap: 4 }}>
          <span style={{ width: 22, height: 22, display: "inline-flex", alignItems: "center", justifyContent: "center" }}>
            <I name="chevron-right" size={12} style={{ transform: "rotate(180deg)" }} />
          </span>
          <span style={{ width: 22, height: 22, display: "inline-flex", alignItems: "center", justifyContent: "center" }}>
            <I name="chevron-right" size={12} />
          </span>
        </span>
      </div>
      <div style={{
        display: "grid", gridTemplateColumns: "repeat(7, 1fr)",
        rowGap: 4, columnGap: 2,
        fontSize: 11, color: T.textDim, marginBottom: 4,
      }}>
        {["S","M","T","W","T","F","S"].map((d, i) => (
          <div key={i} style={{ textAlign: "center", padding: "4px 0" }}>{d}</div>
        ))}
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(7, 1fr)", rowGap: 2, columnGap: 2 }}>
        {days.map((d, i) => {
          const inRange = d && highlightStart && highlightEnd && d >= highlightStart && d <= highlightEnd;
          const isStart = d === highlightStart;
          const isEnd   = d === highlightEnd;
          const isHover = d === hoverDay && !isStart && !isEnd;
          return (
            <div key={i} style={{
              height: 30, display: "flex", alignItems: "center", justifyContent: "center",
              fontSize: 12,
              fontWeight: (isStart || isEnd) ? 600 : 400,
              color: (isStart || isEnd) ? "#FFF"
                   : inRange ? T.primary
                   : d ? T.text : "transparent",
              background: (isStart || isEnd) ? T.primary
                        : inRange ? T.primarySoft
                        : isHover ? "#F4F3FB"
                        : "transparent",
              borderRadius: (isStart && isEnd) ? 999 :
                            isStart ? "999px 0 0 999px" :
                            isEnd ? "0 999px 999px 0" :
                            inRange ? 0 : 999,
            }}>{d ?? ""}</div>
          );
        })}
      </div>
    </div>
  );
}

// ====================================================================
// CSV EXPORT MODAL (preparing → ready)
// ====================================================================
function CsvModal({ phase, rowCount, fileName }) {
  if (phase === "hidden") return null;
  return (
    <div style={{
      position: "absolute", inset: 0,
      display: "flex", justifyContent: "center", alignItems: "center",
      background: "rgba(20,20,20,0.42)",
      zIndex: 60,
      fontFamily: "var(--font-body)",
    }}>
      <div style={{
        width: 460, background: "#FFF",
        borderRadius: 12,
        border: `1.5px solid ${T.text}`,
        boxShadow: "8px 8px 0 0 #141414",
        padding: 24,
      }}>
        <div style={{
          display: "flex", alignItems: "center", gap: 12, marginBottom: 14,
        }}>
          <span style={{
            width: 36, height: 36, borderRadius: 8,
            background: phase === "ready" ? "#DEF5E5" : T.primarySoft,
            display: "inline-flex", alignItems: "center", justifyContent: "center",
          }}>
            <I name={phase === "ready" ? "check" : "file-download"} size={18} />
          </span>
          <div>
            <div style={{ fontSize: 16, fontWeight: 700, color: T.text }}>
              {phase === "ready" ? "Export ready" : "Preparing export"}
            </div>
            <div style={{ fontSize: 12, color: T.textMuted }}>
              {rowCount} onboardings · CSV
            </div>
          </div>
        </div>

        {phase === "preparing" ? (
          <div>
            <div style={{
              height: 6, background: T.bgSoft, borderRadius: 999, overflow: "hidden",
              border: `1px solid ${T.hairline}`,
            }}>
              <div className="csv-bar" style={{
                height: "100%", background: T.primary,
                borderRadius: 999,
              }} />
            </div>
            <div style={{ fontSize: 12, color: T.textMuted, marginTop: 10 }}>
              Generating <code style={{
                fontFamily: "var(--font-mono, ui-monospace, monospace)", color: T.text,
                background: T.bgSoft, padding: "1px 6px", borderRadius: 4, border: `1px solid ${T.hairline}`,
              }}>{fileName}</code>…
            </div>
          </div>
        ) : (
          <div>
            <div style={{
              display: "flex", alignItems: "center", gap: 10,
              padding: "12px 14px",
              border: `1px solid ${T.hairline}`,
              borderRadius: 10,
              background: T.bgSoft,
            }}>
              <I name="file" size={20} />
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 13, fontWeight: 600, color: T.text }}>{fileName}</div>
                <div style={{ fontSize: 11, color: T.textDim }}>{rowCount} rows · 4.2 KB</div>
              </div>
              <button style={{
                padding: "6px 12px",
                border: `1.5px solid ${T.text}`,
                borderRadius: 8,
                background: "#FFF",
                fontSize: 12, fontWeight: 600,
                boxShadow: "2px 2px 0 0 #141414",
                cursor: "pointer",
                fontFamily: "var(--font-body)",
              }}>Download</button>
            </div>
            <div style={{ fontSize: 12, color: T.textMuted, marginTop: 12 }}>
              Saved to your Downloads folder.
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

// ====================================================================
// NOTES SIDE PANEL — opens when clicking View on a row
// ====================================================================
function NotesPanel({ visible, workerName, note }) {
  if (!visible) return null;
  return (
    <div style={{
      position: "absolute", top: 0, right: 0, bottom: 0,
      width: 380,
      background: "#FFF",
      borderLeft: `1.5px solid ${T.text}`,
      boxShadow: "-8px 0 0 0 rgba(20,20,20,0.04)",
      zIndex: 40,
      display: "flex", flexDirection: "column",
      fontFamily: "var(--font-body)",
      animation: "slideInRight 240ms ease-out",
    }}>
      <div style={{
        padding: "20px 22px 16px",
        borderBottom: `1px solid ${T.hairline}`,
        display: "flex", alignItems: "center", justifyContent: "space-between",
      }}>
        <h2 style={{
          margin: 0, fontFamily: "var(--font-display)",
          fontSize: 18, fontWeight: 700, color: T.text,
        }}>Notes for {workerName}</h2>
      </div>
      <div style={{ padding: 18, flex: 1, overflow: "auto" }}>
        <div style={{
          border: `1px solid ${T.hairline}`,
          borderRadius: 10,
          padding: "14px 14px",
        }}>
          <div style={{
            display: "flex", justifyContent: "space-between",
            alignItems: "baseline", marginBottom: 8,
          }}>
            <span style={{ fontWeight: 600, fontSize: 13.5, color: T.text }}>Lanny Degrate</span>
            <span style={{ fontSize: 11.5, color: T.textDim }}>April 27, 2026 · 03:06 pm EDT</span>
          </div>
          <div style={{ fontSize: 13.5, color: T.text, lineHeight: 1.5 }}>{note}</div>
        </div>
      </div>
    </div>
  );
}

// ====================================================================
// CSV PREVIEW (the actual file content the manager opens)
// ====================================================================
function CsvPreview({ visible, fileName, csvText }) {
  if (!visible) return null;
  const lines = csvText.split("\n");
  const header = lines[0].split(",").map(c => c.replace(/^"|"$/g, ""));
  const rows = lines.slice(1).map(r => {
    // simple csv split (data has no commas inside quotes except escaped quotes)
    const out = []; let cur = ""; let inQ = false;
    for (let i = 0; i < r.length; i++) {
      const c = r[i];
      if (c === '"') {
        if (inQ && r[i+1] === '"') { cur += '"'; i++; }
        else inQ = !inQ;
      } else if (c === "," && !inQ) { out.push(cur); cur = ""; }
      else cur += c;
    }
    out.push(cur);
    return out;
  });

  return (
    <div style={{
      position: "absolute", inset: 0,
      background: "#1E1E1E",
      display: "flex", flexDirection: "column",
      zIndex: 70,
      fontFamily: "ui-monospace, SFMono-Regular, Menlo, monospace",
    }}>
      {/* file header bar */}
      <div style={{
        height: 40,
        background: "#2D2D2D",
        borderBottom: "1px solid #3A3A3A",
        display: "flex", alignItems: "center",
        padding: "0 16px",
        gap: 10,
      }}>
        <I name="file" size={14} style={{ filter: "invert(1) brightness(0.9)" }} />
        <span style={{ fontSize: 12, color: "#E5E5E5", fontWeight: 500 }}>{fileName}</span>
        <span style={{
          fontSize: 10, color: "#9A9A9A",
          padding: "1px 6px", borderRadius: 4,
          background: "#3A3A3A",
        }}>CSV</span>
      </div>
      {/* table */}
      <div style={{ flex: 1, overflow: "auto", padding: 0 }}>
        <table style={{
          width: "100%", borderCollapse: "collapse",
          color: "#E5E5E5", fontSize: 12,
        }}>
          <thead>
            <tr>
              {header.map((h, i) => (
                <th key={i} style={{
                  textAlign: "left",
                  padding: "10px 14px",
                  background: "#252525",
                  borderBottom: "1px solid #3A3A3A",
                  borderRight: i < header.length - 1 ? "1px solid #3A3A3A" : "none",
                  color: "#7BD9A9",
                  fontWeight: 600,
                  whiteSpace: "nowrap",
                  fontVariantNumeric: "tabular-nums",
                }}>{h}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {rows.map((r, ri) => (
              <tr key={ri} style={{
                background: ri % 2 === 0 ? "#1E1E1E" : "#222222",
              }}>
                {r.map((c, ci) => (
                  <td key={ci} style={{
                    padding: "8px 14px",
                    borderBottom: "1px solid #2A2A2A",
                    borderRight: ci < r.length - 1 ? "1px solid #2A2A2A" : "none",
                    whiteSpace: "nowrap",
                    color: c === "" ? "#5F5F5F" : "#D5D5D5",
                  }}>{c === "" ? "—" : c}</td>
                ))}
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

// ====================================================================
// ONBOARDING INDEX — main page
// ====================================================================
function OnboardingIndex({
  searchValue = "",
  selectedExtras = [],            // ["Location","Criminal","MVR","Drug Test"]
  columnsOpen = false,
  datePickerOpen = false,
  dateStart = "",                 // "May 11, 2026"
  dateEnd   = "",                 // "May 13, 2026"
  dateHighlightStart, dateHighlightEnd, dateHoverDay,
  filteredRows,                   // optional override, otherwise compute from props
}) {
  // Compute filtered rows
  let rows = ONBOARDINGS;
  if (searchValue) {
    const q = searchValue.toLowerCase();
    rows = rows.filter(r => r.name.toLowerCase().includes(q));
  }
  if (dateStart && dateEnd) {
    const a = parseStart(dateStart), b = parseStart(dateEnd);
    rows = rows.filter(r => {
      const t = parseStart(r.start);
      return t >= a && t <= b;
    });
  }
  if (filteredRows) rows = filteredRows;

  // Visible columns
  const showLocation = selectedExtras.includes("Location");
  const showCriminal = selectedExtras.includes("Criminal");
  const showMVR      = selectedExtras.includes("MVR");
  const showDrug     = selectedExtras.includes("Drug Test");
  const numExtras    = selectedExtras.length;
  const totalCols    = 7 + numExtras;

  return (
    <div style={{
      flex: 1,
      padding: "28px 36px 60px",
      background: "#FFF",
      fontFamily: "var(--font-body)",
      color: T.text,
      overflow: "auto",
    }}>
      {/* breadcrumb */}
      <div style={{
        display: "flex", alignItems: "center", gap: 8,
        fontSize: 12, color: T.textMuted,
        marginBottom: 18,
      }}>
        <I name="home" size={13} />
        <span>Dashboard</span>
        <span style={{ color: T.textDim }}>/</span>
        <span style={{ color: T.text, fontWeight: 500 }}>Onboardings</span>
      </div>

      {/* page heading */}
      <h1 style={{
        margin: 0, fontFamily: "var(--font-display)",
        fontSize: 28, fontWeight: 700, letterSpacing: "-0.005em",
      }}>Onboardings</h1>
      <div style={{ fontSize: 13, color: T.textMuted, marginTop: 4 }}>
        Track onboarding progress
      </div>

      {/* Filter row */}
      <div style={{
        marginTop: 22,
        display: "grid",
        gridTemplateColumns: "1.1fr 1.3fr 1.6fr 1.1fr 14px 1.1fr",
        gap: 14, alignItems: "end",
      }}>
        <div>
          <Label>Search</Label>
          <FieldShell iconStart="search">
            <FieldInput value={searchValue} placeholder="Name or email…" />
          </FieldShell>
        </div>
        <div>
          <Label>Onboarding Status</Label>
          <FieldShell iconEnd="chevron-down">
            <span style={{ color: T.textDim, fontSize: 13.5 }}>Select…</span>
          </FieldShell>
        </div>
        <div>
          <Label>Job Title</Label>
          <FieldShell iconEnd="chevron-down">
            <span style={{ color: T.textDim, fontSize: 13.5 }}>Select…</span>
          </FieldShell>
        </div>
        <div style={{ position: "relative" }}>
          <Label>Start Date</Label>
          <FieldShell iconStart="calendar">
            <span style={{ color: dateStart ? T.text : T.textDim, fontSize: 13.5 }}>{dateStart || ""}</span>
          </FieldShell>
          <DatePicker open={datePickerOpen}
            highlightStart={dateHighlightStart}
            highlightEnd={dateHighlightEnd}
            hoverDay={dateHoverDay} />
        </div>
        <div style={{ paddingBottom: 12, color: T.textMuted, textAlign: "center", fontSize: 14 }}>→</div>
        <div>
          <FieldShell iconStart="calendar">
            <span style={{ color: dateEnd ? T.text : T.textDim, fontSize: 13.5 }}>{dateEnd || ""}</span>
          </FieldShell>
        </div>
      </div>

      {/* Columns + Download row */}
      <div style={{
        marginTop: 18,
        display: "grid",
        gridTemplateColumns: "1fr auto",
        gap: 14, alignItems: "end",
      }}>
        <div>
          <Label>Columns</Label>
          <div style={{ position: "relative" }}>
            <FieldShell iconEnd="chevron-down" trailing={
              numExtras > 0 ? null : null
            }>
              <span style={{
                display: "inline-flex", alignItems: "center",
                padding: "1px 12px", borderRadius: 999,
                background: T.primarySoft, color: T.primary,
                fontSize: 11, fontWeight: 600,
              }}>{`${numExtras + 7} selected`}</span>
              <span style={{ flex: 1 }} />
              <span style={{ fontSize: 12, color: T.textMuted, marginRight: 12 }}>Clear</span>
            </FieldShell>
            <ColumnsDropdown open={columnsOpen} selectedExtras={selectedExtras} />
          </div>
        </div>
        <div style={{ paddingBottom: 0 }}>
          <button style={{
            display: "inline-flex", alignItems: "center", gap: 8,
            padding: "11px 22px",
            border: `1.5px solid ${T.text}`,
            borderRadius: 10,
            background: "#FFF",
            fontFamily: "var(--font-body)",
            fontSize: 13.5, fontWeight: 600,
            color: T.text,
            boxShadow: "3px 3px 0 0 #141414",
            cursor: "pointer",
          }}>
            <I name="file-download" size={15} />
            Download CSV
          </button>
        </div>
      </div>

      {/* Table */}
      <div style={{
        marginTop: 22,
        border: "none",
        borderRadius: 0,
        overflow: "hidden",
        boxShadow: "none",
      }}>
        <div style={{ overflowX: numExtras > 0 ? "auto" : "visible" }}>
          <table style={{
            width: numExtras >= 4 ? 1180 : "100%",
            minWidth: "100%",
            borderCollapse: "collapse",
            fontFamily: "var(--font-body)",
            fontSize: 13,
            tableLayout: "fixed",
          }}>
            <colgroup>
              <col style={{ width: numExtras > 0 ? 110 : 130 }} />
              <col style={{ width: 76 }} />
              {showLocation && <col style={{ width: 110 }} />}
              <col style={{ width: numExtras > 0 ? 200 : 260 }} />
              <col style={{ width: 130 }} />
              <col style={{ width: 96 }} />
              <col style={{ width: 100 }} />
              {showCriminal && <col style={{ width: 78 }} />}
              {showMVR      && <col style={{ width: 78 }} />}
              {showDrug     && <col style={{ width: 80 }} />}
              <col style={{ width: 76 }} />
            </colgroup>
            <thead>
              <tr>
                <Th>Worker Name</Th>
                <Th><span style={{display:"block"}}>Start</span><span style={{display:"block"}}>Date</span></Th>
                {showLocation && <Th>Location</Th>}
                <Th>Job Title</Th>
                <Th>Onboarding Status</Th>
                <Th info><span style={{display:"block"}}>Required</span><span style={{display:"block"}}>for Work</span></Th>
                <Th info><span style={{display:"block"}}>Fully Cleared</span><span style={{display:"block"}}>Requirements</span></Th>
                {showCriminal && <Th>Criminal</Th>}
                {showMVR      && <Th>MVR</Th>}
                {showDrug     && <Th>Drug Test</Th>}
                <Th>Notes</Th>
              </tr>
            </thead>
            <tbody>
              {rows.length === 0 && (
                <tr>
                  <td colSpan={totalCols} style={{
                    padding: "32px 16px", textAlign: "center",
                    color: T.textMuted, fontSize: 13,
                  }}>No onboardings match these filters.</td>
                </tr>
              )}
              {rows.map((r, i) => (
                <tr key={r.id} style={{
                  borderTop: `1px solid ${T.hairlineSoft}`,
                  background: i % 2 === 0 ? "#FFF" : "#FCFCFC",
                }}>
                  <Td>
                    <a style={{
                      color: T.text, textDecoration: "underline",
                      textDecorationColor: T.hairline, textDecorationThickness: 1,
                      textUnderlineOffset: 2, fontWeight: 500,
                    }}>{r.name}</a>
                  </Td>
                  <Td>{r.start}</Td>
                  {showLocation && <Td>{r.location}</Td>}
                  <Td><span style={{ color: T.text }}>{r.job}</span></Td>
                  <Td><StatusPill status={r.status} /></Td>
                  <Td><ProgressCount filled={r.required.f} total={r.required.t} /></Td>
                  <Td><ProgressCount filled={r.cleared.f} total={r.cleared.t} /></Td>
                  {showCriminal && <Td>{r.criminal === "—" ? <span style={{ color: T.textDim }}>—</span> : r.criminal}</Td>}
                  {showMVR      && <Td>{r.mvr === "—" ? <span style={{ color: T.textDim }}>—</span> : r.mvr}</Td>}
                  {showDrug     && <Td>{r.drug === "—" ? <span style={{ color: T.textDim }}>—</span> : r.drug}</Td>}
                  <Td><ViewBtn /></Td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

function Label({ children }) {
  return <div style={{ fontSize: 12, fontWeight: 600, color: T.text, marginBottom: 6 }}>{children}</div>;
}
function FieldShell({ iconStart, iconEnd, children, trailing }) {
  return (
    <div style={{
      display: "flex", alignItems: "center", gap: 8,
      padding: "10px 12px",
      border: `1.5px solid ${T.text}`,
      borderRadius: 10,
      background: "#FFF",
    }}>
      {iconStart && <I name={iconStart} size={15} />}
      {children}
      {iconEnd && <I name={iconEnd} size={14} />}
      {trailing}
    </div>
  );
}
function FieldInput({ value, placeholder }) {
  return (
    <span style={{
      flex: 1, fontSize: 13.5,
      color: value ? T.text : T.textDim,
    }}>{value || placeholder}</span>
  );
}
function Th({ children, info }) {
  return (
    <th style={{
      textAlign: "left",
      padding: "12px 14px",
      fontSize: 11.5, fontWeight: 600,
      color: T.text,
      background: T.bgSoft,
      borderBottom: `1.5px solid ${T.text}`,
      whiteSpace: "normal",
      lineHeight: 1.25,
      verticalAlign: "middle",
    }}>
      <span style={{ display: "flex", alignItems: "center", gap: 6 }}>
        <span style={{ display: "block" }}>{children}</span>
        {info && <I name="info" size={12} style={{ opacity: 0.55, flexShrink: 0 }} />}
      </span>
    </th>
  );
}
function Td({ children }) {
  return (
    <td style={{
      padding: "16px 14px",
      verticalAlign: "middle",
      fontSize: 13,
      color: T.text,
      lineHeight: 1.4,
    }}>{children}</td>
  );
}

// ====================================================================
// FULL APP — composes everything
// ====================================================================
function ManagerApp({ scene }) {
  return (
    <div style={{
      width: "100%", height: "100%",
      display: "flex", flexDirection: "column",
      background: "#FFF", position: "relative",
      overflow: "hidden",
    }}>
      <div style={{ display: "flex", flex: 1, minHeight: 0 }}>
        <SideNav active="onboardings" />
        <div style={{ flex: 1, display: "flex", flexDirection: "column", minWidth: 0 }}>
          <TopBar />
          <OnboardingIndex {...scene.page} />
        </div>
      </div>

      <SearchModal
        visible={!!scene.search?.visible}
        query={scene.search?.query || ""}
        caretOn={scene.search?.caretOn !== false}
      />
      <NotesPanel
        visible={!!scene.notes?.visible}
        workerName={scene.notes?.workerName || ""}
        note={scene.notes?.note || ""}
      />
      <CsvModal
        phase={scene.csv?.phase || "hidden"}
        rowCount={scene.csv?.rowCount || 0}
        fileName={scene.csv?.fileName || "onboardings.csv"}
      />
      <CsvPreview
        visible={!!scene.csvPreview?.visible}
        fileName={scene.csvPreview?.fileName || "onboardings.csv"}
        csvText={scene.csvPreview?.csvText || ""}
      />
    </div>
  );
}

Object.assign(window, {
  ManagerApp,
  // expose tokens too in case the walkthrough wants them
  M_T: T,
});
})();
