// =====================================================================
// People & Permissions — Settings screen.
// Shows everyone with access to the ATS plus the role-capability matrix.
// =====================================================================

const { useState: useStateP } = React;

function _formatLastActive(iso) {
  if (!iso) return "";
  const d = new Date(iso);
  const now = new Date();
  const diffMs = now - d;
  const diffMin = Math.floor(diffMs / 60000);
  if (diffMin < 1) return "Just now";
  if (diffMin < 60) return diffMin + "m ago";
  const diffHr = Math.floor(diffMin / 60);
  if (diffHr < 24) return diffHr + "h ago";
  const diffDay = Math.floor(diffHr / 24);
  if (diffDay < 30) return diffDay + "d ago";
  return d.toLocaleDateString("en-US", { month: "short", day: "numeric" });
}

const ADMIN_NAMES = ["fangchang", "edward", "karren", "nicole"];

function _isAdmin(t) {
  if (t.raw_role === "admin" || t.role === "Admin") return true;
  const first = (t.name || "").split(" ")[0].toLowerCase();
  return ADMIN_NAMES.includes(first);
}

function _buildPeople() {
  const internal = TEAM.map(t => ({
    id: t.id, name: t.name, email: t.email || "", initials: t.initials, color: t.color,
    role: _isAdmin(t) ? "admin" : "interviewer",
    title: t.role, last_login: t.last_login || null,
    scopeRoles: "all", comp: true,
  }));
  const external = [{
    id: "ext-jon-luzha", name: "Jon Luzha", email: "", initials: "JL",
    color: "#9C6B4F", role: "external", title: "Alexander Chapman",
    last_login: null, scopeRoles: "ownSubs", agencyName: "Alexander Chapman",
    comp: false,
  }];
  return [...internal, ...external];
}

const CAPABILITIES = [
  { id: "see_all",        name: "See all candidates",              hint: "Across every role in the workspace",
    perms: { admin: "yes", interviewer: "yes", external: "no" },
    cellHint: { external: "Own submissions only" } },
  { id: "read_write",     name: "Read & write candidate data",     hint: "Emails, Slack, notes, scores, profiles, stage changes",
    perms: { admin: "yes", interviewer: "yes", external: "partial" },
    cellHint: { external: "Own submissions only" } },
  { id: "hired_access",   name: "Read & write Hired candidates",   hint: "View and manage candidates in the Hired stage",
    perms: { admin: "yes", interviewer: "no", external: "no" } },
  { id: "manage_users",   name: "Manage users & permissions",      hint: "Invite, change roles, remove access",
    perms: { admin: "yes", interviewer: "no", external: "no" } },
];

function PermCell({ value, hint }) {
  const ch = value === "yes" ? "✓" : value === "no" ? "—" : "◐";
  const cls = "ats-perm-cell ats-perm-cell--" + (value === "yes" ? "yes" : value === "no" ? "no" : "partial");
  return (
    <div>
      <span className={cls}>{ch}</span>
      {hint && <div className="ats-perm-cell__hint">{hint}</div>}
    </div>
  );
}

function RolePill({ role }) {
  const r = ROLES[role];
  return (
    <span className="ats-role-pill" data-role={role}>
      <span className="ats-role-pill__dot" style={{ background: r.accent }} />
      {r.label}
    </span>
  );
}

// Short-form role title for compact scope chips
function shortRoleTitle(t) {
  return t
    .replace("Research Scientist, Multimodal", "Research Sci · Multimodal")
    .replace("Staff Engineer, Real-time Systems", "Staff Eng · Real-time")
    .replace("ML Infrastructure Engineer", "ML Infra")
    .replace("Perception & Computer Vision", "Perception & CV")
    .replace("Senior Product Designer", "Sr Product Designer")
    .replace("Founding Frontend Engineer", "Founding FE");
}

function ScopeCell({ p }) {
  const jobs = p.scopeRoles;
  return (
    <div className="ats-perms__scope">
      {jobs === "all" ? (
        <span className="ats-perms__scope-all">
          <span className="ats-perms__scope-all-dot" />
          All roles <span style={{ color: "var(--fg-4)", fontWeight: 400 }}>· {JOBS.filter(j => j.status === "open" || j.status === "active").length} open</span>
        </span>
      ) : jobs === "ownSubs" ? (
        <div>
          <span className="ats-perms__scope-agency">{p.agencyName}</span>
          <span className="ats-perms__scope-note">their submissions only</span>
        </div>
      ) : (
        <div className="ats-perms__scope-chips">
          {jobs.map(j => (
            <span key={j} className="ats-perms__scope-chip" title={j}>{shortRoleTitle(j)}</span>
          ))}
          {p.panelOnly && <span className="ats-perms__scope-note">· panel only</span>}
        </div>
      )}
    </div>
  );
}

function PermissionsScreen() {
  const allPeople = _buildPeople();
  const [, showToast, ToastHost] = useAtsToast();
  const [rowMenu, setRowMenu] = useState(null); // email of row with open menu
  // Listen for page changes to update active tab
  const [currentPage, setCurrentPage] = React.useState(
    typeof window.__atsCurrentPage === 'string' ? window.__atsCurrentPage : 'settings'
  );

  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" style={{ height: "100%" }}>
      <RoleBanner />
      <TopNav activeTab={activeTabMap[currentPage] || "Permissions"} />
      <div className="ats-body">
        <JobSidebar activeJobId={null} onSelect={(id) => {
          const job = JOBS.find(j => j.id === id);
          if (job) showToast(`${job.title} — open the Pipeline artboard to view candidates`);
          else if (id === "__all__") showToast("All roles selected");
          else if (id === null) showToast("Showing open roles");
          else showToast("Saved view selected");
        }} />
        <main className="ats-main">
          <div className="ats-perms">
            <div className="ats-perms__head">
              <h1 className="ats-perms__title">People & permissions</h1>
              <p className="ats-perms__sub">
                Who has access to your hiring data, what they can see, and what they can do.
                External agents only see candidates they personally submitted.
              </p>
            </div>

            {/* People */}
            <div className="ats-perms__section">
              <div className="ats-perms__section-head">
                <h2 className="ats-perms__section-title">People with access</h2>
                <span className="ats-perms__section-sub">{allPeople.length} accounts</span>
                <div className="ats-perms__section-spacer" />
                <button className="ats-btn ats-btn--ghost-bordered ats-btn--page-action" onClick={() => showToast("Invite teammate — form coming soon", { tone: "success" })}>Invite teammate</button>
                <button className="ats-btn ats-btn--primary ats-btn--page-action" onClick={() => showToast("Add agency recruiter — form coming soon", { tone: "success" })}>+ Add agency recruiter</button>
              </div>
              <div className="ats-perms__people">
                <table>
                  <thead>
                    <tr>
                      <th style={{ width: "26%" }}>Person</th>
                      <th style={{ width: 130 }}>Role</th>
                      <th>Scope</th>
                      <th style={{ width: 110 }}>Last active</th>
                      <th style={{ width: 50 }}></th>
                    </tr>
                  </thead>
                  <tbody>
                    {allPeople.map(p => (
                      <tr key={p.id}>
                        <td>
                          <div className="ats-perms__person">
                            <Avatar name={p.name} size={28} />
                            <div>
                              <div className="ats-perms__person-name">{p.name}</div>
                              <div className="ats-perms__person-email">{p.email}</div>
                            </div>
                          </div>
                        </td>
                        <td><RolePill role={p.role} /></td>
                        <td><ScopeCell p={p} /></td>
                        <td style={{ color: "var(--fg-3)", fontSize: 11.5 }}>{p.last_login ? _formatLastActive(p.last_login) : ""}</td>
                        <td style={{ position: "relative" }}>
                          <button className="ats-btn" style={{ fontSize: 11.5 }} onClick={(e) => { e.stopPropagation(); setRowMenu(rowMenu === p.id ? null : p.id); }}>⋯</button>
                          {rowMenu === p.id && (
                            <>
                              <div onClick={() => setRowMenu(null)} style={{ position: "fixed", inset: 0, zIndex: 40 }} />
                              <div className="ats-stage-menu" style={{ position: "absolute", right: 0, top: "100%", zIndex: 41, minWidth: 180 }}>
                                <button className="ats-stage-menu__item" onClick={() => { setRowMenu(null); showToast(`Changed role for ${p.name}`); }}>Change role…</button>
                                <button className="ats-stage-menu__item" onClick={() => { setRowMenu(null); showToast(`Scope edited for ${p.name}`); }}>Edit scope…</button>
                                <button className="ats-stage-menu__item" onClick={() => { setRowMenu(null); showToast(`Password reset sent to ${p.email}`, { tone: "success" }); }}>Send password reset</button>
                                <div className="ats-stage-menu__divider" />
                                <button className="ats-stage-menu__item ats-stage-menu__item--danger" onClick={() => { setRowMenu(null); showToast(`Access removed for ${p.name}`, { tone: "warn" }); }}>Remove access</button>
                              </div>
                            </>
                          )}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>

            {/* Matrix */}
            <div className="ats-perms__section">
              <div className="ats-perms__section-head">
                <h2 className="ats-perms__section-title">Permissions matrix</h2>
                <span className="ats-perms__section-sub">What each role can see and do</span>
              </div>
              <div className="ats-perms__matrix">
                <table>
                  <thead>
                    <tr>
                      <th>Capability</th>
                      <th className="is-role">Admin</th>
                      <th className="is-role">Interviewer</th>
                      <th className="is-role">External Agent</th>
                    </tr>
                  </thead>
                  <tbody>
                    {CAPABILITIES.map(cap => (
                      <tr key={cap.id}>
                        <td className="is-cap-name">
                          {cap.name}
                          {cap.hint && <div className="ats-perms__cap-hint">{cap.hint}</div>}
                        </td>
                        {["admin","interviewer","external"].map(r => (
                          <td key={r} className="is-role">
                            <PermCell value={cap.perms[r]} hint={cap.cellHint?.[r]} />
                          </td>
                        ))}
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          </div>
          {ToastHost}
        </main>
      </div>
    </div>
  );
}

Object.assign(window, { PermissionsScreen });
