"use client";

import { useEffect, useMemo, useState } from "react";
import { apiGet, apiPatch, apiPost, apiPut } from "@/lib/api";
import type { AuthSessionChallengeState, AuthWorkflowStatus, CustomDomainGovernanceQueuePlan, CustomDomainReadinessPlan, EmailTwoFactorPolicy, EmailTwoFactorRevocationState, LoginChallengeAuditEvent, NotificationPreferences, NotificationReadiness, NotificationSenderPreviewTool, OutboundEmailLog, SenderPolicyHelpArticle, SuperAdminNotificationGovernance, User, VerifiedCustomDomainRequestRecord, VerifiedCustomDomainRequestStatus, WorkAssignmentQueueItem, WorkAssignmentQueueSummary } from "@/types";
import { AssignmentQueueCard } from "@/components/dispatch/assignment-queue-card";

const DEFAULT_PREFS: NotificationPreferences = {
  inApp: true,
  emailDueToday: true,
  emailOverdue: true,
  emailUrgent: true,
  teamDigest: false,
  smsReserved: false,
};



type FollowUpHint = {
  key: string;
  label: string;
  status: "FRESH" | "WATCH" | "URGENT";
  body: string;
};

type RecoveryPrompt = {
  key: string;
  label: string;
  status: "READY" | "REVIEW" | "HOLD";
  body: string;
};

type ConsistencyCheck = {
  key: string;
  label: string;
  status: "CONSISTENT" | "WATCH" | "CONFLICT";
  body: string;
};

type ClosureGuidance = {
  key: string;
  label: string;
  status: "READY" | "WATCH" | "HOLD";
  body: string;
};

function diffInDays(dateText?: string | null) {
  if (!dateText) return null;
  const value = new Date(dateText).getTime();
  if (Number.isNaN(value)) return null;
  return Math.max(0, Math.floor((Date.now() - value) / (1000 * 60 * 60 * 24)));
}

function buildFollowUpHints(request: VerifiedCustomDomainRequestRecord): FollowUpHint[] {
  const daysSinceReview = diffInDays(request.reviewedAt);
  const daysSinceSubmitted = diffInDays(request.submittedAt) ?? 0;
  const ageSource = daysSinceReview ?? daysSinceSubmitted;
  const ageStatus: FollowUpHint["status"] = ageSource >= 14 ? "URGENT" : ageSource >= 7 ? "WATCH" : "FRESH";
  const pausedStatus: FollowUpHint["status"] = request.status === "PAUSED" ? (daysSinceSubmitted >= 7 ? "URGENT" : "WATCH") : "FRESH";
  const unassignedStatus: FollowUpHint["status"] = request.reviewedByUserId ? "FRESH" : (daysSinceSubmitted >= 3 ? "URGENT" : "WATCH");
  return [
    {
      key: `${request.id}-review-movement`,
      label: 'Days since latest reviewer movement',
      status: ageStatus,
      body: daysSinceReview != null ? `${daysSinceReview} day${daysSinceReview === 1 ? '' : 's'} since the latest recorded reviewer movement on this request.` : 'No reviewer movement is recorded yet. The submission timeline is being used as the fallback follow-up anchor.',
    },
    {
      key: `${request.id}-submission-age`,
      label: 'Days since submission when no review movement exists',
      status: daysSinceReview == null ? ageStatus : 'FRESH',
      body: `${daysSinceSubmitted} day${daysSinceSubmitted === 1 ? '' : 's'} since the request was submitted into the governance queue.`,
    },
    {
      key: `${request.id}-paused-follow-up`,
      label: 'Paused-request follow-up timing',
      status: pausedStatus,
      body: request.status === 'PAUSED' ? 'This request is paused and should be checked for readiness, requester updates, or closure guidance before it ages further.' : 'This request is not currently paused, so paused-request follow-up pressure is clear for now.',
    },
    {
      key: `${request.id}-unassigned-follow-up`,
      label: 'Unassigned-request follow-up timing',
      status: unassignedStatus,
      body: request.reviewedByUserId ? 'A Super Admin reviewer is already attached to this request.' : 'No reviewer is visible on this request yet. Governance follow-up should confirm ownership before the request ages further.',
    },
  ];
}

function buildRecoveryPrompts(request: VerifiedCustomDomainRequestRecord): RecoveryPrompt[] {
  const hasReviewer = Boolean(request.reviewedByUserId);
  const prompts: RecoveryPrompt[] = [
    {
      key: `${request.id}-ownership-recovery`,
      label: 'Reviewer ownership recovery',
      status: hasReviewer ? 'READY' : 'HOLD',
      body: hasReviewer ? 'Reviewer ownership is visible, so follow-up can stay with the current governance owner.' : 'Assign or confirm reviewer ownership so this request does not remain in an unowned review state.',
    },
  ];
  if (request.status === 'SUBMITTED') {
    prompts.push({ key: `${request.id}-submitted-recovery`, label: 'Submitted-request recovery path', status: 'REVIEW', body: 'Move the request into review when the justification, ownership contact, and reply-handling notes are strong enough to start governance evaluation.' });
  }
  if (request.status === 'IN_REVIEW') {
    prompts.push({ key: `${request.id}-in-review-recovery`, label: 'In-review recovery path', status: 'READY', body: 'Use review notes and the readiness sections to either qualify, pause, reject, or continue review without letting the request stagnate.' });
  }
  if (request.status === 'QUALIFIED') {
    prompts.push({ key: `${request.id}-qualified-recovery`, label: 'Qualified-request recovery path', status: 'REVIEW', body: 'Qualified requests should move into explicit approval or hold guidance so they do not linger without a governance decision.' });
  }
  if (request.status === 'PAUSED') {
    prompts.push({ key: `${request.id}-paused-recovery`, label: 'Paused-request recovery path', status: 'HOLD', body: 'Paused requests should get a clear restart, follow-up, or closure decision once blocker notes and requester updates are reviewed.' });
  }
  if (request.status === 'APPROVED') {
    prompts.push({ key: `${request.id}-approved-recovery`, label: 'Approved-but-held recovery path', status: 'READY', body: 'Approval is already recorded. Keep the request in governed hold until later DNS verification and sender-activation controls are actually implemented.' });
  }
  return prompts;
}

function buildDecisionConsistencyChecks(request: VerifiedCustomDomainRequestRecord): ConsistencyCheck[] {
  const checks: ConsistencyCheck[] = [];
  const hasReviewNotes = Boolean(request.reviewNotes?.trim());
  const hasReviewer = Boolean(request.reviewedByUserId || request.reviewedByName);
  const hasApprovalInputs = Boolean(request.businessJustification?.trim() && request.dnsOwnerContact?.trim() && request.replyHandlingPlan?.trim());

  checks.push({
    key: `${request.id}-review-note-consistency`,
    label: 'Review-note consistency',
    status: hasReviewNotes ? 'CONSISTENT' : request.status === 'SUBMITTED' ? 'WATCH' : 'CONFLICT',
    body: hasReviewNotes ? 'Review notes are present to support the current governance state.' : 'Add or confirm review notes so the current decision state is easier to audit and defend later.',
  });

  checks.push({
    key: `${request.id}-reviewer-state-consistency`,
    label: 'Reviewer-state consistency',
    status: hasReviewer ? 'CONSISTENT' : request.status === 'SUBMITTED' ? 'WATCH' : 'CONFLICT',
    body: hasReviewer ? 'A reviewer is visible on this request, which supports ownership continuity.' : 'Reviewer ownership is not visible for this state. Confirm governance ownership before progressing or closing the request.',
  });

  checks.push({
    key: `${request.id}-approval-input-consistency`,
    label: 'Approval-input consistency',
    status: hasApprovalInputs ? 'CONSISTENT' : request.status === 'APPROVED' || request.status === 'QUALIFIED' ? 'CONFLICT' : 'WATCH',
    body: hasApprovalInputs ? 'Business, DNS contact, and reply-handling inputs are all present.' : 'Core approval inputs are incomplete. Avoid treating this request as approval-ready until the missing governance inputs are filled in.',
  });

  return checks;
}

function buildClosureGuidance(request: VerifiedCustomDomainRequestRecord): ClosureGuidance[] {
  const guidance: ClosureGuidance[] = [];
  const hasReviewNotes = Boolean(request.reviewNotes?.trim());
  const hasReviewer = Boolean(request.reviewedByUserId || request.reviewedByName);

  guidance.push({
    key: `${request.id}-closure-audit`,
    label: 'Closure audit guidance',
    status: hasReviewNotes ? 'READY' : 'WATCH',
    body: hasReviewNotes ? 'Review notes are present, so closure or hold messaging has a recorded governance basis.' : 'Add closure-oriented notes so later reviewers can understand why the request should pause, reject, or remain held.',
  });

  guidance.push({
    key: `${request.id}-closure-ownership`,
    label: 'Closure ownership guidance',
    status: hasReviewer ? 'READY' : 'HOLD',
    body: hasReviewer ? 'Reviewer ownership is visible, so the request has a clear governance owner for closure follow-through.' : 'Assign or confirm a reviewer before treating the request as closed, paused, or fully handed off.',
  });

  guidance.push({
    key: `${request.id}-closure-state`,
    label: 'Governance closure state guidance',
    status: request.status in {"REJECTED":1, "PAUSED":1, "APPROVED":1} ? 'READY' : request.status === 'QUALIFIED' ? 'WATCH' : 'HOLD',
    body: request.status === 'REJECTED'
      ? 'This request is already rejected. Keep the record visible for audit continuity and future resubmission context.'
      : request.status === 'PAUSED'
        ? 'This request is paused. Use closure notes to explain the blocker and the path to restart or retire the request later.'
        : request.status === 'APPROVED'
          ? 'This request is approved but still governed by activation hold. Treat approval as an intermediate governance state, not final technical activation.'
          : request.status === 'QUALIFIED'
            ? 'This request is qualified but not yet resolved. Confirm whether the next move is approval, pause, or rejection to avoid drift.'
            : 'This request is still active in the queue. A final governance closure state should not be implied yet.',
  });

  return guidance;
}

function summaryTile(label: string, value: number, tone = "bg-slate-50") {
  return (
    <div className={`rounded-2xl border ${tone} px-4 py-4`}>
      <div className="text-xs font-semibold uppercase tracking-wide text-slate-500">{label}</div>
      <div className="mt-1 text-2xl font-semibold text-slate-900">{value}</div>
    </div>
  );
}

export function NotificationCenterClient() {
  const [user, setUser] = useState<User | null>(null);
  const [prefs, setPrefs] = useState<NotificationPreferences>(DEFAULT_PREFS);
  const [readiness, setReadiness] = useState<NotificationReadiness | null>(null);
  const [prefsSaving, setPrefsSaving] = useState(false);
  const [prefsMessage, setPrefsMessage] = useState<string | null>(null);
  const [authWorkflows, setAuthWorkflows] = useState<AuthWorkflowStatus | null>(null);
  const [recentLogs, setRecentLogs] = useState<OutboundEmailLog[]>([]);
  const [emailActionMessage, setEmailActionMessage] = useState<string | null>(null);
  const [emailActionLoading, setEmailActionLoading] = useState(false);
  const [senderPreviews, setSenderPreviews] = useState<NotificationSenderPreviewTool[]>([]);
  const [customDomainPlan, setCustomDomainPlan] = useState<CustomDomainReadinessPlan | null>(null);
  const [emailTwoFactorPolicy, setEmailTwoFactorPolicy] = useState<EmailTwoFactorPolicy | null>(null);
  const [authSession, setAuthSession] = useState<AuthSessionChallengeState | null>(null);
  const [challengeAudit, setChallengeAudit] = useState<LoginChallengeAuditEvent[]>([]);
  const [revocation, setRevocation] = useState<EmailTwoFactorRevocationState | null>(null);
  const [myItems, setMyItems] = useState<WorkAssignmentQueueItem[]>([]);
  const [mySummary, setMySummary] = useState<WorkAssignmentQueueSummary>({ total: 0, overdue: 0, dueToday: 0, dueSoon: 0, urgent: 0, escalated: 0 });
  const [teamItems, setTeamItems] = useState<WorkAssignmentQueueItem[]>([]);
  const [teamSummary, setTeamSummary] = useState<WorkAssignmentQueueSummary>({ total: 0, overdue: 0, dueToday: 0, dueSoon: 0, urgent: 0, escalated: 0 });
  const [platformGovernance, setPlatformGovernance] = useState<SuperAdminNotificationGovernance | null>(null);
  const [customDomainRequests, setCustomDomainRequests] = useState<VerifiedCustomDomainRequestRecord[]>([]);
  const [requestForm, setRequestForm] = useState({ domain: "", businessJustification: "", dnsOwnerContact: "", replyHandlingPlan: "" });
  const [requestLoading, setRequestLoading] = useState(false);
  const [requestMessage, setRequestMessage] = useState<string | null>(null);
  const [requestStatusFilter, setRequestStatusFilter] = useState<"ALL" | VerifiedCustomDomainRequestStatus>("ALL");
  const [reviewNotesDrafts, setReviewNotesDrafts] = useState<Record<string, string>>({});

  useEffect(() => {
    apiGet<{ user: User }>("/api/auth/me").then((data) => setUser(data.user)).catch(() => setUser(null));
    apiGet<{ preferences: NotificationPreferences }>("/api/notifications/preferences")
      .then((data) => setPrefs({ ...DEFAULT_PREFS, ...data.preferences }))
      .catch(() => setPrefs(DEFAULT_PREFS));
    apiGet<{ readiness: NotificationReadiness }>("/api/notifications/readiness")
      .then((data) => setReadiness(data.readiness))
      .catch(() => setReadiness(null));
    apiGet<{ governance: SuperAdminNotificationGovernance }>("/api/notifications/platform-governance")
      .then((data) => setPlatformGovernance(data.governance))
      .catch(() => setPlatformGovernance(null));
    apiGet<{ requests: VerifiedCustomDomainRequestRecord[] }>("/api/notifications/custom-domain-requests")
      .then((data) => setCustomDomainRequests(data.requests ?? []))
      .catch(() => setCustomDomainRequests([]));
    apiGet<{ previews: NotificationSenderPreviewTool[]; customDomainPlan: CustomDomainReadinessPlan }>("/api/notifications/sender-preview")
      .then((data) => {
        setSenderPreviews(data.previews ?? []);
        setCustomDomainPlan(data.customDomainPlan ?? null);
      })
      .catch(() => {
        setSenderPreviews([]);
        setCustomDomainPlan(null);
      });
    apiGet<{ logs: OutboundEmailLog[]; authWorkflows: AuthWorkflowStatus }>("/api/notifications/logs")
      .then((data) => {
        setRecentLogs(data.logs);
        setAuthWorkflows(data.authWorkflows);
        setEmailTwoFactorPolicy(data.authWorkflows?.emailTwoFactorPolicy ?? null);
      })
      .catch(() => {
        setRecentLogs([]);
        setAuthWorkflows(null);
        setEmailTwoFactorPolicy(null);
      });
    apiGet<{ policy: EmailTwoFactorPolicy; authSession: AuthSessionChallengeState; audit: LoginChallengeAuditEvent[]; revocation: EmailTwoFactorRevocationState }>("/api/auth/email-2fa/policy")
      .then((data) => {
        setEmailTwoFactorPolicy(data.policy);
        setAuthSession(data.authSession);
        setChallengeAudit(data.audit ?? []);
        setRevocation(data.revocation ?? null);
      })
      .catch(() => {
        setAuthSession(null);
      });
    apiGet<{ items: WorkAssignmentQueueItem[]; summary: WorkAssignmentQueueSummary }>("/api/assignments/queue?scope=MINE")
      .then((data) => { setMyItems(data.items.slice(0, 8)); setMySummary(data.summary); })
      .catch(() => {});
    apiGet<{ items: WorkAssignmentQueueItem[]; summary: WorkAssignmentQueueSummary }>("/api/assignments/queue?scope=TEAM")
      .then((data) => { setTeamItems(data.items.slice(0, 8)); setTeamSummary(data.summary); })
      .catch(() => {});
  }, []);

  async function updatePref(key: keyof NotificationPreferences, value: boolean) {
    const next = { ...prefs, [key]: value };
    setPrefs(next);
    setPrefsSaving(true);
    setPrefsMessage(null);
    try {
      const data = await apiPut<{ preferences: NotificationPreferences }>("/api/notifications/preferences", next);
      setPrefs({ ...DEFAULT_PREFS, ...data.preferences });
      setPrefsMessage("Preferences saved.");
    } catch (error: any) {
      setPrefsMessage(error?.message ?? "Failed to save preferences.");
    } finally {
      setPrefsSaving(false);
    }
  }


  async function runEmailAction(path: string, successMessage: string, body?: unknown) {
    setEmailActionLoading(true);
    setEmailActionMessage(null);
    try {
      await apiPost(path, body ?? {});
      setEmailActionMessage(successMessage);
      const data = await apiGet<{ logs: OutboundEmailLog[]; authWorkflows: AuthWorkflowStatus }>("/api/notifications/logs");
      setRecentLogs(data.logs);
      setAuthWorkflows(data.authWorkflows);
      setEmailTwoFactorPolicy(data.authWorkflows?.emailTwoFactorPolicy ?? null);
    } catch (error: any) {
      setEmailActionMessage(error?.message ?? "Email action failed.");
    } finally {
      setEmailActionLoading(false);
    }
  }

  async function sendSenderPreview(senderKey: string) {
    await runEmailAction("/api/notifications/sender-preview", `Sender preview email sent for ${senderKey}.`, { senderKey });
  }

  async function revokeTrustedSession() {
    try {
      setEmailActionLoading(true);
      setEmailActionMessage(null);
      await apiPost<{ revoked: boolean }>("/api/auth/email-2fa/revoke-trusted-session", {});
      setEmailActionMessage("Trusted email 2FA grace was revoked for this browser. The next eligible login will require a fresh challenge.");
      const policyData = await apiGet<{ policy: EmailTwoFactorPolicy; authSession: AuthSessionChallengeState; audit: LoginChallengeAuditEvent[]; revocation: EmailTwoFactorRevocationState }>("/api/auth/email-2fa/policy");
      setEmailTwoFactorPolicy(policyData.policy ?? null);
      setAuthSession(policyData.authSession ?? null);
      setChallengeAudit(policyData.audit ?? []);
      setRevocation(policyData.revocation ?? null);
    } catch (error: any) {
      setEmailActionMessage(error?.message ?? "Failed to revoke trusted session grace.");
    } finally {
      setEmailActionLoading(false);
    }
  }

  async function refreshCustomDomainRequests() {
    try {
      const data = await apiGet<{ requests: VerifiedCustomDomainRequestRecord[] }>("/api/notifications/custom-domain-requests");
      setCustomDomainRequests(data.requests ?? []);
      const governanceData = await apiGet<{ governance: SuperAdminNotificationGovernance }>("/api/notifications/platform-governance").catch(() => null as any);
      if (governanceData?.governance) setPlatformGovernance(governanceData.governance);
    } catch {}
  }

  async function submitCustomDomainRequest() {
    setRequestLoading(true);
    setRequestMessage(null);
    try {
      await apiPost<{ request: VerifiedCustomDomainRequestRecord }>("/api/notifications/custom-domain-requests", requestForm);
      setRequestForm({ domain: "", businessJustification: "", dnsOwnerContact: "", replyHandlingPlan: "" });
      setRequestMessage("Verified custom-domain request submitted for Super Admin review.");
      await refreshCustomDomainRequests();
    } catch (error: any) {
      setRequestMessage(error?.message ?? "Failed to submit custom-domain request.");
    } finally {
      setRequestLoading(false);
    }
  }

  async function reviewCustomDomainRequest(requestId: string, status: VerifiedCustomDomainRequestStatus) {
    setRequestLoading(true);
    setRequestMessage(null);
    try {
      const reviewNotes = (reviewNotesDrafts[requestId] ?? "").trim();
      await apiPatch<{ request: VerifiedCustomDomainRequestRecord }>(`/api/notifications/custom-domain-requests/${requestId}`, { status, reviewNotes: reviewNotes || undefined });
      setRequestMessage(`Request moved to ${status.replaceAll("_", " ")}.`);
      setReviewNotesDrafts((current) => ({ ...current, [requestId]: "" }));
      await refreshCustomDomainRequests();
    } catch (error: any) {
      setRequestMessage(error?.message ?? "Failed to update request status.");
    } finally {
      setRequestLoading(false);
    }
  }

  const inboxPreview = useMemo(() => [...myItems, ...teamItems].slice(0, 10), [myItems, teamItems]);
  const emailAuditSummary = useMemo(() => {
    const summary = { total: recentLogs.length, sent: 0, failed: 0, skipped: 0, pending: 0 };
    for (const log of recentLogs) {
      if (log.status === "SENT") summary.sent += 1;
      else if (log.status === "FAILED") summary.failed += 1;
      else if (log.status === "SKIPPED") summary.skipped += 1;
      else if (log.status === "PENDING") summary.pending += 1;
    }
    return summary;
  }, [recentLogs]);
  const templateSummary = useMemo(() => {
    const counts = new Map<string, number>();
    for (const log of recentLogs) counts.set(log.templateKey, (counts.get(log.templateKey) ?? 0) + 1);
    return Array.from(counts.entries()).sort((a, b) => b[1] - a[1]).slice(0, 4);
  }, [recentLogs]);
  const latestEmailEvent = recentLogs[0] ?? null;
  const workspaceBrandName = user?.organization?.name || "Your workspace";
  const workspaceReplyToPreview = readiness?.workspaceReplyToSupported ? `ops@${workspaceBrandName.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "") || "workspace"}.example.com` : (readiness?.replyTo || null);

  const filteredGovernanceRequests = useMemo(() => {
    const records = platformGovernance?.requestRecords ?? [];
    if (requestStatusFilter === "ALL") return records;
    return records.filter((item) => item.status === requestStatusFilter);
  }, [platformGovernance?.requestRecords, requestStatusFilter]);

  const governanceOutcomeSummary = useMemo(() => {
    const records = platformGovernance?.requestRecords ?? [];
    return {
      total: records.length,
      submitted: records.filter((item) => item.status === "SUBMITTED").length,
      inReview: records.filter((item) => item.status === "IN_REVIEW").length,
      qualified: records.filter((item) => item.status === "QUALIFIED").length,
      approved: records.filter((item) => item.status === "APPROVED").length,
      rejected: records.filter((item) => item.status === "REJECTED").length,
      paused: records.filter((item) => item.status === "PAUSED").length,
    };
  }, [platformGovernance?.requestRecords]);

  const governanceQueueAging = useMemo(() => {
    const records = platformGovernance?.requestRecords ?? [];
    const now = Date.now();
    const counts = { fresh: 0, aging: 0, stale: 0, urgent: 0 };
    for (const item of records) {
      if (item.status === "APPROVED" || item.status === "REJECTED") continue;
      const submittedAt = new Date(item.submittedAt).getTime();
      const days = Math.max(0, Math.floor((now - submittedAt) / 86400000));
      if (days >= 14) counts.urgent += 1;
      else if (days >= 7) counts.stale += 1;
      else if (days >= 3) counts.aging += 1;
      else counts.fresh += 1;
    }
    return counts;
  }, [platformGovernance?.requestRecords]);

  const governancePriorityPrompts = useMemo(() => {
    const prompts: Array<{ key: string; label: string; status: "READY" | "WATCH" | "CLEAR"; body: string }> = [];
    prompts.push({
      key: "urgent-aging",
      label: "Urgent aging attention",
      status: governanceQueueAging.urgent > 0 ? "READY" : governanceQueueAging.stale > 0 ? "WATCH" : "CLEAR",
      body: governanceQueueAging.urgent > 0
        ? `${governanceQueueAging.urgent} request${governanceQueueAging.urgent === 1 ? " has" : "s have"} been waiting 14+ days and should be reviewed first.`
        : governanceQueueAging.stale > 0
          ? `${governanceQueueAging.stale} request${governanceQueueAging.stale === 1 ? " is" : "s are"} moving into stale territory and should be scheduled next.`
          : "No urgent aging pressure is currently visible in the governance queue.",
    });
    prompts.push({
      key: "qualification-focus",
      label: "Qualification follow-up",
      status: governanceOutcomeSummary.qualified > 0 ? "READY" : governanceOutcomeSummary.inReview > 0 ? "WATCH" : "CLEAR",
      body: governanceOutcomeSummary.qualified > 0
        ? `${governanceOutcomeSummary.qualified} qualified request${governanceOutcomeSummary.qualified === 1 ? " is" : "s are"} ready for tighter response and decision follow-up.`
        : governanceOutcomeSummary.inReview > 0
          ? `${governanceOutcomeSummary.inReview} request${governanceOutcomeSummary.inReview === 1 ? " is" : "s are"} still in review and may need prioritization.`
          : "No qualified or in-review backlog currently needs immediate response-priority escalation.",
    });
    prompts.push({
      key: "held-approved",
      label: "Approved-but-held follow-up",
      status: governanceOutcomeSummary.approved > 0 ? "WATCH" : "CLEAR",
      body: governanceOutcomeSummary.approved > 0
        ? `${governanceOutcomeSummary.approved} approved request${governanceOutcomeSummary.approved === 1 ? " remains" : "s remain"} held behind governed activation prerequisites.`
        : "No approved records are currently waiting in governed hold state.",
    });
    return prompts;
  }, [governanceOutcomeSummary, governanceQueueAging]);

  const reviewerFollowUpReminders = useMemo(() => {
    const records = filteredGovernanceRequests;
    const now = Date.now();
    const needsFollowUp = records.filter((item) => {
      if (item.status === "APPROVED" || item.status === "REJECTED") return false;
      const reviewedAt = item.reviewedAt ? new Date(item.reviewedAt).getTime() : null;
      const submittedAt = new Date(item.submittedAt).getTime();
      const baseline = reviewedAt ?? submittedAt;
      const days = Math.max(0, Math.floor((now - baseline) / 86400000));
      return days >= 3;
    });
    const overdueFollowUp = needsFollowUp.filter((item) => {
      const reviewedAt = item.reviewedAt ? new Date(item.reviewedAt).getTime() : null;
      const submittedAt = new Date(item.submittedAt).getTime();
      const baseline = reviewedAt ?? submittedAt;
      const days = Math.max(0, Math.floor((now - baseline) / 86400000));
      return days >= 7;
    });
    const pausedFollowUp = records.filter((item) => item.status === "PAUSED");
    const unassignedOpen = records.filter((item) => item.status !== "APPROVED" && item.status !== "REJECTED" && !item.reviewedByUserId);

    return [
      {
        key: "FOLLOW_UP_DUE",
        label: "Reviewer follow-up due",
        value: String(needsFollowUp.length),
        tone: needsFollowUp.length ? "bg-amber-50 text-amber-900" : "bg-emerald-50 text-emerald-900",
        helpText: needsFollowUp.length ? "Requests with no recent reviewer movement in 3+ days should be checked for follow-up." : "No reviewer follow-up reminders are currently due.",
      },
      {
        key: "FOLLOW_UP_OVERDUE",
        label: "Reviewer follow-up overdue",
        value: String(overdueFollowUp.length),
        tone: overdueFollowUp.length ? "bg-rose-50 text-rose-900" : "bg-emerald-50 text-emerald-900",
        helpText: overdueFollowUp.length ? "Requests with no recent reviewer movement in 7+ days need stronger governance follow-up." : "No reviewer follow-up reminders are currently overdue.",
      },
      {
        key: "PAUSED_FOLLOW_UP",
        label: "Paused follow-up reminders",
        value: String(pausedFollowUp.length),
        tone: pausedFollowUp.length ? "bg-amber-50 text-amber-900" : "bg-emerald-50 text-emerald-900",
        helpText: pausedFollowUp.length ? "Paused requests should be checked to confirm whether workspace guidance or DNS-owner action is still pending." : "No paused requests currently need reminder follow-up.",
      },
      {
        key: "UNASSIGNED_REMINDERS",
        label: "Unassigned review reminders",
        value: String(unassignedOpen.length),
        tone: unassignedOpen.length ? "bg-blue-50 text-blue-900" : "bg-emerald-50 text-emerald-900",
        helpText: unassignedOpen.length ? "Open requests without reviewer ownership should be claimed before follow-up responsibility drifts." : "All visible open requests currently show reviewer ownership or the queue is clear.",
      },
    ];
  }, [filteredGovernanceRequests]);

  const governanceBacklogHealth = useMemo(() => {
    const records = platformGovernance?.requestRecords ?? [];
    const open = records.filter((item) => item.status !== "APPROVED" && item.status !== "REJECTED");
    const paused = open.filter((item) => item.status === "PAUSED").length;
    const stalePressure = governanceQueueAging.stale + governanceQueueAging.urgent;
    const unassigned = open.filter((item) => !item.reviewedByUserId).length;
    const healthScore = Math.max(0, 100 - (stalePressure * 15) - (paused * 8) - (unassigned * 10));
    const status = healthScore >= 85 ? "HEALTHY" : healthScore >= 60 ? "WATCH" : "AT_RISK";
    const prompts = [
      {
        key: "BACKLOG_HEALTH",
        label: "Backlog health status",
        status,
        body: status === "HEALTHY"
          ? "The governance queue currently looks healthy with limited stale pressure and reviewer drift."
          : status === "WATCH"
            ? "The governance queue is carrying moderate follow-up pressure. Review stale, paused, or unassigned requests soon."
            : "The governance queue is under visible pressure. Prioritize stale requests, assign reviewer ownership, and clear paused blockers.",
      },
      {
        key: "BACKLOG_PRESSURE",
        label: "Backlog pressure summary",
        status: stalePressure > 0 || paused > 0 ? (stalePressure >= 2 || paused >= 2 ? "READY" : "WATCH") : "CLEAR",
        body: stalePressure > 0 || paused > 0
          ? `${stalePressure} stale/urgent request${stalePressure === 1 ? '' : 's'} and ${paused} paused request${paused === 1 ? '' : 's'} are contributing to governance backlog pressure.`
          : "No meaningful stale or paused backlog pressure is currently visible.",
      },
      {
        key: "REVIEWER_COVERAGE",
        label: "Reviewer coverage health",
        status: unassigned > 0 ? (unassigned >= 2 ? "READY" : "WATCH") : "CLEAR",
        body: unassigned > 0
          ? `${unassigned} open request${unassigned === 1 ? ' is' : 's are'} still missing reviewer ownership and may increase backlog drift.`
          : "Reviewer ownership currently covers the visible open governance queue.",
      },
    ] as Array<{ key: string; label: string; status: "READY" | "WATCH" | "CLEAR" | "HEALTHY" | "AT_RISK"; body: string }>;
    return { healthScore, status, prompts };
  }, [platformGovernance?.requestRecords, governanceQueueAging]);

  const senderBrandingPreview = useMemo(() => (readiness?.senderIdentities ?? []).map((sender) => ({
    ...sender,
    displayFromName: sender.key === "PLATFORM_DEFAULT" ? `${workspaceBrandName} via Dispatch Spot` : sender.fromName,
    displayReplyTo: readiness?.workspaceReplyToSupported ? workspaceReplyToPreview : sender.replyTo,
  })), [readiness, workspaceBrandName, workspaceReplyToPreview]);

  return (
    <div className="space-y-6">
      <section className="rounded-2xl border bg-white p-5 shadow-sm">
        <div className="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
          <div>
            <h2 className="text-base font-semibold text-slate-900">Notification center foundation</h2>
            <p className="mt-1 text-sm text-slate-500">Assignment-aware inbox foundation for in-app visibility, email preference planning, and future SMS escalation lanes.</p>
          </div>
          <div className="grid grid-cols-2 gap-3 lg:grid-cols-4">
            {summaryTile("My open", mySummary.total)}
            {summaryTile("My overdue", mySummary.overdue, "bg-red-50")}
            {summaryTile("My today", mySummary.dueToday, "bg-amber-50")}
            {summaryTile("Team escalated", teamSummary.escalated, "bg-blue-50")}
          </div>
        </div>
      </section>


            {user?.role === "ORG_ADMIN" && !user?.isSuperAdmin ? (
        <section className="rounded-2xl border bg-white p-5 shadow-sm">
          <div className="mb-4 flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
            <div>
              <h3 className="text-base font-semibold text-slate-900">Verified custom-domain request intake</h3>
              <p className="mt-1 text-sm text-slate-500">Workspace Admin can submit governed verified-domain requests for later Super Admin review. Submission does not activate live sending.</p>
            </div>
            <div className="rounded-2xl border bg-slate-50 px-4 py-3 text-xs text-slate-600">
              <div>Requests submitted: <span className="font-semibold text-slate-800">{customDomainRequests.length}</span></div>
              <div className="mt-1">Review path: <span className="font-semibold text-slate-800">Super Admin governance queue</span></div>
            </div>
          </div>
          <div className="grid gap-4 lg:grid-cols-2">
            <div className="space-y-3 rounded-2xl border bg-slate-50 p-4">
              <label className="block text-sm font-medium text-slate-700">Requested sending domain</label>
              <input value={requestForm.domain} onChange={(e) => setRequestForm((current) => ({ ...current, domain: e.target.value }))} className="w-full rounded-xl border px-3 py-2 text-sm" placeholder="mail.yourcompany.com" />
              <label className="block text-sm font-medium text-slate-700">Business justification</label>
              <textarea value={requestForm.businessJustification} onChange={(e) => setRequestForm((current) => ({ ...current, businessJustification: e.target.value }))} className="min-h-[110px] w-full rounded-xl border px-3 py-2 text-sm" placeholder="Why platform-managed sender branding is not enough for this workspace" />
              <label className="block text-sm font-medium text-slate-700">DNS owner contact</label>
              <input value={requestForm.dnsOwnerContact} onChange={(e) => setRequestForm((current) => ({ ...current, dnsOwnerContact: e.target.value }))} className="w-full rounded-xl border px-3 py-2 text-sm" placeholder="Name, team, or email responsible for DNS changes" />
              <label className="block text-sm font-medium text-slate-700">Reply-handling plan</label>
              <textarea value={requestForm.replyHandlingPlan} onChange={(e) => setRequestForm((current) => ({ ...current, replyHandlingPlan: e.target.value }))} className="min-h-[80px] w-full rounded-xl border px-3 py-2 text-sm" placeholder="Optional: explain reply-routing or bounce-handling expectations" />
              <div className="flex items-center gap-3">
                <button type="button" onClick={submitCustomDomainRequest} disabled={requestLoading} className="rounded-xl bg-slate-900 px-4 py-2 text-sm font-medium text-white disabled:opacity-50">{requestLoading ? "Submitting..." : "Submit request"}</button>
                {requestMessage ? <span className="text-xs text-slate-500">{requestMessage}</span> : null}
              </div>
            </div>
            <div className="rounded-2xl border bg-white p-4">
              <div className="text-sm font-semibold text-slate-900">Your submitted requests</div>
              <div className="mt-3 space-y-3">
                {customDomainRequests.length ? customDomainRequests.map((request) => (
                  <div key={request.id} className="rounded-2xl border bg-slate-50 p-3 text-sm text-slate-700">
                    <div className="flex items-center justify-between gap-3">
                      <div className="font-semibold text-slate-900">{request.domain}</div>
                      <span className="rounded-full border px-2 py-1 text-[11px] font-semibold uppercase tracking-wide text-slate-600">{request.status.replaceAll("_", " ")}</span>
                    </div>
                    <div className="mt-2 text-xs text-slate-500">Submitted {new Date(request.submittedAt).toLocaleString()}</div>
                    <div className="mt-2 text-xs text-slate-600">{request.businessJustification}</div>
                  </div>
                )) : <div className="rounded-2xl border border-dashed bg-slate-50 p-4 text-sm text-slate-500">No requests submitted yet.</div>}
              </div>
            </div>
          </div>
        </section>
      ) : null}

{user?.isSuperAdmin && platformGovernance ? (
        <>
        <section className="rounded-2xl border bg-white p-5 shadow-sm">
          <div className="mb-4 flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
            <div>
              <h3 className="text-base font-semibold text-slate-900">Super-admin notification governance</h3>
              <p className="mt-1 text-sm text-slate-500">Platform-owned notification transport, sender-domain policy, and sender control surfaces for Dispatch Spot.</p>
            </div>
            <div className="rounded-2xl border bg-slate-50 px-4 py-3 text-xs text-slate-600">
              <div>Governance owner: <span className="font-semibold text-slate-800">Super Admin</span></div>
              <div className="mt-1">Transport mode: <span className="font-semibold text-slate-800">Platform SMTP</span></div>
            </div>
          </div>
          <div className="grid gap-3 lg:grid-cols-2 xl:grid-cols-4">
            {platformGovernance.senderControls.map((control) => (
              <div key={control.key} className="rounded-2xl border bg-slate-50 p-4 text-sm text-slate-700">
                <div className="text-xs font-semibold uppercase tracking-wide text-slate-500">{control.label}</div>
                <div className="mt-2 font-semibold text-slate-900">{control.value}</div>
                <div className="mt-2 text-xs text-slate-500">{control.helpText}</div>
              </div>
            ))}
          </div>
          <div className="mt-4 grid gap-3 xl:grid-cols-3">
            {platformGovernance.senderIdentities.map((sender) => (
              <div key={sender.key} className="rounded-2xl border bg-white p-4 text-sm text-slate-700 shadow-sm">
                <div className="text-xs font-semibold uppercase tracking-wide text-slate-500">{sender.label}</div>
                <div className="mt-2 font-semibold text-slate-900">{sender.fromName}</div>
                <div className="mt-1 text-xs text-slate-500">From: {sender.fromEmail || "Not configured"}</div>
                <div className="mt-1 text-xs text-slate-500">Reply-To: {sender.replyTo || "Platform default"}</div>
                <div className="mt-2 text-xs text-slate-500">{sender.purpose}</div>
              </div>
            ))}
          </div>
        </section>

        <section className="rounded-2xl border bg-white p-5 shadow-sm">
          <div className="mb-4 flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
            <div>
              <h3 className="text-base font-semibold text-slate-900">Notification scheduler platform health</h3>
              <p className="mt-1 text-sm text-slate-500">Super Admin visibility for protected digest scheduler runs across workspaces. This shows health, history, and simple action guidance without exposing secrets, SMTP credentials, or provider diagnostics.</p>
            </div>
            <div className={`rounded-2xl border px-4 py-3 text-xs ${platformGovernance.schedulerPlatformHealth.status === "NEEDS_ATTENTION" ? "border-rose-200 bg-rose-50 text-rose-800" : platformGovernance.schedulerPlatformHealth.status === "READY" ? "border-emerald-200 bg-emerald-50 text-emerald-800" : platformGovernance.schedulerPlatformHealth.status === "LOCKED" ? "border-blue-200 bg-blue-50 text-blue-800" : "border-amber-200 bg-amber-50 text-amber-800"}`}>
              <div className="font-semibold">{platformGovernance.schedulerPlatformHealth.statusLabel}</div>
              <div className="mt-1">Automation: {platformGovernance.schedulerPlatformHealth.automationEnabled ? "Enabled" : "Approval-first"}</div>
              <div className="mt-1">Webhook: {platformGovernance.schedulerPlatformHealth.webhookConfigured ? "Configured" : "Not configured"}</div>
            </div>
          </div>
          <div className="rounded-2xl border bg-slate-50 p-4 text-sm text-slate-700">
            <div className="font-semibold text-slate-900">{platformGovernance.schedulerPlatformHealth.message}</div>
            <div className="mt-2 text-xs text-slate-500">Last run: {platformGovernance.schedulerPlatformHealth.lastRunAt ? new Date(platformGovernance.schedulerPlatformHealth.lastRunAt).toLocaleString() : "No recorded run yet"} {platformGovernance.schedulerPlatformHealth.lastRunStatusLabel ? `· ${platformGovernance.schedulerPlatformHealth.lastRunStatusLabel}` : ""}</div>
          </div>
          <div className="mt-4 grid gap-3 md:grid-cols-2 xl:grid-cols-5">
            <div className="rounded-2xl border bg-white p-4 text-sm text-slate-700 shadow-sm"><div className="text-xs font-semibold uppercase tracking-wide text-slate-500">Recent runs</div><div className="mt-2 text-2xl font-semibold text-slate-900">{platformGovernance.schedulerPlatformHealth.recentRunCount}</div></div>
            <div className="rounded-2xl border bg-white p-4 text-sm text-slate-700 shadow-sm"><div className="text-xs font-semibold uppercase tracking-wide text-slate-500">Workspaces seen</div><div className="mt-2 text-2xl font-semibold text-slate-900">{platformGovernance.schedulerPlatformHealth.workspaceCount}</div></div>
            <div className="rounded-2xl border bg-white p-4 text-sm text-slate-700 shadow-sm"><div className="text-xs font-semibold uppercase tracking-wide text-slate-500">Users checked</div><div className="mt-2 text-2xl font-semibold text-slate-900">{platformGovernance.schedulerPlatformHealth.totals.usersChecked}</div></div>
            <div className="rounded-2xl border bg-white p-4 text-sm text-slate-700 shadow-sm"><div className="text-xs font-semibold uppercase tracking-wide text-slate-500">Sent</div><div className="mt-2 text-2xl font-semibold text-emerald-700">{platformGovernance.schedulerPlatformHealth.totals.sent}</div></div>
            <div className="rounded-2xl border bg-white p-4 text-sm text-slate-700 shadow-sm"><div className="text-xs font-semibold uppercase tracking-wide text-slate-500">Needs attention</div><div className="mt-2 text-2xl font-semibold text-rose-700">{platformGovernance.schedulerPlatformHealth.failedRunCount + platformGovernance.schedulerPlatformHealth.totals.failed}</div></div>
          </div>
          <div className="mt-4 grid gap-4 xl:grid-cols-3">
            <div className="rounded-2xl border bg-slate-50 p-4 text-xs text-slate-600 xl:col-span-2">
              <div className="font-semibold uppercase tracking-wide text-slate-500">Recent scheduler runs</div>
              <div className="mt-3 space-y-2">
                {platformGovernance.schedulerRunRecords.length ? platformGovernance.schedulerRunRecords.slice(0, 6).map((run) => (
                  <div key={run.id} className="rounded-xl border bg-white px-3 py-2">
                    <div className="flex flex-col gap-2 md:flex-row md:items-start md:justify-between">
                      <div>
                        <div className="font-semibold text-slate-900">{run.organizationName}</div>
                        <div className="mt-1 text-[11px] text-slate-500">{new Date(run.createdAt).toLocaleString()} · {run.dryRun ? "Dry run" : "Live check"}</div>
                      </div>
                      <div className={`rounded-full border px-2 py-1 text-[10px] font-semibold uppercase tracking-wide ${run.statusLabel === "Needs attention" ? "border-rose-200 bg-rose-50 text-rose-700" : run.statusLabel === "Completed" || run.statusLabel === "Dry run complete" ? "border-emerald-200 bg-emerald-50 text-emerald-700" : "border-slate-200 bg-slate-50 text-slate-700"}`}>{run.statusLabel}</div>
                    </div>
                    <div className="mt-2 text-[11px] text-slate-500">{run.message}</div>
                    <div className="mt-2 grid gap-2 text-[11px] text-slate-600 md:grid-cols-5">
                      <div>Users: <span className="font-semibold text-slate-800">{run.usersChecked}</span></div>
                      <div>Sent: <span className="font-semibold text-emerald-700">{run.sent}</span></div>
                      <div>Ready: <span className="font-semibold text-blue-700">{run.readyForApproval}</span></div>
                      <div>Skipped: <span className="font-semibold text-slate-700">{run.skipped}</span></div>
                      <div>Failed: <span className="font-semibold text-rose-700">{run.failed}</span></div>
                    </div>
                  </div>
                )) : <div className="rounded-xl border border-dashed bg-white px-3 py-4 text-slate-500">No protected scheduler runs have been recorded yet.</div>}
              </div>
            </div>
            <div className="rounded-2xl border bg-slate-50 p-4 text-xs text-slate-600">
              <div className="font-semibold uppercase tracking-wide text-slate-500">Platform guardrails</div>
              <ul className="mt-3 space-y-2">
                {platformGovernance.schedulerPlatformHealth.guidance.map((item) => (
                  <li key={item} className="flex gap-2"><span className="mt-0.5 text-slate-400">•</span><span>{item}</span></li>
                ))}
              </ul>
            </div>
          </div>
          <div className="mt-4 rounded-2xl border bg-white p-4 shadow-sm">
            <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
              <div>
                <div className="text-xs font-semibold uppercase tracking-wide text-slate-500">Scheduler runbook / cron setup</div>
                <div className="mt-2 text-sm font-semibold text-slate-900">{platformGovernance.schedulerPlatformHealth.runbook.statusLabel}</div>
                <div className="mt-1 text-xs text-slate-500">{platformGovernance.schedulerPlatformHealth.runbook.message}</div>
              </div>
              <div className="rounded-2xl border bg-slate-50 px-4 py-3 text-xs text-slate-600">
                <div>Endpoint: <span className="font-semibold text-slate-800">{platformGovernance.schedulerPlatformHealth.runbook.endpointPath}</span></div>
                <div className="mt-1">Cadence: <span className="font-semibold text-slate-800">Business-hours guarded checks</span></div>
              </div>
            </div>
            <div className="mt-4 grid gap-3 lg:grid-cols-3">
              {platformGovernance.schedulerPlatformHealth.runbook.environmentVariables.map((item) => (
                <div key={item.key} className="rounded-xl border bg-slate-50 p-3 text-xs text-slate-600">
                  <div className="font-semibold text-slate-900">{item.label}</div>
                  <div className="mt-1 font-mono text-[11px] text-slate-700">{item.key}</div>
                  <div className="mt-2">{item.helpText}</div>
                  <div className="mt-2 rounded-full border bg-white px-2 py-1 text-[10px] font-semibold uppercase tracking-wide text-slate-500">{item.safeToShowValue ? "Value may be summarized" : "Never show value"}</div>
                </div>
              ))}
            </div>
            <div className="mt-4 grid gap-4 xl:grid-cols-3">
              <div className="rounded-2xl border bg-slate-50 p-4 text-xs text-slate-600">
                <div className="font-semibold uppercase tracking-wide text-slate-500">Setup steps</div>
                <div className="mt-3 space-y-2">
                  {platformGovernance.schedulerPlatformHealth.runbook.setupSteps.map((step) => (
                    <div key={step.key} className="rounded-xl border bg-white px-3 py-2">
                      <div className="font-semibold text-slate-900">{step.label}</div>
                      <div className="mt-1 text-slate-500">{step.body}</div>
                    </div>
                  ))}
                </div>
              </div>
              <div className="rounded-2xl border bg-slate-50 p-4 text-xs text-slate-600">
                <div className="font-semibold uppercase tracking-wide text-slate-500">Verification steps</div>
                <div className="mt-3 space-y-2">
                  {platformGovernance.schedulerPlatformHealth.runbook.verificationSteps.map((step) => (
                    <div key={step.key} className="rounded-xl border bg-white px-3 py-2">
                      <div className="font-semibold text-slate-900">{step.label}</div>
                      <div className="mt-1 text-slate-500">{step.body}</div>
                    </div>
                  ))}
                </div>
              </div>
              <div className="rounded-2xl border bg-slate-50 p-4 text-xs text-slate-600">
                <div className="font-semibold uppercase tracking-wide text-slate-500">Rollback steps</div>
                <div className="mt-3 space-y-2">
                  {platformGovernance.schedulerPlatformHealth.runbook.rollbackSteps.map((step) => (
                    <div key={step.key} className="rounded-xl border bg-white px-3 py-2">
                      <div className="font-semibold text-slate-900">{step.label}</div>
                      <div className="mt-1 text-slate-500">{step.body}</div>
                    </div>
                  ))}
                </div>
              </div>
            </div>
            <div className="mt-4 grid gap-3 xl:grid-cols-2">
              {platformGovernance.schedulerPlatformHealth.runbook.cronExamples.map((example) => (
                <div key={example.key} className="rounded-2xl border bg-slate-950 p-4 text-xs text-slate-200">
                  <div className="font-semibold text-white">{example.label}</div>
                  <div className="mt-1 text-slate-400">{example.cadence}</div>
                  <pre className="mt-3 overflow-auto whitespace-pre-wrap rounded-xl bg-slate-900 p-3 font-mono text-[11px] leading-relaxed text-slate-100">{example.command}</pre>
                  <ul className="mt-3 space-y-1 text-slate-300">
                    {example.notes.map((note) => <li key={note}>• {note}</li>)}
                  </ul>
                </div>
              ))}
            </div>
            <div className="mt-4 rounded-2xl border bg-amber-50 p-4 text-xs text-amber-900">
              <div className="font-semibold uppercase tracking-wide">Runbook guardrails</div>
              <ul className="mt-3 grid gap-2 md:grid-cols-2">
                {platformGovernance.schedulerPlatformHealth.runbook.guardrails.map((item) => <li key={item}>• {item}</li>)}
              </ul>
            </div>
          </div>

        </section>

        <section className="rounded-2xl border bg-white p-5 shadow-sm">
          <div className="mb-4 flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
            <div>
              <h3 className="text-base font-semibold text-slate-900">Sender policy help center</h3>
              <p className="mt-1 text-sm text-slate-500">Super Admin guidance for how sender governance works today and how verified custom-domain sending will be introduced later.</p>
            </div>
            <div className="rounded-2xl border bg-slate-50 px-4 py-3 text-xs text-slate-600">
              <div>Help topics: <span className="font-semibold text-slate-800">{platformGovernance.helpCenter.length}</span></div>
              <div className="mt-1">Queue mode: <span className="font-semibold text-slate-800">Governed review queue</span></div>
            </div>
          </div>
          <div className="grid gap-3 xl:grid-cols-3">
            {platformGovernance.helpCenter.map((article) => (
              <div key={article.key} className="rounded-2xl border bg-slate-50 p-4 text-sm text-slate-700">
                <div className="text-xs font-semibold uppercase tracking-wide text-slate-500">Policy guide</div>
                <div className="mt-2 font-semibold text-slate-900">{article.title}</div>
                <div className="mt-2 text-xs text-slate-500">{article.summary}</div>
                <ul className="mt-3 space-y-2 text-xs text-slate-600">
                  {article.bullets.map((bullet) => (
                    <li key={bullet} className="flex gap-2"><span className="mt-0.5 text-slate-400">•</span><span>{bullet}</span></li>
                  ))}
                </ul>
              </div>
            ))}
          </div>
          <div className="mt-4 rounded-2xl border bg-white p-4 shadow-sm">
            <div className="text-xs font-semibold uppercase tracking-wide text-slate-500">Verified custom-domain request intake foundation</div>
            <div className="mt-2 text-sm font-semibold text-slate-900">{platformGovernance.requestIntakeFoundation.summary}</div>
            <div className="mt-4 grid gap-3 lg:grid-cols-3">
              <div className="rounded-2xl border bg-slate-50 p-4 text-sm text-slate-700 lg:col-span-2">
                <div className="text-xs font-semibold uppercase tracking-wide text-slate-500">Intake request fields</div>
                <div className="mt-3 grid gap-3 md:grid-cols-2">
                  {platformGovernance.requestIntakeFoundation.requestFields.map((field) => (
                    <div key={field.key} className="rounded-xl border bg-white p-3 text-xs text-slate-600">
                      <div className="font-semibold text-slate-800">{field.label}{field.required ? " *" : ""}</div>
                      <div className="mt-1">{field.helpText}</div>
                    </div>
                  ))}
                </div>
              </div>
              <div className="rounded-2xl border bg-slate-50 p-4 text-sm text-slate-700">
                <div className="text-xs font-semibold uppercase tracking-wide text-slate-500">Qualification checks</div>
                <ul className="mt-3 space-y-2 text-xs text-slate-600">
                  {platformGovernance.requestIntakeFoundation.qualificationChecks.map((item) => (
                    <li key={item} className="flex gap-2"><span className="mt-0.5 text-slate-400">•</span><span>{item}</span></li>
                  ))}
                </ul>
                <div className="mt-4 text-xs font-semibold uppercase tracking-wide text-slate-500">Submission notes</div>
                <ul className="mt-3 space-y-2 text-xs text-slate-600">
                  {platformGovernance.requestIntakeFoundation.submissionNotes.map((item) => (
                    <li key={item} className="flex gap-2"><span className="mt-0.5 text-slate-400">•</span><span>{item}</span></li>
                  ))}
                </ul>
              </div>
            </div>
          </div>

          <div className="mt-4 rounded-2xl border bg-white p-4 shadow-sm">
            <div className="text-xs font-semibold uppercase tracking-wide text-slate-500">Verified custom-domain governance review queue scaffolding</div>
            <div className="mt-2 text-sm font-semibold text-slate-900">{platformGovernance.governanceQueuePlan.summary}</div>
            <div className="mt-4 grid gap-3 lg:grid-cols-3">
              <div className="rounded-2xl border bg-slate-50 p-4 text-sm text-slate-700">
                <div className="text-xs font-semibold uppercase tracking-wide text-slate-500">Entry criteria</div>
                <ul className="mt-3 space-y-2 text-xs text-slate-600">
                  {platformGovernance.governanceQueuePlan.entryCriteria.map((item) => (
                    <li key={item} className="flex gap-2"><span className="mt-0.5 text-slate-400">•</span><span>{item}</span></li>
                  ))}
                </ul>
              </div>
              <div className="rounded-2xl border bg-slate-50 p-4 text-sm text-slate-700">
                <div className="text-xs font-semibold uppercase tracking-wide text-slate-500">Review stages</div>
                <ul className="mt-3 space-y-2 text-xs text-slate-600">
                  {platformGovernance.governanceQueuePlan.reviewStages.map((item) => (
                    <li key={item} className="flex gap-2"><span className="mt-0.5 text-slate-400">•</span><span>{item}</span></li>
                  ))}
                </ul>
              </div>
              <div className="rounded-2xl border bg-slate-50 p-4 text-sm text-slate-700">
                <div className="text-xs font-semibold uppercase tracking-wide text-slate-500">Launch guardrails</div>
                <ul className="mt-3 space-y-2 text-xs text-slate-600">
                  {platformGovernance.governanceQueuePlan.launchGuardrails.map((item) => (
                    <li key={item} className="flex gap-2"><span className="mt-0.5 text-slate-400">•</span><span>{item}</span></li>
                  ))}
                </ul>
              </div>
            </div>
          </div>
        </section>

        <section className="rounded-2xl border bg-white p-5 shadow-sm">
          <div className="mb-4 flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
            <div>
              <h3 className="text-base font-semibold text-slate-900">Verified custom-domain request records</h3>
              <p className="mt-1 text-sm text-slate-500">Governed intake submissions now create reviewable request records for Super Admin follow-up, with review notes, approval outcomes, and state filtering.</p>
            </div>
            <div className="rounded-2xl border bg-slate-50 px-4 py-3 text-xs text-slate-600">
              <div>Total records: <span className="font-semibold text-slate-800">{governanceOutcomeSummary.total}</span></div>
              <div className="mt-1">Open review: <span className="font-semibold text-slate-800">{governanceOutcomeSummary.submitted + governanceOutcomeSummary.inReview + governanceOutcomeSummary.qualified}</span></div>
              <div className="mt-1">Approved: <span className="font-semibold text-emerald-700">{governanceOutcomeSummary.approved}</span> • Rejected: <span className="font-semibold text-rose-700">{governanceOutcomeSummary.rejected}</span></div>
            </div>
          </div>
          <div className="mb-4 grid gap-3 lg:grid-cols-4">
            <div className="rounded-2xl border bg-slate-50 p-3 text-xs text-slate-600">
              <div className="font-semibold uppercase tracking-wide text-slate-500">Request-state filter</div>
              <select value={requestStatusFilter} onChange={(event) => setRequestStatusFilter(event.target.value as "ALL" | VerifiedCustomDomainRequestStatus)} className="mt-2 w-full rounded-lg border px-3 py-2 text-sm text-slate-700">
                <option value="ALL">All states</option>
                <option value="SUBMITTED">Submitted</option>
                <option value="IN_REVIEW">In review</option>
                <option value="QUALIFIED">Qualified</option>
                <option value="APPROVED">Approved</option>
                <option value="REJECTED">Rejected</option>
                <option value="PAUSED">Paused</option>
              </select>
            </div>
            <div className="rounded-2xl border bg-emerald-50 p-3 text-xs text-emerald-800">
              <div className="font-semibold uppercase tracking-wide">Approval outcomes</div>
              <div className="mt-2">Approved requests are ready for later DNS verification and governed launch planning.</div>
            </div>
            <div className="rounded-2xl border bg-rose-50 p-3 text-xs text-rose-800">
              <div className="font-semibold uppercase tracking-wide">Rejection outcomes</div>
              <div className="mt-2">Rejected requests stay visible for audit history and can inform later resubmission guidance.</div>
            </div>
            <div className="rounded-2xl border bg-amber-50 p-3 text-xs text-amber-800">
              <div className="font-semibold uppercase tracking-wide">Review notes</div>
              <div className="mt-2">Super Admin can capture notes before moving a request into review, approval, rejection, or pause.</div>
            </div>
          </div>
          <div className="mb-4 grid gap-3 xl:grid-cols-4">
            {platformGovernance.reviewerWorkloadSummaries.map((item) => (
              <div key={item.key} className={`rounded-2xl border p-3 text-xs ${item.tone === "WATCH" ? "bg-amber-50 text-amber-900" : item.tone === "GOOD" ? "bg-emerald-50 text-emerald-900" : "bg-slate-50 text-slate-700"}`}>
                <div className="font-semibold uppercase tracking-wide">{item.label}</div>
                <div className="mt-2 text-2xl font-semibold">{item.value}</div>
                <div className="mt-2 text-[11px] opacity-80">{item.helpText}</div>
              </div>
            ))}
          </div>
          <div className="mb-4 grid gap-3 xl:grid-cols-4">
            <div className="rounded-2xl border bg-slate-50 p-3 text-xs text-slate-700">
              <div className="font-semibold uppercase tracking-wide">Fresh queue</div>
              <div className="mt-2 text-2xl font-semibold text-slate-900">{governanceQueueAging.fresh}</div>
              <div className="mt-2 text-[11px] opacity-80">Requests submitted in the last 2 days that are not yet in long-aging territory.</div>
            </div>
            <div className="rounded-2xl border bg-blue-50 p-3 text-xs text-blue-900">
              <div className="font-semibold uppercase tracking-wide">Aging queue</div>
              <div className="mt-2 text-2xl font-semibold">{governanceQueueAging.aging}</div>
              <div className="mt-2 text-[11px] opacity-80">Requests waiting 3–6 days and beginning to need response-priority attention.</div>
            </div>
            <div className="rounded-2xl border bg-amber-50 p-3 text-xs text-amber-900">
              <div className="font-semibold uppercase tracking-wide">Stale queue</div>
              <div className="mt-2 text-2xl font-semibold">{governanceQueueAging.stale}</div>
              <div className="mt-2 text-[11px] opacity-80">Requests waiting 7–13 days that should be pulled forward in governance response order.</div>
            </div>
            <div className="rounded-2xl border bg-rose-50 p-3 text-xs text-rose-900">
              <div className="font-semibold uppercase tracking-wide">Urgent aging</div>
              <div className="mt-2 text-2xl font-semibold">{governanceQueueAging.urgent}</div>
              <div className="mt-2 text-[11px] opacity-80">Requests waiting 14+ days that should receive the highest response-priority follow-up.</div>
            </div>
          </div>
          <div className="mb-4 grid gap-3 xl:grid-cols-3">
            {platformGovernance.governanceEscalationPrompts.map((item) => (
              <div key={item.key} className={`rounded-2xl border p-3 text-xs ${item.status === "READY" ? "bg-rose-50 text-rose-900" : item.status === "WATCH" ? "bg-amber-50 text-amber-900" : "bg-emerald-50 text-emerald-900"}`}>
                <div className="flex items-center justify-between gap-2">
                  <div className="font-semibold uppercase tracking-wide">{item.label}</div>
                  <span className="rounded-full border px-2 py-1 text-[10px] font-semibold uppercase tracking-wide">{item.status}</span>
                </div>
                <div className="mt-2 text-[11px] opacity-80">{item.body}</div>
              </div>
            ))}
          </div>
          <div className="mb-4 grid gap-3 xl:grid-cols-3">
            {governancePriorityPrompts.map((item) => (
              <div key={item.key} className={`rounded-2xl border p-3 text-xs ${item.status === "READY" ? "bg-rose-50 text-rose-900" : item.status === "WATCH" ? "bg-amber-50 text-amber-900" : "bg-emerald-50 text-emerald-900"}`}>
                <div className="flex items-center justify-between gap-2">
                  <div className="font-semibold uppercase tracking-wide">{item.label}</div>
                  <span className="rounded-full border px-2 py-1 text-[10px] font-semibold uppercase tracking-wide">{item.status}</span>
                </div>
                <div className="mt-2 text-[11px] opacity-80">{item.body}</div>
              </div>
            ))}
          </div>
          <div className="mb-4 grid gap-3 xl:grid-cols-4">
            {reviewerFollowUpReminders.map((item) => (
              <div key={item.key} className={`rounded-2xl border p-3 text-xs ${item.tone}`}>
                <div className="font-semibold uppercase tracking-wide">{item.label}</div>
                <div className="mt-2 text-2xl font-semibold">{item.value}</div>
                <div className="mt-2 text-[11px] opacity-80">{item.helpText}</div>
              </div>
            ))}
          </div>
          <div className="mb-4 grid gap-3 xl:grid-cols-4">
            <div className={`rounded-2xl border p-3 text-xs ${governanceBacklogHealth.status === "HEALTHY" ? "bg-emerald-50 text-emerald-900" : governanceBacklogHealth.status === "WATCH" ? "bg-amber-50 text-amber-900" : "bg-rose-50 text-rose-900"}`}>
              <div className="font-semibold uppercase tracking-wide">Backlog health score</div>
              <div className="mt-2 text-2xl font-semibold">{governanceBacklogHealth.healthScore}</div>
              <div className="mt-2 text-[11px] opacity-80">Overall governance backlog health across open verified custom-domain review work.</div>
            </div>
            {governanceBacklogHealth.prompts.map((item) => (
              <div key={item.key} className={`rounded-2xl border p-3 text-xs ${item.status === "READY" || item.status === "AT_RISK" ? "bg-rose-50 text-rose-900" : item.status === "WATCH" ? "bg-amber-50 text-amber-900" : "bg-emerald-50 text-emerald-900"}`}>
                <div className="flex items-center justify-between gap-2">
                  <div className="font-semibold uppercase tracking-wide">{item.label}</div>
                  <span className="rounded-full border px-2 py-1 text-[10px] font-semibold uppercase tracking-wide">{item.status.replaceAll("_", " ")}</span>
                </div>
                <div className="mt-2 text-[11px] opacity-80">{item.body}</div>
              </div>
            ))}
          </div>
          <div className="space-y-3">

            {filteredGovernanceRequests.length ? filteredGovernanceRequests.map((request) => {
              const decisionConsistencyChecks = buildDecisionConsistencyChecks(request);
              const closureGuidance = buildClosureGuidance(request);
              return (
              <div key={request.id} className="rounded-2xl border bg-slate-50 p-4 text-sm text-slate-700">
                <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
                  <div className="min-w-0 flex-1">
                    <div className="text-sm font-semibold text-slate-900">{request.domain}</div>
                    <div className="mt-1 text-xs text-slate-500">{request.organizationName || "Workspace"} • submitted by {request.requestedByName} on {new Date(request.submittedAt).toLocaleString()}</div>
                    <div className="mt-2 text-xs text-slate-600">{request.businessJustification}</div>
                    <div className="mt-2 text-xs text-slate-500">DNS owner: {request.dnsOwnerContact}{request.replyHandlingPlan ? ` • Reply plan: ${request.replyHandlingPlan}` : ""}</div>
                    {(request.reviewNotes || request.reviewedByName || request.reviewedAt) ? (
                      <div className="mt-3 rounded-xl border bg-white p-3 text-xs text-slate-600">
                        <div className="font-semibold uppercase tracking-wide text-slate-500">Latest review outcome</div>
                        <div className="mt-1">Status: <span className="font-semibold text-slate-800">{request.status.replaceAll("_", " ")}</span></div>
                        {request.reviewedByName ? <div className="mt-1">Reviewed by: <span className="font-semibold text-slate-800">{request.reviewedByName}</span></div> : null}
                        {request.reviewedAt ? <div className="mt-1">Reviewed at: <span className="font-semibold text-slate-800">{new Date(request.reviewedAt).toLocaleString()}</span></div> : null}
                        {request.reviewNotes ? <div className="mt-2 text-slate-700">{request.reviewNotes}</div> : null}
                      </div>
                    ) : null}
                    <div className="mt-3 grid gap-3 xl:grid-cols-2">
                      <div className="rounded-xl border bg-white p-3 text-xs text-slate-600">
                        <div className="font-semibold uppercase tracking-wide text-slate-500">Review timeline</div>
                        <div className="mt-3 space-y-2">
                          {request.reviewTimeline.map((event) => (
                            <div key={event.key} className="flex items-start justify-between gap-3 rounded-lg border bg-slate-50 px-3 py-2">
                              <div>
                                <div className="font-semibold text-slate-800">{event.label}</div>
                                {event.helpText ? <div className="mt-1 text-[11px] text-slate-500">{event.helpText}</div> : null}
                              </div>
                              <div className="text-right">
                                <div className={`rounded-full border px-2 py-1 text-[10px] font-semibold uppercase tracking-wide ${event.state === "COMPLETED" ? "border-emerald-200 bg-emerald-50 text-emerald-700" : event.state === "CURRENT" ? "border-blue-200 bg-blue-50 text-blue-700" : "border-slate-200 bg-white text-slate-500"}`}>{event.state.replaceAll("_", " ")}</div>
                                {event.at ? <div className="mt-1 text-[10px] text-slate-500">{new Date(event.at).toLocaleString()}</div> : null}
                              </div>
                            </div>
                          ))}
                        </div>
                      </div>
                      <div className="rounded-xl border bg-white p-3 text-xs text-slate-600">
                        <div className="font-semibold uppercase tracking-wide text-slate-500">Approval readiness checklist</div>
                        <div className="mt-3 space-y-2">
                          {request.approvalReadinessChecklist.map((item) => (
                            <div key={item.key} className="rounded-lg border bg-slate-50 px-3 py-2">
                              <div className="flex items-center justify-between gap-3">
                                <div className="font-semibold text-slate-800">{item.label}</div>
                                <div className={`rounded-full border px-2 py-1 text-[10px] font-semibold uppercase tracking-wide ${item.status === "COMPLETE" ? "border-emerald-200 bg-emerald-50 text-emerald-700" : item.status === "BLOCKED" ? "border-rose-200 bg-rose-50 text-rose-700" : "border-amber-200 bg-amber-50 text-amber-700"}`}>{item.status}</div>
                              </div>
                              <div className="mt-1 text-[11px] text-slate-500">{item.helpText}</div>
                            </div>
                          ))}
                        </div>
                      </div>
                      <div className="rounded-xl border bg-white p-3 text-xs text-slate-600">
                        <div className="font-semibold uppercase tracking-wide text-slate-500">DNS validation checklist scaffolding</div>
                        <div className="mt-3 space-y-2">
                          {request.dnsValidationChecklist.map((item) => (
                            <div key={item.key} className="rounded-lg border bg-slate-50 px-3 py-2">
                              <div className="flex items-center justify-between gap-3">
                                <div className="font-semibold text-slate-800">{item.label}</div>
                                <div className={`rounded-full border px-2 py-1 text-[10px] font-semibold uppercase tracking-wide ${item.status === "READY" ? "border-emerald-200 bg-emerald-50 text-emerald-700" : item.status === "BLOCKED" ? "border-rose-200 bg-rose-50 text-rose-700" : "border-amber-200 bg-amber-50 text-amber-700"}`}>{item.status}</div>
                              </div>
                              <div className="mt-1 text-[11px] text-slate-500">{item.helpText}</div>
                            </div>
                          ))}
                        </div>
                      </div>
                      <div className="rounded-xl border bg-white p-3 text-xs text-slate-600">
                        <div className="font-semibold uppercase tracking-wide text-slate-500">DNS record instruction surfaces</div>
                        <div className="mt-3 space-y-2">
                          {request.dnsRecordInstructions.map((item) => (
                            <div key={item.key} className="rounded-lg border bg-slate-50 px-3 py-2">
                              <div className="flex items-center justify-between gap-3">
                                <div className="font-semibold text-slate-800">{item.label}</div>
                                <div className={`rounded-full border px-2 py-1 text-[10px] font-semibold uppercase tracking-wide ${item.readiness === "READY" ? "border-emerald-200 bg-emerald-50 text-emerald-700" : item.readiness === "BLOCKED" ? "border-rose-200 bg-rose-50 text-rose-700" : "border-amber-200 bg-amber-50 text-amber-700"}`}>{item.readiness}</div>
                              </div>
                              <div className="mt-2 grid gap-2 lg:grid-cols-3">
                                <div><span className="font-semibold text-slate-700">Type:</span> {item.recordType}</div>
                                <div className="lg:col-span-2 break-all"><span className="font-semibold text-slate-700">Host:</span> {item.host}</div>
                              </div>
                              <div className="mt-1 break-all"><span className="font-semibold text-slate-700">Expected value:</span> {item.expectedValue}</div>
                              <div className="mt-1 text-[11px] text-slate-500">{item.purpose}</div>
                            </div>
                          ))}
                        </div>
                      </div>
                      <div className="rounded-xl border bg-white p-3 text-xs text-slate-600">
                        <div className="font-semibold uppercase tracking-wide text-slate-500">Approval decision guidance</div>
                        <div className="mt-3 space-y-2">
                          {request.approvalDecisionGuidance.map((item) => (
                            <div key={item.key} className="rounded-lg border bg-slate-50 px-3 py-2">
                              <div className="flex items-center justify-between gap-3">
                                <div className="font-semibold text-slate-800">{item.label}</div>
                                <div className={`rounded-full border px-2 py-1 text-[10px] font-semibold uppercase tracking-wide ${item.status === "READY" ? "border-emerald-200 bg-emerald-50 text-emerald-700" : item.status === "HOLD" ? "border-rose-200 bg-rose-50 text-rose-700" : "border-blue-200 bg-blue-50 text-blue-700"}`}>{item.status}</div>
                              </div>
                              <div className="mt-1 text-[11px] text-slate-500">{item.body}</div>
                            </div>
                          ))}
                        </div>
                      </div>
                      <div className="rounded-xl border bg-white p-3 text-xs text-slate-600">
                        <div className="font-semibold uppercase tracking-wide text-slate-500">DNS verification outcome placeholders</div>
                        <div className="mt-3 space-y-2">
                          {request.dnsVerificationOutcomePlaceholders.map((item) => (
                            <div key={item.key} className="rounded-lg border bg-slate-50 px-3 py-2">
                              <div className="flex items-center justify-between gap-3">
                                <div className="font-semibold text-slate-800">{item.label}</div>
                                <div className={`rounded-full border px-2 py-1 text-[10px] font-semibold uppercase tracking-wide ${item.status === "READY_FOR_LATER" ? "border-emerald-200 bg-emerald-50 text-emerald-700" : item.status === "PENDING" ? "border-amber-200 bg-amber-50 text-amber-700" : "border-slate-200 bg-slate-50 text-slate-700"}`}>{item.status.replaceAll("_", " ")}</div>
                              </div>
                              <div className="mt-1 text-[11px] text-slate-500">{item.body}</div>
                            </div>
                          ))}
                        </div>
                      </div>
                      <div className="rounded-xl border bg-white p-3 text-xs text-slate-600">
                        <div className="font-semibold uppercase tracking-wide text-slate-500">Approval notes</div>
                        <div className="mt-3 space-y-2">
                          {request.approvalHandoffNotes.map((item) => (
                            <div key={item.key} className="rounded-lg border bg-slate-50 px-3 py-2">
                              <div className="font-semibold text-slate-800">{item.label}</div>
                              <div className="mt-1 text-[11px] text-slate-500">{item.body}</div>
                            </div>
                          ))}
                        </div>
                      </div>
                      <div className="rounded-xl border bg-white p-3 text-xs text-slate-600">
                        <div className="font-semibold uppercase tracking-wide text-slate-500">Launch-readiness governance notes</div>
                        <div className="mt-3 space-y-2">
                          {request.launchReadinessGovernanceNotes.map((item) => (
                            <div key={item.key} className="rounded-lg border bg-slate-50 px-3 py-2">
                              <div className="font-semibold text-slate-800">{item.label}</div>
                              <div className="mt-1 text-[11px] text-slate-500">{item.body}</div>
                            </div>
                          ))}
                        </div>
                      </div>
                      <div className="rounded-xl border bg-white p-3 text-xs text-slate-600">
                        <div className="font-semibold uppercase tracking-wide text-slate-500">Final review summary</div>
                        <div className="mt-3 space-y-2">
                          {request.finalReviewSummary.map((item) => (
                            <div key={item.key} className="rounded-lg border bg-slate-50 px-3 py-2">
                              <div className="flex items-center justify-between gap-3">
                                <div className="font-semibold text-slate-800">{item.label}</div>
                                <div className={`rounded-full border px-2 py-1 text-[10px] font-semibold uppercase tracking-wide ${item.status === "READY" ? "border-emerald-200 bg-emerald-50 text-emerald-700" : item.status === "HOLD" ? "border-rose-200 bg-rose-50 text-rose-700" : "border-blue-200 bg-blue-50 text-blue-700"}`}>{item.status}</div>
                              </div>
                              <div className="mt-1 text-[11px] text-slate-500">{item.body}</div>
                            </div>
                          ))}
                        </div>
                      </div>
                      <div className="rounded-xl border bg-white p-3 text-xs text-slate-600">
                        <div className="font-semibold uppercase tracking-wide text-slate-500">Post-approval coordination surfaces</div>
                        <div className="mt-3 space-y-2">
                          {request.postApprovalCoordination.map((item) => (
                            <div key={item.key} className="rounded-lg border bg-slate-50 px-3 py-2">
                              <div className="flex items-center justify-between gap-3">
                                <div className="font-semibold text-slate-800">{item.label}</div>
                                <div className={`rounded-full border px-2 py-1 text-[10px] font-semibold uppercase tracking-wide ${item.status === "READY" ? "border-emerald-200 bg-emerald-50 text-emerald-700" : item.status === "REVIEW" ? "border-blue-200 bg-blue-50 text-blue-700" : "border-rose-200 bg-rose-50 text-rose-700"}`}>{item.status}</div>
                              </div>
                              <div className="mt-1 text-[11px] text-slate-500">{item.body}</div>
                            </div>
                          ))}
                        </div>
                      </div>
                      <div className="rounded-xl border bg-white p-3 text-xs text-slate-600">
                        <div className="font-semibold uppercase tracking-wide text-slate-500">Governed activation prerequisites summary</div>
                        <div className="mt-3 space-y-2">
                          {request.activationPrerequisitesSummary.map((item) => (
                            <div key={item.key} className="rounded-lg border bg-slate-50 px-3 py-2">
                              <div className="flex items-center justify-between gap-3">
                                <div className="font-semibold text-slate-800">{item.label}</div>
                                <div className={`rounded-full border px-2 py-1 text-[10px] font-semibold uppercase tracking-wide ${item.status === "COMPLETE" ? "border-emerald-200 bg-emerald-50 text-emerald-700" : item.status === "PENDING" ? "border-amber-200 bg-amber-50 text-amber-700" : "border-rose-200 bg-rose-50 text-rose-700"}`}>{item.status}</div>
                              </div>
                              <div className="mt-1 text-[11px] text-slate-500">{item.body}</div>
                            </div>
                          ))}
                        </div>
                      </div>
                      <div className="rounded-xl border bg-white p-3 text-xs text-slate-600">
                        <div className="flex items-start justify-between gap-3">
                          <div>
                            <div className="font-semibold uppercase tracking-wide text-slate-500">Governed activation hold-state visibility</div>
                            <div className="mt-1 text-sm font-semibold text-slate-900">{request.activationHoldState.headline}</div>
                          </div>
                          <div className={`rounded-full border px-2 py-1 text-[10px] font-semibold uppercase tracking-wide ${request.activationHoldState.status === "READY_FOR_LATER" ? "border-emerald-200 bg-emerald-50 text-emerald-700" : "border-rose-200 bg-rose-50 text-rose-700"}`}>{request.activationHoldState.status.replaceAll("_", " ")}</div>
                        </div>
                        <div className="mt-2 text-[11px] text-slate-500">{request.activationHoldState.body}</div>
                        <div className="mt-3 space-y-2">
                          {request.activationHoldState.blockers.map((item, index) => (
                            <div key={`${request.id}-hold-${index}`} className="rounded-lg border bg-slate-50 px-3 py-2 text-[11px] text-slate-600">{item}</div>
                          ))}
                        </div>
                      </div>
                    </div>
                  </div>
                  <div className="flex w-full max-w-xl flex-col gap-2 lg:w-auto">
                    <div className="flex flex-wrap items-center gap-2">
                      <span className="rounded-full border px-2 py-1 text-[11px] font-semibold uppercase tracking-wide text-slate-600">{request.status.replaceAll("_", " ")}</span>
                      <button type="button" onClick={() => reviewCustomDomainRequest(request.id, "IN_REVIEW")} disabled={requestLoading} className="rounded-lg border px-3 py-1.5 text-xs font-medium text-slate-700 disabled:opacity-50">Mark in review</button>
                      <button type="button" onClick={() => reviewCustomDomainRequest(request.id, "QUALIFIED")} disabled={requestLoading} className="rounded-lg border px-3 py-1.5 text-xs font-medium text-slate-700 disabled:opacity-50">Qualify</button>
                      <button type="button" onClick={() => reviewCustomDomainRequest(request.id, "APPROVED")} disabled={requestLoading} className="rounded-lg border border-emerald-200 bg-emerald-50 px-3 py-1.5 text-xs font-medium text-emerald-700 disabled:opacity-50">Approve</button>
                      <button type="button" onClick={() => reviewCustomDomainRequest(request.id, "REJECTED")} disabled={requestLoading} className="rounded-lg border border-rose-200 bg-rose-50 px-3 py-1.5 text-xs font-medium text-rose-700 disabled:opacity-50">Reject</button>
                      <button type="button" onClick={() => reviewCustomDomainRequest(request.id, "PAUSED")} disabled={requestLoading} className="rounded-lg border px-3 py-1.5 text-xs font-medium text-slate-700 disabled:opacity-50">Pause</button>
                    </div>
                    <textarea value={reviewNotesDrafts[request.id] ?? ""} onChange={(event) => setReviewNotesDrafts((current) => ({ ...current, [request.id]: event.target.value }))} rows={3} placeholder="Add Super Admin review notes before updating outcome..." className="w-full rounded-xl border bg-white px-3 py-2 text-xs text-slate-700" />
                  </div>
                </div>
              </div>
              );
            }) : (
              <div className="rounded-2xl border border-dashed bg-slate-50 p-4 text-sm text-slate-500">No verified custom-domain requests match the selected state filter.</div>
            )}
          </div>
        </section>
        </>
      ) : null}
      <section className="rounded-2xl border bg-white p-5 shadow-sm">
        <div className="mb-4 flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
          <div>
            <h3 className="text-base font-semibold text-slate-900">Reply-to governance controls</h3>
            <p className="mt-1 text-sm text-slate-500">Workspace-facing sender behavior now distinguishes between platform-owned sender identity and governed reply-to flexibility for your company workflows.</p>
          </div>
          <div className="rounded-2xl border bg-slate-50 px-4 py-3 text-xs text-slate-600">
            <div>Governance mode: <span className="font-semibold text-slate-800">{readiness?.replyToGovernanceMode === "WORKSPACE_REPLY_TO_ALLOWED" ? "Workspace reply-to allowed" : "Platform reply-to only"}</span></div>
            <div className="mt-1">Branding mode: <span className="font-semibold text-slate-800">{readiness?.brandingMode === "PLATFORM_SENDER_WITH_WORKSPACE_BRANDING" ? "Platform sender with workspace branding" : "Platform sender only"}</span></div>
          </div>
        </div>
        <div className="grid gap-3 lg:grid-cols-3">
          <div className="rounded-2xl border bg-slate-50 p-4 text-sm text-slate-700">
            <div className="text-xs font-semibold uppercase tracking-wide text-slate-500">Workspace brand</div>
            <div className="mt-1 font-medium">{workspaceBrandName}</div>
            <div className="mt-2 text-xs text-slate-500">Used for workspace-facing sender presentation while the sending domain remains platform-managed.</div>
          </div>
          <div className="rounded-2xl border bg-slate-50 p-4 text-sm text-slate-700">
            <div className="text-xs font-semibold uppercase tracking-wide text-slate-500">Governed reply-to</div>
            <div className="mt-1 font-medium">{workspaceReplyToPreview || readiness?.replyTo || "Platform default reply-to"}</div>
            <div className="mt-2 text-xs text-slate-500">{readiness?.replyToHelpText}</div>
          </div>
          <div className="rounded-2xl border bg-slate-50 p-4 text-sm text-slate-700">
            <div className="text-xs font-semibold uppercase tracking-wide text-slate-500">Workspace-owned raw SMTP</div>
            <div className="mt-1 font-medium">{readiness?.workspaceCustomSmtpAllowed ? "Enabled" : "Not enabled"}</div>
            <div className="mt-2 text-xs text-slate-500">Verified custom domains remain a later governed rollout path.</div>
          </div>
        </div>
        <div className="mt-4 grid gap-3 xl:grid-cols-3">
          {senderBrandingPreview.map((sender) => (
            <div key={sender.key} className="rounded-2xl border bg-white p-4 text-sm text-slate-700 shadow-sm">
              <div className="text-xs font-semibold uppercase tracking-wide text-slate-500">{sender.label}</div>
              <div className="mt-2 font-semibold text-slate-900">{sender.displayFromName}</div>
              <div className="mt-1 text-xs text-slate-500">From: {sender.fromEmail || "Not configured"}</div>
              <div className="mt-1 text-xs text-slate-500">Reply-To: {sender.displayReplyTo || "Platform default"}</div>
              <div className="mt-2 text-xs text-slate-500">{sender.purpose}</div>
            </div>
          ))}
        </div>
      </section>

      <section className="rounded-2xl border bg-white p-5 shadow-sm">
        <div className="mb-4 flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
          <div>
            <h3 className="text-base font-semibold text-slate-900">Sender-preview test tools</h3>
            <p className="mt-1 text-sm text-slate-500">Preview the governed sender lanes and optionally send a live preview email to your signed-in address while SMTP remains platform-managed.</p>
          </div>
          <div className="rounded-2xl border bg-slate-50 px-4 py-3 text-xs text-slate-600">
            <div>SMTP delivery: <span className="font-semibold text-slate-800">{readiness?.deliveryActive ? "Active" : "Not active"}</span></div>
            <div className="mt-1">Preview mode: <span className="font-semibold text-slate-800">Governed sender lanes</span></div>
          </div>
        </div>
        <div className="grid gap-3 xl:grid-cols-3">
          {senderPreviews.map((preview) => (
            <div key={preview.senderKey} className="rounded-2xl border bg-slate-50 p-4 text-sm text-slate-700">
              <div className="text-xs font-semibold uppercase tracking-wide text-slate-500">{preview.label}</div>
              <div className="mt-2 font-semibold text-slate-900">{preview.subjectPreview}</div>
              <div className="mt-2 text-xs text-slate-500">{preview.previewBody}</div>
              <div className="mt-3 rounded-xl border bg-white px-3 py-2 text-[11px] text-slate-600">{preview.governanceNote}</div>
              <div className="mt-3 flex flex-wrap gap-2">
                <button type="button" disabled={emailActionLoading || !readiness?.deliveryActive} onClick={() => sendSenderPreview(preview.senderKey)} className="rounded-xl border bg-white px-3 py-2 text-xs font-medium disabled:opacity-60">{emailActionLoading ? "Sending..." : "Send live preview to me"}</button>
              </div>
            </div>
          ))}
        </div>
      </section>

      <section className="rounded-2xl border bg-white p-5 shadow-sm">
        <div className="mb-4 flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
          <div>
            <h3 className="text-base font-semibold text-slate-900">Governed custom-domain readiness planning</h3>
            <p className="mt-1 text-sm text-slate-500">This is planning visibility only. Custom-domain sending remains a later governed rollout path rather than an open raw-SMTP workspace feature.</p>
          </div>
          <div className="rounded-2xl border bg-slate-50 px-4 py-3 text-xs text-slate-600">
            <div>Mode: <span className="font-semibold text-slate-800">{customDomainPlan?.mode === "PLANNED_GOVERNED_ROLLOUT" ? "Planned governed rollout" : "Planning"}</span></div>
          </div>
        </div>
        <div className="rounded-2xl border bg-slate-50 p-4 text-sm text-slate-700">
          <div className="font-medium text-slate-900">{customDomainPlan?.summary || readiness?.customDomainReadinessPlan?.summary}</div>
          <div className="mt-4 grid gap-3 lg:grid-cols-2">
            <div>
              <div className="text-xs font-semibold uppercase tracking-wide text-slate-500">Readiness checklist</div>
              <ul className="mt-2 space-y-2 text-sm text-slate-600">
                {(customDomainPlan?.checklist || readiness?.customDomainReadinessPlan?.checklist || []).map((item) => (
                  <li key={item} className="rounded-xl border bg-white px-3 py-2">{item}</li>
                ))}
              </ul>
            </div>
            <div>
              <div className="text-xs font-semibold uppercase tracking-wide text-slate-500">Supported later for</div>
              <div className="mt-2 flex flex-wrap gap-2">
                {(customDomainPlan?.supportedLaterFor || readiness?.customDomainReadinessPlan?.supportedLaterFor || []).map((item) => (
                  <span key={item} className="rounded-full border bg-white px-3 py-1 text-xs text-slate-600">{item}</span>
                ))}
              </div>
            </div>
          </div>
        </div>
      </section>

      <section className="rounded-2xl border bg-white p-5 shadow-sm">
        <div className="mb-4 flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
          <div>
            <h3 className="text-base font-semibold text-slate-900">Notification delivery governance</h3>
            <p className="mt-1 text-sm text-slate-500">Dispatch Spot currently uses a platform-managed sender model. Workspace users can govern notification behavior and reply-to usage, while raw SMTP ownership remains at the platform layer.</p>
          </div>
          <div className={`rounded-2xl border px-4 py-3 text-sm ${readiness?.smtpConfigured ? "border-emerald-200 bg-emerald-50 text-emerald-700" : "border-amber-200 bg-amber-50 text-amber-700"}`}>
            <div className="font-semibold">{readiness?.deliveryActive ? "SMTP active" : readiness?.smtpConfigured ? "SMTP prepared" : "SMTP not configured"}</div>
            <div className="mt-1">Delivery active: {readiness?.deliveryActive ? "Yes" : "No"}</div>
          </div>
        </div>
        <div className="grid gap-3 md:grid-cols-2 xl:grid-cols-4">
          <div className="rounded-2xl border bg-slate-50 p-4 text-sm text-slate-700"><div className="text-xs font-semibold uppercase tracking-wide text-slate-500">Host</div><div className="mt-1 font-medium">{readiness?.host || "Not configured"}</div></div>
          <div className="rounded-2xl border bg-slate-50 p-4 text-sm text-slate-700"><div className="text-xs font-semibold uppercase tracking-wide text-slate-500">Port</div><div className="mt-1 font-medium">{readiness?.port ?? 587}</div></div>
          <div className="rounded-2xl border bg-slate-50 p-4 text-sm text-slate-700"><div className="text-xs font-semibold uppercase tracking-wide text-slate-500">From</div><div className="mt-1 font-medium">{readiness?.fromEmail || "Not configured"}</div></div>
          <div className="rounded-2xl border bg-slate-50 p-4 text-sm text-slate-700"><div className="text-xs font-semibold uppercase tracking-wide text-slate-500">Mode</div><div className="mt-1 font-medium">{readiness?.deliveryMode === "active" ? "Active" : readiness?.deliveryMode === "prepared" ? "Prepared" : "Not configured"}</div></div>
        </div>
        <div className="mt-4 rounded-2xl border border-dashed bg-slate-50 px-4 py-3 text-xs text-slate-500">
          Missing fields: {readiness?.missingFields?.length ? readiness.missingFields.join(", ") : "None"}. Set <span className="font-semibold text-slate-700">SMTP_ENABLE_DELIVERY=true</span> after the SMTP credentials are in place when you are ready for live email sending.
        </div>
      </section>

      <section className="rounded-2xl border bg-white p-5 shadow-sm">
        <div className="mb-4 flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
          <div>
            <h3 className="text-base font-semibold text-slate-900">Auth email workflow surfaces</h3>
            <p className="mt-1 text-sm text-slate-500">Verification, password recovery, and confirmation notifications now run through the same SMTP delivery foundation and outbound email logging layer.</p>
          </div>
          <div className="rounded-2xl border bg-slate-50 px-4 py-3 text-xs text-slate-600">
            Verification: <span className="font-semibold text-slate-800">{authWorkflows?.emailVerificationReady ? "Ready" : "Pending"}</span> · Recovery: <span className="font-semibold text-slate-800">{authWorkflows?.passwordRecoveryReady ? "Ready" : "Pending"}</span> · Login challenge: <span className="font-semibold text-slate-800">{authWorkflows?.loginChallengeReady ? "Ready" : "Pending"}</span>
          </div>
        </div>
        <div className={`mb-4 rounded-2xl border px-4 py-3 text-sm ${user?.emailVerifiedAt ? 'border-emerald-200 bg-emerald-50 text-emerald-700' : 'border-amber-200 bg-amber-50 text-amber-700'}`}>
          <div className="font-semibold">{user?.emailVerifiedAt ? 'Your email is verified.' : 'Your email still needs verification.'}</div>
          <div className="mt-1 text-xs">{user?.emailVerifiedAt ? `Verified on ${new Date(user.emailVerifiedAt).toLocaleString()}.` : 'Verification state is now surfaced inside auth-protected pages so workspace users can confirm account trust status before relying on security-sensitive workflows.'}</div>
        </div>
        <div className="mb-4 grid gap-4 xl:grid-cols-2">
          <div className="rounded-2xl border bg-slate-50 p-4 text-xs text-slate-600">
            <div className="text-sm font-semibold text-slate-900">Email 2FA policy controls</div>
            <div className="mt-2">Policy enabled: <span className="font-semibold text-slate-800">{emailTwoFactorPolicy?.enabled ? 'Yes' : 'No'}</span></div>
            <div className="mt-1">SMTP delivery active: <span className="font-semibold text-slate-800">{emailTwoFactorPolicy?.deliveryActive ? 'Yes' : 'No'}</span></div>
            <div className="mt-1">Super Admin role policy: <span className="font-semibold text-slate-800">{emailTwoFactorPolicy?.requireForSuperAdmin ? 'Enabled' : 'Disabled'}</span></div>
            <div className="mt-1">Workspace Admin role policy: <span className="font-semibold text-slate-800">{emailTwoFactorPolicy?.requireForOrgAdmin ? 'Enabled' : 'Disabled'}</span></div>
            <div className="mt-2 text-[11px] text-slate-500">These controls are platform-governed in this package so role coverage is visible without exposing raw SMTP ownership to each workspace.</div>
          </div>
          <div className={`rounded-2xl border p-4 text-xs ${authSession?.challengeSatisfied ? 'border-blue-200 bg-blue-50 text-blue-800' : 'border-slate-200 bg-slate-50 text-slate-600'}`}>
            <div className="text-sm font-semibold">Protected session challenge state</div>
            <div className="mt-2">Current auth method: <span className="font-semibold">{authSession?.authMethod === 'EMAIL_2FA' ? 'Email 2FA' : 'Password only'}</span></div>
            <div className="mt-1">Challenge satisfied: <span className="font-semibold">{authSession?.challengeSatisfied ? 'Yes' : 'No'}</span></div>
            <div className="mt-1">Grace active: <span className="font-semibold">{authSession?.graceActive ? 'Yes' : 'No'}</span></div>
            <div className="mt-1">Applied policy source: <span className="font-semibold">{authSession?.emailTwoFactorPolicyKey ?? emailTwoFactorPolicy?.appliedPolicyKey ?? 'None'}</span></div>
            <div className="mt-1">Satisfied at: <span className="font-semibold">{authSession?.emailTwoFactorSatisfiedAt ? new Date(authSession.emailTwoFactorSatisfiedAt).toLocaleString() : 'Not recorded for this session'}</span></div>
            <div className="mt-1">Trusted until: <span className="font-semibold">{authSession?.trustedUntil ? new Date(authSession.trustedUntil).toLocaleString() : 'No trusted-session grace active'}</span></div>
            <div className="mt-1">Override state: <span className="font-semibold">{emailTwoFactorPolicy?.overrideState ?? 'NONE'}</span></div>
            <div className="mt-1">Override reason: <span className="font-semibold">{emailTwoFactorPolicy?.overrideReason ?? 'No per-user override applied'}</span></div>
            <div className="mt-1">Trusted-session revocation visible: <span className="font-semibold">{revocation?.revocationVisible ? 'Yes' : 'No'}</span></div>
            <div className="mt-3 flex flex-wrap gap-3">
              <button type="button" onClick={revokeTrustedSession} disabled={emailActionLoading || !revocation?.canRevokeTrustedSession} className="rounded-xl border px-4 py-2 text-sm font-semibold text-slate-700 disabled:cursor-not-allowed disabled:opacity-50">Revoke trusted session grace on this browser</button>
            </div>
          </div>
        </div>
        <div className="mt-4 rounded-2xl border bg-slate-50 p-4">
          <div className="text-sm font-semibold text-slate-900">Challenge audit visibility</div>
          <div className="mt-1 text-xs text-slate-500">Recent email 2FA challenge history for the signed-in user, including verification, lock, resend, and expiry outcomes.</div>
          <div className="mt-3 space-y-2">
            {challengeAudit.length ? challengeAudit.map((entry) => (
              <div key={entry.id} className="rounded-xl border bg-white px-3 py-3 text-xs text-slate-600">
                <div className="flex items-center justify-between gap-3">
                  <div className="font-semibold text-slate-800">{entry.status}</div>
                  <div>{new Date(entry.createdAt).toLocaleString()}</div>
                </div>
                <div className="mt-1">Resends: <span className="font-semibold">{entry.resendCount}</span> · Failed attempts: <span className="font-semibold">{entry.failedAttemptCount}</span></div>
                <div className="mt-1 text-[11px] text-slate-500">{entry.usedAt ? `Verified ${new Date(entry.usedAt).toLocaleString()}` : entry.lockedAt ? `Locked ${new Date(entry.lockedAt).toLocaleString()}` : `Expires ${new Date(entry.expiresAt).toLocaleString()}`}</div>
              </div>
            )) : <div className="rounded-xl border border-dashed bg-white px-3 py-6 text-xs text-slate-500">No recent email 2FA challenge events for this user.</div>}
          </div>
        </div>

        <div className="grid gap-4 xl:grid-cols-[1.2fr_0.8fr]">
          <div className="rounded-2xl border bg-slate-50 p-4">
            <div className="text-sm font-semibold text-slate-900">Live email actions</div>
            <p className="mt-1 text-xs text-slate-500">Use these to validate delivery and scaffolded auth email generation for the signed-in account.</p>
            <div className="mt-4 flex flex-wrap gap-3">
              <button type="button" onClick={() => runEmailAction("/api/notifications/test-email", "SMTP test email sent.")} disabled={emailActionLoading || !readiness?.deliveryActive} className="rounded-xl border px-4 py-2 text-sm font-semibold text-slate-700 disabled:cursor-not-allowed disabled:opacity-50">Send SMTP test email</button>
              <button type="button" onClick={() => runEmailAction("/api/auth/email-verification/request", user?.emailVerifiedAt ? "This email is already verified." : "Verification email prepared.")} disabled={emailActionLoading || Boolean(user?.emailVerifiedAt)} className="rounded-xl border px-4 py-2 text-sm font-semibold text-slate-700 disabled:cursor-not-allowed disabled:opacity-50">{user?.emailVerifiedAt ? 'Email verified' : 'Send verification email'}</button>
            </div>
            <div className="mt-3 rounded-xl border border-dashed bg-white px-3 py-3 text-xs text-slate-500">
              {emailActionMessage || "Password recovery is active through /api/auth/password-recovery/request, and successful password resets now queue a confirmation email back to the user."}
            </div>
          </div>
          <div className="rounded-2xl border bg-slate-50 p-4">
            <div className="text-sm font-semibold text-slate-900">Recent outbound email log</div>
            <div className="mt-3 space-y-2">
              {recentLogs.length ? recentLogs.map((log) => (
                <div key={log.id} className="rounded-xl border bg-white px-3 py-3 text-xs text-slate-600">
                  <div className="flex items-center justify-between gap-3">
                    <div className="font-semibold text-slate-800">{log.subject}</div>
                    <div className={`rounded-full px-2 py-0.5 ${log.status === "SENT" ? "bg-emerald-50 text-emerald-700" : log.status === "FAILED" ? "bg-red-50 text-red-700" : log.status === "SKIPPED" ? "bg-amber-50 text-amber-700" : "bg-slate-100 text-slate-700"}`}>{log.status}</div>
                  </div>
                  <div className="mt-1">{log.email} · {log.templateKey}</div>
                  <div className="mt-1 text-[11px] text-slate-500">{log.errorMessage || (log.sentAt ? `Sent ${new Date(log.sentAt).toLocaleString()}` : "Awaiting delivery or skipped by configuration.")}</div>
                </div>
              )) : <div className="rounded-xl border border-dashed bg-white px-3 py-6 text-xs text-slate-500">No outbound email logs yet for this user.</div>}
            </div>
          </div>
        </div>
      </section>

      <section className="rounded-2xl border bg-white p-5 shadow-sm">
        <div className="mb-4">
          <h3 className="text-base font-semibold text-slate-900">Assignment alert preferences</h3>
          <p className="mt-1 text-sm text-slate-500">These preferences now persist to your Dispatch Spot account so your notification center settings follow your signed-in user instead of staying trapped in a single browser.</p>
        </div>
        <div className="grid gap-3 md:grid-cols-2 xl:grid-cols-3">
          {[
            ["inApp", "In-app assignment visibility", "Keep assignments surfaced in queue-driven views."],
            ["emailDueToday", "Email when due today", "Use email lane for same-day assignment action prompts."],
            ["emailOverdue", "Email when overdue", "Allow escalation-ready overdue email prompts."],
            ["emailUrgent", "Email for urgent assignments", "Prioritize urgent or high-priority assignment alerts."],
            ["teamDigest", "Team digest lane", "Include you in shared assignment reminder digests."],
            ["smsReserved", "Future SMS escalation lane", "Reserve opt-in for future urgent SMS escalation support."],
          ].map(([key, label, desc]) => (
            <label key={String(key)} className="rounded-2xl border bg-slate-50 p-4">
              <div className="flex items-start justify-between gap-3">
                <div>
                  <div className="text-sm font-semibold text-slate-900">{label}</div>
                  <div className="mt-1 text-xs text-slate-500">{desc}</div>
                </div>
                <input type="checkbox" checked={Boolean(prefs[key as keyof NotificationPreferences])} onChange={(e) => updatePref(key as keyof NotificationPreferences, e.target.checked)} disabled={prefsSaving} />
              </div>
            </label>
          ))}
        </div>
        <div className="mt-4 rounded-2xl border border-dashed bg-slate-50 px-4 py-3 text-xs text-slate-500">
          Signed in as: <span className="font-semibold text-slate-700">{[user?.firstName, user?.lastName].filter(Boolean).join(" ") || user?.email || "Connected session"}</span>. {prefsMessage || "Preference changes save to your signed-in account in this package."}
        </div>
      </section>

      <section className="rounded-2xl border bg-white p-5 shadow-sm">
        <div className="mb-4">
          <h3 className="text-base font-semibold text-slate-900">Assignment inbox preview</h3>
          <p className="mt-1 text-sm text-slate-500">Unified preview of the work that will feed the future notification center inbox.</p>
        </div>
        {inboxPreview.length ? (
          <div className="space-y-3">
            {inboxPreview.map((item) => (
              <div key={item.id} className="rounded-2xl border p-4">
                <div className="flex flex-col gap-2 lg:flex-row lg:items-center lg:justify-between">
                  <div>
                    <a href={item.href} className="text-sm font-semibold text-slate-900 hover:underline">{item.targetLabel}</a>
                    <div className="mt-1 text-sm text-slate-600">{item.instructions || "No assignment instructions recorded."}</div>
                  </div>
                  <div className="text-xs text-slate-500">{item.reminderState.replaceAll("_", " ")} • {item.escalationState.replaceAll("_", " ")}</div>
                </div>
              </div>
            ))}
          </div>
        ) : (
          <div className="rounded-2xl border border-dashed px-4 py-8 text-sm text-slate-500">No assignment notifications are in preview right now.</div>
        )}
      </section>

      <div className="grid gap-4 xl:grid-cols-2">
        <AssignmentQueueCard title="My notification-backed queue" description="Queue visibility feeding your personal notification center foundation." items={myItems} summary={mySummary} emptyMessage="No personal assignment items are waiting right now." />
        <AssignmentQueueCard title="Team notification pressure" description="Workspace-wide items likely to appear in team reminder and escalation lanes." items={teamItems} summary={teamSummary} emptyMessage="No team assignment items require notification attention right now." />
      </div>
    </div>
  );
}
