// Job detail screen — funnel, candidates list, job post settings

function JobFunnel({ jobId }) {
  const stages = STAGES.filter(s => !["backburner","rejected","not_interested","declined"].includes(s.id));
  const counts = stages.map(s => jobStageCount(jobId, s.id));
  const max = Math.max(...counts, 1);
  return (
    <div className="ats-funnel">
      {stages.map((s, i) => {
        const count = counts[i];
        const prev = i > 0 ? counts[i - 1] : count;
        const conv = i > 0 && prev > 0 ? Math.round((count / prev) * 100) : null;
        return (
          <div key={s.id} className="ats-funnel__step">
            <div className="ats-funnel__step__top">
              <span className="ats-col__dot" style={{ background: s.accent }} />
              {s.label}
            </div>
            <div className="ats-funnel__step__count">{count}</div>
            <div className="ats-funnel__step__bar">
              <span style={{ width: `${(count / max) * 100}%`, background: s.accent }} />
            </div>
            <div className="ats-funnel__step__conv">
              {conv !== null ? `${conv}% from prev` : "Top of funnel"}
            </div>
          </div>
        );
      })}
    </div>
  );
}

const { useState: useStateJ } = React;

function JobDetail() {
  const job = JOBS.find(j => j.id === "se-rt"); // Staff Engineer, Real-time Systems
  const candidates = candidatesByJob(job.id);
  const active = candidates.filter(c => !["rejected","not_interested","declined","hired"].includes(c.stage));

  const [subtab, setSubtab] = useStateJ("Pipeline");
  const [layout, setLayout] = useStateJ("compact"); // "kanban" | "compact"
  const [filters, setFilters] = useStateJ({});
  const [addModalOpen, setAddModalOpen] = useStateJ(false);
  const [, showToast, ToastHost] = useAtsToast();
  const toggleFilter = (id, label) => {
    setFilters(p => {
      const n = { ...p };
      if (n[id]) { delete n[id]; showToast(`Cleared ${label}`); }
      else { n[id] = label; showToast(`Filter applied: ${label}`); }
      return n;
    });
  };
  const SUBTABS = [
    { id: "Pipeline", label: "Pipeline", count: 39 },
    { id: "Job post", label: "Job post" },
    { id: "Scorecards", label: "Scorecards" },
    { id: "Sequences", label: "Sequences" },
    { id: "Sourcing", label: "Sourcing" },
    { id: "Activity", label: "Activity" },
    { id: "Settings", label: "Settings" },
  ];

  return (
    <div className="ats-shell ats-shell--frame">
      <TopNav activeTab="Jobs" />
      <div className="ats-body">
        <JobSidebar activeJobId={job.id} onSelect={(id) => {
          if (id === job.id) return;
          const sel = JOBS.find(j => j.id === id);
          if (sel) showToast(`Open ${sel.title} from the canvas to view its job page`);
          else if (id === "__all__") showToast("All roles selected");
          else if (id === null) showToast("Open roles selected");
          else showToast("Saved view selected");
        }} />
        <main className="ats-main">
          <div className="ats-page-head">
            <div>
              <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 4 }}>
                <span className="ats-source-pill" data-src="referral" style={{ background: "rgba(227,165,78,0.18)", color: "#7A5A24" }}>P0 · priority</span>
                <span className="nl-eyebrow" style={{ margin: 0 }}>{job.dept} · open since {job.opened}</span>
              </div>
              <h1 className="ats-page-title">{job.title}</h1>
              <div className="ats-job-meta-row">
                <span>📍 <b>{job.loc}</b></span>
                <span>· {job.type}</span>
                <span>· Hiring manager: <b>{job.manager}</b></span>
                <span>· Job post: <a className="nl-link" href="#">nuancelabs.ai/careers/staff-rt</a></span>
                <span>· <b style={{ color: "var(--success)" }}>● Live</b> on LinkedIn, Otta, Wellfound</span>
              </div>
            </div>
            <div className="ats-page-actions">
              <button className="ats-btn ats-btn--ghost-bordered ats-btn--page-action" onClick={() => {
                try { navigator.clipboard && navigator.clipboard.writeText("https://nuancelabs.ai/careers/staff-rt"); } catch(e) {}
                showToast("Link copied to clipboard", { tone: "success" });
              }}>Share link</button>
              <button className="ats-btn ats-btn--primary ats-btn--page-action" onClick={() => setAddModalOpen(true)}>＋ Add candidate</button>
            </div>
          </div>

          <div className="ats-metric-row">
            <div className="ats-metric">
              <div className="ats-metric__label">Active candidates</div>
              <div className="ats-metric__value">{active.length}</div>
              <div className="ats-metric__delta is-up">+3 this week</div>
            </div>
            <div className="ats-metric">
              <div className="ats-metric__label">Days open</div>
              <div className="ats-metric__value">27<em style={{ fontSize: 14, color: "var(--fg-3)" }}>d</em></div>
              <div className="ats-metric__delta">Target: 45d</div>
            </div>
            <div className="ats-metric">
              <div className="ats-metric__label">Pass-through</div>
              <div className="ats-metric__value">62<em style={{ fontSize: 14, color: "var(--fg-3)" }}>%</em></div>
              <div className="ats-metric__delta">Sourced → Intro</div>
            </div>
            <div className="ats-metric">
              <div className="ats-metric__label">Job-post views</div>
              <div className="ats-metric__value">1,284</div>
              <div className="ats-metric__delta is-up">38 applies</div>
            </div>
            <div className="ats-metric">
              <div className="ats-metric__label">Sourcing</div>
              <div className="ats-metric__value">3</div>
              <div className="ats-metric__delta">LinkedIn searches running</div>
            </div>
          </div>

          <JobFunnel jobId={job.id} />

          <div className="ats-subtabs">
            {SUBTABS.map(t => (
              <button
                key={t.id}
                className={"ats-subtab" + (subtab === t.id ? " is-active" : "")}
                onClick={() => setSubtab(t.id)}
              >
                {t.label}
                {t.count != null && <span className="ats-subtab__count">{t.count}</span>}
              </button>
            ))}
          </div>

          {subtab === "Pipeline" && (
            <>
              <div className="ats-toolbar">
                <div className="ats-toolbar__group">
                  <button className={"ats-btn" + (filters.stage ? " is-active" : "")} onClick={() => toggleFilter("stage", "Stage")}>Stage ▾</button>
                  <button className={"ats-btn" + (filters.source ? " is-active" : "")} onClick={() => toggleFilter("source", "Source")}>Source ▾</button>
                  <button className="ats-btn" onClick={() => showToast("Pick a property to filter on — coming soon")}>+ Filter</button>
                </div>
                <div className="ats-toolbar__spacer" />
                <div className="ats-segmented">
                  <button
                    className={"ats-segmented__btn" + (layout === "kanban" ? " is-active" : "")}
                    onClick={() => setLayout("kanban")}
                  >Kanban</button>
                  <button
                    className={"ats-segmented__btn" + (layout === "compact" ? " is-active" : "")}
                    onClick={() => setLayout("compact")}
                  >Compact</button>
                </div>
              </div>

              {layout === "compact" && (
                <div className="ats-sheet" style={{ background: "var(--bg-3)" }}>
                  <table>
                    <thead>
                      <tr>
                        <th>Candidate</th>
                        <th>Stage</th>
                        <th>Source</th>
                        <th>Days</th>
                        <th>Location</th>
                        <th>Comp ask</th>
                        <th>Owner</th>
                        <th>Last activity</th>
                      </tr>
                    </thead>
                    <tbody>
                      {(() => {
                        // Spread across stages so the visible rows reflect the full pipeline,
                        // not just the first 22 sourced candidates returned by candidatesByJob.
                        const byStage = STAGES.map(s => candidates.filter(c => c.stage === s.id));
                        const interleaved = [];
                        let i = 0;
                        while (interleaved.length < 22) {
                          let added = 0;
                          for (const bucket of byStage) {
                            if (bucket[i]) { interleaved.push(bucket[i]); added++; if (interleaved.length >= 22) break; }
                          }
                          if (!added) break;
                          i++;
                        }
                        return interleaved;
                      })().map(c => {
                        const stage = STAGE_BY_ID[c.stage];
                        const isStale = c.days >= 12 && !["hired","rejected","declined","backburner"].includes(c.stage);
                        return (
                          <tr key={c.id}>
                            <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}</b>
                                  <span className="ats-sheet__company">{c.title} · {c.company}</span>
                                </div>
                              </div>
                            </td>
                            <td><StageChip stage={stage} dense /></td>
                            <td><SourcePill source={c.source} /></td>
                            <td><span className={"ats-card__days" + (isStale ? " is-stale" : "")}>{c.days}d</span></td>
                            <td style={{ color: "var(--fg-3)" }}>{c.location}</td>
                            <td style={{ color: "var(--fg-3)", fontFamily: "var(--font-mono)", fontSize: 11 }}>{c.salary}</td>
                            <td><InitialDisc initials={c.recruiterInitials} color={c.recruiterColor} size={18} title={c.recruiterName} /></td>
                            <td className="ats-card__activity" style={{ maxWidth: 180 }}>{c.lastActivity}</td>
                          </tr>
                        );
                      })}
                    </tbody>
                  </table>
                </div>
              )}

              {layout === "kanban" && (
                <JobMiniKanban candidates={candidates} />
              )}
            </>
          )}

          {subtab !== "Pipeline" && (
            <JobSubtabPlaceholder name={subtab} job={job} />
          )}
          {ToastHost}
        </main>
      </div>
      {addModalOpen && (
        <AddCandidateModal onClose={() => setAddModalOpen(false)} defaultJobId={job?.id} />
      )}
    </div>
  );
}

Object.assign(window, { JobDetail, JobFunnel });

// === Mini-kanban for Job page ===
function JobMiniKanban({ candidates }) {
  const stages = STAGES.filter(s => !["backburner","rejected","not_interested","declined"].includes(s.id));
  const byStage = Object.fromEntries(stages.map(s => [s.id, candidates.filter(c => c.stage === s.id)]));
  return (
    <div className="ats-job-kanban">
      {stages.map(s => (
        <div key={s.id} className="ats-job-col">
          <div className="ats-job-col__head">
            <span className="ats-col__dot" style={{ background: s.accent }} />
            <b>{s.label}</b>
            <span className="ats-job-col__count">{byStage[s.id].length}</span>
          </div>
          <div className="ats-job-col__body">
            {byStage[s.id].slice(0, 6).map(c => (
              <div key={c.id} className="ats-job-card">
                <Avatar src={c.avatar} name={c.name} size={18} />
                <div style={{ minWidth: 0, flex: 1 }}>
                  <div style={{ fontSize: 12, fontWeight: 500, color: "var(--nl-ink)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{c.name}</div>
                  <div style={{ fontSize: 10.5, color: "var(--fg-3)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{c.company}</div>
                </div>
              </div>
            ))}
            {byStage[s.id].length > 6 && (
              <div className="ats-job-col__more">+{byStage[s.id].length - 6} more</div>
            )}
            {byStage[s.id].length === 0 && (
              <div className="ats-job-col__empty">—</div>
            )}
          </div>
        </div>
      ))}
    </div>
  );
}

// === Placeholder for non-Pipeline subtabs ===
function JobSubtabPlaceholder({ name, job }) {
  const COPY = {
    "Job post": {
      title: "Job post",
      desc: `The public-facing posting for ${job.title}. Edit copy, requirements, and where it's syndicated.`,
      stats: [
        { k: "Views", v: "1,284" },
        { k: "Applies", v: "38" },
        { k: "Apply rate", v: "3.0%" },
      ],
    },
    Scorecards: {
      title: "Interview scorecards",
      desc: "The competency rubric every interviewer fills out for this role. Per-stage scorecards roll up into a single decision.",
      stats: [
        { k: "Active scorecards", v: "5" },
        { k: "Avg completion", v: "94%" },
        { k: "Calibration sessions", v: "2" },
      ],
    },
    Sequences: {
      title: "Outreach sequences",
      desc: "Templated outreach used by sourcers and recruiters. AI-personalized opening + 2 follow-ups.",
      stats: [
        { k: "Running", v: "3" },
        { k: "Reply rate", v: "31%" },
        { k: "Last sent", v: "12m ago" },
      ],
    },
    Sourcing: {
      title: "Sourcing searches",
      desc: "Saved LinkedIn / GitHub / arXiv searches. New matches drop into Auto-screen for AI review before reaching the pipeline.",
      stats: [
        { k: "Saved searches", v: "3" },
        { k: "Matches today", v: "27" },
        { k: "Auto-passed", v: "12" },
      ],
    },
    Activity: {
      title: "Activity feed",
      desc: "Every change to this job — stage moves, comments, scorecard submissions, offer events.",
      stats: [
        { k: "Events today", v: "18" },
        { k: "This week", v: "104" },
      ],
    },
    Settings: {
      title: "Settings",
      desc: "Who owns this role, who has access, default stages, hiring manager approval flow.",
      stats: [
        { k: "Members", v: "6" },
        { k: "Visibility", v: "Hiring team" },
      ],
    },
  };
  const c = COPY[name] || { title: name, desc: "", stats: [] };
  return (
    <div className="ats-subtab-placeholder">
      <div className="ats-subtab-placeholder__head">
        <h2>{c.title}</h2>
        <p>{c.desc}</p>
      </div>
      <div className="ats-subtab-placeholder__stats">
        {c.stats.map(s => (
          <div key={s.k} className="ats-subtab-placeholder__stat">
            <div className="ats-subtab-placeholder__k">{s.k}</div>
            <div className="ats-subtab-placeholder__v">{s.v}</div>
          </div>
        ))}
      </div>
      <div className="ats-subtab-placeholder__hint">
        <span className="ats-subtab-placeholder__dot" />
        Full <b>{c.title.toLowerCase()}</b> view — design coming next iteration
      </div>
    </div>
  );
}

Object.assign(window, { JobMiniKanban, JobSubtabPlaceholder });
