// =====================================================================
// Viewer context — drives the "View as..." access-control demo.
// The App provides a viewer (one of VIEWERS) and every screen uses
// useViewer() to filter what they show.
// =====================================================================

const ViewerContext = React.createContext(null);

function ViewerProvider({ viewer, children }) {
  return <ViewerContext.Provider value={viewer}>{children}</ViewerContext.Provider>;
}

function useViewer() {
  return React.useContext(ViewerContext) || VIEWERS[0]; // default to admin
}

// Filter a candidate list down to what the current viewer can see.
function useVisibleCandidates(list = CANDIDATES) {
  const viewer = useViewer();
  return React.useMemo(() => visibleCandidates(viewer, list), [viewer, list]);
}

// =====================================================================
// "Viewing as..." top banner — slim strip above the topnav, color-coded
// to the viewer's role. Only shows when role !== 'admin' so the default
// experience has no chrome cost.
// =====================================================================
function RoleBanner() {
  const viewer = useViewer();
  if (!viewer || viewer.role === "admin") return null;
  const role = ROLES[viewer.role];
  if (!role) return null;
  const visibleCount = visibleCandidates(viewer).length;
  const authUser = window.__atsAuthUser;
  const isSimulated = authUser && authUser.role === "admin" && viewer.role !== "admin";
  const exitSimulation = () => {
    if (typeof window.__atsSetViewer === "function" && authUser) {
      const nameParts = (authUser.full_name || "").split(" ");
      const initials = nameParts.map(p => p[0] || "").join("").slice(0, 2).toUpperCase();
      window.__atsSetViewer({
        id: authUser.id, name: authUser.full_name, initials,
        color: "#7595D5", role: "admin", title: authUser.email,
        avatar_url: authUser.avatar_url,
      });
    }
  };
  return (
    <div className="ats-role-banner" style={{ background: role.accent }}>
      <span className="ats-role-banner__dot" />
      <span className="ats-role-banner__role">{isSimulated ? "Viewing as" : ""} {role.label}</span>
      <span className="ats-role-banner__sep">·</span>
      <span className="ats-role-banner__name">{viewer.name}</span>
      <span className="ats-role-banner__spacer" />
      <span className="ats-role-banner__visibility">
        Showing <b>{visibleCount}</b> candidates · {role.desc}
      </span>
      {isSimulated && (
        <button
          onClick={exitSimulation}
          style={{
            marginLeft: 12, padding: '2px 10px', fontSize: 11, fontWeight: 600,
            background: 'rgba(255,255,255,0.2)', color: '#fff',
            border: '1px solid rgba(255,255,255,0.3)', borderRadius: 4,
            cursor: 'pointer', transition: 'background 0.15s',
          }}
          onMouseEnter={(e) => e.currentTarget.style.background = 'rgba(255,255,255,0.35)'}
          onMouseLeave={(e) => e.currentTarget.style.background = 'rgba(255,255,255,0.2)'}
        >
          Exit
        </button>
      )}
    </div>
  );
}

// =====================================================================
// "Hidden by access" placeholder — replaces a row/card when a feature
// would have been visible to admins but the current viewer is locked
// out. (Used in the Permissions screen demos.)
// =====================================================================
function AccessLock({ reason }) {
  return (
    <span className="ats-access-lock" title={reason}>
      <svg width="11" height="11" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5">
        <rect x="3" y="7" width="10" height="7" rx="1.2" />
        <path d="M5.5 7V5a2.5 2.5 0 0 1 5 0v2" strokeLinecap="round" />
      </svg>
      Hidden
    </span>
  );
}

Object.assign(window, {
  ViewerContext, ViewerProvider, useViewer, useVisibleCandidates,
  RoleBanner, AccessLock,
});
