// =====================================================================
// "My candidates" screen — every candidate the current user is involved in.
// Three buckets: Owner · Referred by me · On the interview panel.
// Notion-style view tabs (Board / Table), filtered by bucket via a left rail.
// =====================================================================

const { useState: useStateMC, useMemo: useMemoMC } = React;

// Current user (demo). Matches the avatar in the topnav.
const ME = { id: "fm", name: "Fangchang Ma", initials: "FM", color: "#7595D5", refLabel: "Fangchang M." };

// Deterministic hash so "on panel" is stable across renders.
function hashStr(s) {
  let h = 0;
  for (let i = 0; i < s.length; i++) h = ((h << 5) - h + s.charCodeAt(i)) | 0;
  return Math.abs(h);
}

// Build my candidate rows (with `why` and `detail` annotations) from the global CANDIDATES list.
function useMyRows(viewer) {
  return useMemoMC(() => {
    const visible = visibleCandidates(viewer, CANDIDATES);
    const rows = [];
    for (const c of visible) {
      // Owner = the viewer is the recruiter for this candidate
      if (c.recruiter === viewer.id || c.submittedById === viewer.id) {
        rows.push({ c, why: "owner", detail: null, key: "o-" + c.id });
      }
      // Referred-by-me: only shows for ME's reference label
      if (c.referredBy === ME.refLabel && viewer.id === ME.id) {
        rows.push({ c, why: "referred", detail: null, key: "r-" + c.id });
      }
      // On panel = viewer is in the candidate's panelMembers list
      if ((c.panelMembers || []).includes(viewer.id) && c.recruiter !== viewer.id) {
        const myRound = panelRoundFor(c);
        rows.push({ c, why: "panel", detail: myRound.label, round: myRound, key: "p-" + c.id });
      }
    }
    const stageOrder = STAGES.map(s => s.id);
    rows.sort((a, b) => {
      const sa = stageOrder.indexOf(a.c.stage), sb = stageOrder.indexOf(b.c.stage);
      if (sa !== sb) return sa - sb;
      return b.c.days - a.c.days;
    });
    return rows;
  }, [viewer]);
}

function panelRoundFor(c) {
  switch (c.stage) {
    case "intro":      return { label: "Intro · Mon",      round: "Intro" };
    case "tech1":      return { label: "Tech 1 · Wed",     round: "Tech 1" };
    case "tech2":      return { label: "Tech 2 · scored",  round: "Tech 2", scored: true };
    case "tech3":      return { label: "Tech 3 · Thu",     round: "Tech 3" };
    case "onsite":     return { label: "Onsite · System design", round: "Onsite" };
    case "offer":      return { label: "Onsite · scored",  round: "Onsite", scored: true };
    case "hired":      return { label: "Onsite · scored",  round: "Onsite", scored: true };
    default:           return { label: "Up next",          round: "Panel" };
  }
}

// Map why → color tokens used for stripes/dots/pills
const WHY_META = {
  owner:    { label: "Owner",    color: "#6B8E76", bg: "rgba(150,177,173,0.20)", border: "rgba(107,142,118,0.35)", fg: "#3F5E45" },
  referred: { label: "Referred", color: "#C9923D", bg: "rgba(227,165,78,0.18)",  border: "rgba(227,165,78,0.40)",  fg: "#8A5418" },
  panel:    { label: "On panel", color: "#7595D5", bg: "rgba(117,149,213,0.18)", border: "rgba(117,149,213,0.40)", fg: "#3A588A" },
};

// --- Filter rail ---
function MyRail({ filter, setFilter, counts }) {
  const items = [
    { id: "all",       label: "All my candidates", count: counts.all,       hint: "Anyone I touch" },
    { id: "owner",     label: "Owner",             count: counts.owner,     hint: "I run the process" },
    { id: "referred",  label: "Referred by me",    count: counts.referred,  hint: "I sent them in" },
    { id: "panel",     label: "On the panel",      count: counts.panel,     hint: "I run an interview" },
  ];
  return (
    <aside className="ats-myc-rail">
      <div className="ats-myc-rail__head">
        <Avatar name={ME.name} size={36} ring />
        <div>
          <div className="ats-myc-rail__name">{ME.name}</div>
          <div className="ats-myc-rail__role">CEO · Nuance Labs</div>
        </div>
      </div>
      <nav className="ats-myc-rail__nav">
        {items.map(it => (
          <button
            key={it.id}
            className={"ats-myc-rail__item" + (filter === it.id ? " is-active" : "")}
            onClick={() => setFilter(it.id)}
          >
            <span className="ats-myc-rail__label">{it.label}</span>
            <span className="ats-myc-rail__count">{it.count}</span>
            <span className="ats-myc-rail__hint">{it.hint}</span>
          </button>
        ))}
      </nav>

      <div className="ats-myc-rail__footer">
        <div className="nl-eyebrow">Saved views</div>
        <button className="ats-myc-rail__saved">Stalled with me &gt; 7d <span>3</span></button>
        <button className="ats-myc-rail__saved">Awaiting my score <span>2</span></button>
        <button className="ats-myc-rail__saved">Offer pending response <span>1</span></button>
      </div>
    </aside>
  );
}

// "Why am I here?" pill (used in table)
function WhyPill({ kind, detail }) {
  const m = WHY_META[kind];
  return (
    <span
      className="ats-myc-why"
      style={{ color: m.fg, background: m.bg, borderColor: m.border }}
    >
      <span className="ats-myc-why__dot" />
      {m.label}
      {detail && <span className="ats-myc-why__detail"> · {detail}</span>}
    </span>
  );
}

// Small dot used on kanban cards to indicate the "why"
function WhyDot({ kind, detail }) {
  const m = WHY_META[kind];
  return (
    <span className="ats-myc-card-why" title={detail ? `${m.label} · ${detail}` : m.label}>
      <span className="ats-myc-card-why__stripe" style={{ background: m.color }} />
      <span className="ats-myc-card-why__label" style={{ color: m.fg }}>{m.label}</span>
      {detail && <span className="ats-myc-card-why__detail"> · {detail}</span>}
    </span>
  );
}

// Kanban card variant — uses the SAME .ats-card markup as the main pipeline,
// with a small "why" stripe along the left edge.
function MyKanbanCard({ row }) {
  const { c, why, detail } = row;
  const m = WHY_META[why];
  const isStale = c.days >= 12 && !["hired","rejected","not_interested","declined","backburner"].includes(c.stage);
  return (
    <div
      className={
        "ats-card ats-card--xdense" +
        (c.flagged ? " is-flagged" : "") +
        (c.starred ? " is-starred" : "")
      }
      style={{ position: "relative" }}
      title={detail ? `${m.label} · ${detail}` : m.label}
    >
      <span
        aria-hidden="true"
        style={{
          position: "absolute", left: 0, top: 0, bottom: 0, width: 3,
          background: m.color, borderTopLeftRadius: 6, borderBottomLeftRadius: 6,
        }}
      />
      <div className="ats-card__row">
        <Avatar src={c.avatar} name={c.name} size={18} />
        <span className="ats-card__name">{c.name}</span>
        {c.duplicateIds && c.duplicateIds.length > 0 && (
          <span className="ats-card__dup" title={`${c.duplicateIds.length} duplicate profile${c.duplicateIds.length > 1 ? "s" : ""} found`}>
            <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
              <path d="M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z"/>
              <line x1="12" y1="9" x2="12" y2="13"/>
              <line x1="12" y1="17" x2="12.01" y2="17"/>
            </svg>
          </span>
        )}
        {c.starred && <span className="ats-card__star">★</span>}
        <span style={{ flex: 1 }} />
        <span style={{
          fontSize: 10, fontWeight: 500, color: m.fg,
          padding: "1px 5px", borderRadius: 3, background: m.bg,
          letterSpacing: "0.02em",
        }}>{m.label}{detail ? ` · ${detail}` : ""}</span>
      </div>
      <div className="ats-card__row">
        <span className="ats-card__title">
          <b>{c.title.replace("Senior ","Sr ").replace("Research Scientist","Research Sci")}</b>
          <span style={{ color: "var(--fg-4)" }}> · </span>
          {c.company}
        </span>
      </div>
      <div className="ats-card__meta">
        <SourcePill source={c.source} />
        {c.duplicateIds && c.duplicateIds.length > 0 && <span className="ats-source-pill" data-src="duplicate">Duplicate</span>}
        <span className={"ats-card__days" + (isStale ? " is-stale" : "")}>{c.days}d</span>
        <span style={{ flex: 1 }} />
        <InitialDisc
          initials={c.recruiterInitials}
          color={c.recruiterColor}
          size={14}
          title={c.recruiterName}
        />
      </div>
    </div>
  );
}

// Kanban column — uses the SAME .ats-col classes as the main pipeline,
// minus drag/drop (this is a read-only "my view").
function MyKanbanColumn({ stage, rows }) {
  const isTerminal = ["rejected","declined","hired","backburner"].includes(stage.id);
  return (
    <div className={"ats-col" + (isTerminal ? " ats-col--terminal" : "")}>
      <div className="ats-col__head">
        <div className="ats-col__title-line">
          <span className="ats-col__dot" style={{ background: stage.accent }} />
          <span className="ats-col__title">{stage.label}</span>
          <span className="ats-col__count">{rows.length}</span>
        </div>
      </div>
      <div className="ats-col__body">
        {rows.length === 0 ? (
          <div className="ats-empty-hint">Nothing here yet</div>
        ) : rows.map(r => <MyKanbanCard key={r.key} row={r} />)}
      </div>
    </div>
  );
}

// Board: kanban grouped by stage
function MyBoardView({ rows }) {
  return (
    <div className="ats-kanban">
      {STAGES.map(s => (
        <MyKanbanColumn
          key={s.id}
          stage={s}
          rows={rows.filter(r => r.c.stage === s.id)}
        />
      ))}
    </div>
  );
}

// Table row — uses the SAME .ats-sheet markup as the main pipeline table.
function MyCandidateRow({ row }) {
  const { c, why, detail } = row;
  const stage = STAGE_BY_ID[c.stage];
  const isStale = c.days >= 12 && !["hired","rejected","not_interested","declined","backburner"].includes(c.stage);
  const job = JOBS.find(j => j.id === c.jobId);
  return (
    <tr>
      <td>
        <div className="ats-sheet__name">
          <Avatar src={c.avatar} name={c.name} size={20} />
          <div style={{ display: "flex", flexDirection: "column", lineHeight: 1.2 }}>
            <b>{c.name} {c.starred && <span style={{ color: "var(--nl-amber)" }}>★</span>}</b>
            <span className="ats-sheet__company">{c.title} · {c.company}</span>
          </div>
        </div>
      </td>
      <td><WhyPill kind={why} detail={detail} /></td>
      <td><StageChip stage={stage} dense /></td>
      <td style={{ color: "var(--fg-2)" }}>{job ? job.title.replace("Real-time Systems", "RT Systems") : "—"}</td>
      <td><span className={"ats-card__days" + (isStale ? " is-stale" : "")}>{c.days}d</span></td>
      <td className="ats-card__activity" style={{ maxWidth: 220 }}>{c.lastActivity}</td>
    </tr>
  );
}

function MyCandidatesTable({ rows }) {
  return (
    <div className="ats-sheet">
      <table>
        <thead>
          <tr>
            <th style={{ width: "26%" }}>Candidate</th>
            <th style={{ width: 150 }}>Why I'm here</th>
            <th style={{ width: 120 }}>Stage</th>
            <th>Role</th>
            <th style={{ width: 60 }}>Days</th>
            <th>Last activity</th>
          </tr>
        </thead>
        <tbody>
          {rows.map(r => <MyCandidateRow key={r.key} row={r} />)}
        </tbody>
      </table>
    </div>
  );
}

// Bucket header inside All-table view
function BucketHeader({ icon, title, count, hint }) {
  return (
    <div className="ats-myc-bucket">
      <span className="ats-myc-bucket__icon">{icon}</span>
      <div>
        <div className="ats-myc-bucket__title">{title}</div>
        <div className="ats-myc-bucket__hint">{hint}</div>
      </div>
      <span className="ats-myc-bucket__count">{count}</span>
    </div>
  );
}

// Grouped table view (used when filter === "all" + view === "table"):
// shows three sections, each preceded by a bucket header.
function MyGroupedTableView({ rows, counts }) {
  const owner    = rows.filter(r => r.why === "owner");
  const referred = rows.filter(r => r.why === "referred");
  const panel    = rows.filter(r => r.why === "panel");
  return (
    <>
      {owner.length > 0 && (
        <>
          <BucketHeader
            icon={<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="8" r="4"/><path d="M4 21c0-4.4 3.6-8 8-8s8 3.6 8 8"/></svg>}
            title="I own these"
            count={counts.owner}
            hint="My pipeline · I drive the process"
          />
          <MyCandidatesTable rows={owner} />
        </>
      )}
      {referred.length > 0 && (
        <>
          <BucketHeader
            icon={<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M4 12v7a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-7"/><path d="M16 6l-4-4-4 4"/><path d="M12 2v14"/></svg>}
            title="Referrals I sent in"
            count={counts.referred}
            hint="People I vouched for · check in on momentum"
          />
          <MyCandidatesTable rows={referred} />
        </>
      )}
      {panel.length > 0 && (
        <>
          <BucketHeader
            icon={<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><circle cx="9" cy="9" r="3"/><path d="M3 21c0-3.3 2.7-6 6-6s6 2.7 6 6"/><circle cx="17" cy="8" r="2.5"/><path d="M14 21c0-2.5 1.6-4.5 4-5"/></svg>}
            title="On the panel"
            count={counts.panel}
            hint="I'm running an interview round · score before they advance"
          />
          <MyCandidatesTable rows={panel} />
        </>
      )}
    </>
  );
}

// Top "My week" KPI strip
function MyWeekStrip({ counts }) {
  const items = [
    { label: "Awaiting my score",   value: 2,                 hint: "Tech-2 panels · score by Fri" },
    { label: "Need my decision",    value: 1,                 hint: "Edward Z. · offer ask" },
    { label: "Interviews this week",value: 4,                 hint: "Mon · Tue · Thu · Fri" },
    { label: "Referrals in flight", value: counts.referred,   hint: "across active stages" },
  ];
  return (
    <div className="ats-myc-week">
      {items.map((i, idx) => (
        <div key={idx} className="ats-myc-week__cell">
          <div className="ats-myc-week__value">{i.value}</div>
          <div className="ats-myc-week__label">{i.label}</div>
          <div className="ats-myc-week__hint">{i.hint}</div>
        </div>
      ))}
    </div>
  );
}

// Notion-style view tabs (Board / Table)
const BoardIcon = () => (
  <svg width="11" height="11" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.4" style={{ display: "block" }}>
    <rect x="2" y="3" width="3.5" height="10" rx="0.5"/>
    <rect x="6.25" y="3" width="3.5" height="7" rx="0.5"/>
    <rect x="10.5" y="3" width="3.5" height="5" rx="0.5"/>
  </svg>
);
const TableIcon = () => (
  <svg width="11" height="11" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.4" style={{ display: "block" }}>
    <rect x="2" y="3" width="12" height="10" rx="1"/>
    <path d="M2 6.5h12M2 9.5h12M6 3v10"/>
  </svg>
);

function MyViewTabs({ activeId, onSelect, onAction }) {
  const VIEWS = [
    { id: "board", label: "Board view", icon: <BoardIcon />, desc: "Kanban grouped by stage" },
    { id: "table", label: "Table view", icon: <TableIcon />, desc: "Grouped by bucket" },
  ];
  return (
    <div className="ats-view-tabs">
      {VIEWS.map(v => (
        <button
          key={v.id}
          className={"ats-view-tab" + (activeId === v.id ? " is-active" : "")}
          onClick={() => onSelect(v.id)}
          title={v.desc}
        >
          <span className="ats-view-tab__icon">{v.icon}</span>
          {v.label}
        </button>
      ))}
      <div className="ats-view-tabs__spacer" />
      <button className="ats-view-tabs__menu" onClick={() => onAction && onAction("Filter panel — coming soon")}>Filter</button>
      <button className="ats-view-tabs__menu" onClick={() => onAction && onAction("Sort panel — coming soon")}>Sort</button>
      <button className="ats-view-tabs__menu" onClick={() => onAction && onAction("Group panel — coming soon")}>Group</button>
      <button className="ats-view-tabs__menu" onClick={() => onAction && onAction("More options — coming soon")}>⋯</button>
    </div>
  );
}

// --- Main screen ---
function MyCandidatesScreen() {
  const viewer = useViewer();
  const [filter, setFilter] = useStateMC("all");
  const [view, setView] = useStateMC("board");
  const [, showToast, ToastHost] = useAtsToast();
  const allRows = useMyRows(viewer);

  const counts = {
    all: allRows.length,
    owner:    allRows.filter(r => r.why === "owner").length,
    referred: allRows.filter(r => r.why === "referred").length,
    panel:    allRows.filter(r => r.why === "panel").length,
  };

  const visibleRows = filter === "all" ? allRows : allRows.filter(r => r.why === filter);

  // Listen for page changes to update active tab
  const [currentPage, setCurrentPage] = React.useState(
    typeof window.__atsCurrentPage === 'string' ? window.__atsCurrentPage : 'my-candidates'
  );

  React.useEffect(() => {
    const handlePageChange = (e) => setCurrentPage(e.detail);
    window.addEventListener('ats-page-change', handlePageChange);
    return () => window.removeEventListener('ats-page-change', handlePageChange);
  }, []);

  const activeTabMap = {
    'pipeline': 'Pipeline',
    'my-candidates': 'My candidates',
    'settings': 'Permissions'
  };

  return (
    <div className="ats-shell ats-shell--frame">
      <RoleBanner />
      <TopNav activeTab={activeTabMap[currentPage] || "My candidates"} />
      <div className="ats-body">
        <MyRail filter={filter} setFilter={setFilter} counts={counts} />
        <main className="ats-main ats-myc-main">
          <div className="ats-myc-header">
            <div>
              <h1 className="ats-page-title">My candidates</h1>
              <p className="ats-myc-sub">
                Everyone you've put your name on — as the owner, the referrer, or someone running an interview.
                Triage what's blocked on you.
              </p>
            </div>
            <div className="ats-myc-controls">
              <button className="ats-btn ats-btn--primary" onClick={() => showToast("Refer someone — form coming soon", { tone: "success" })}>+ Refer someone</button>
            </div>
          </div>

          <MyWeekStrip counts={counts} />

          <MyViewTabs activeId={view} onSelect={setView} onAction={showToast} />

          {view === "board" && <MyBoardView rows={visibleRows} />}
          {view === "table" && (
            filter === "all"
              ? <MyGroupedTableView rows={visibleRows} counts={counts} />
              : <MyCandidatesTable rows={visibleRows} />
          )}

          {visibleRows.length === 0 && (
            <div className="ats-myc-empty">
              <b>Nothing here yet.</b>
              <span>You're not currently {filter === "owner" ? "owning" : filter === "referred" ? "referring" : "on a panel for"} any candidate.</span>
            </div>
          )}
          {ToastHost}
        </main>
      </div>
    </div>
  );
}

Object.assign(window, { MyCandidatesScreen });
