"use client";

import { useEffect, useMemo, useState } from "react";
import { apiGet, apiPost } from "@/lib/api";

type LifecycleReviewStatus = "Ready" | "Check" | "Blocked" | "Locked";

type CheckRow = {
  key: string;
  label: string;
  status: LifecycleReviewStatus;
  detail: string;
  firstFix: string;
};

type LifecycleWorkspaceRow = {
  workspaceId: string;
  workspaceName: string;
  workspaceSlug: string;
  adminEmail: string;
  adminEmailVerified: boolean;
  isActive: boolean;
  workspaceTypeLabel: string;
  accountClassLabel: string;
  subscriptionId: string | null;
  subscriptionStatus: string;
  subscriptionStatusLabel: string;
  lifecycleBucket: string;
  planName: string;
  planCode: string;
  planFamily: string;
  planMonthlyPrice: number;
  billingProvider: string;
  billingMode: string;
  providerSyncStatus: string;
  billingProviderStatus: string;
  trialEndsAt: string | null;
  daysUntilTrialEnd: number | null;
  currentPeriodEndsAt: string | null;
  daysUntilCurrentPeriodEnd: number | null;
  lastProviderSyncAt: string | null;
  daysSinceProviderSync: number | null;
  stripeCustomerIdMasked: string;
  stripeSubscriptionIdMasked: string;
  stripeSubscriptionItemIdMasked: string;
  duplicateCustomerId: boolean;
  duplicateSubscriptionId: boolean;
  latestWebhook: null | {
    eventId: string;
    eventType: string;
    mode: string;
    livemode: boolean;
    verificationStatus: string;
    providerSyncOutcome: string;
    handled: boolean;
    createdAt: string | null;
  };
  readinessStatus: LifecycleReviewStatus;
  riskReasons: string[];
  reviewNeeded: boolean;
  hasLifecycleAuditNote: boolean;
  needsLifecycleAuditNote: boolean;
  auditNoteState: string;
  auditExportGroup: string;
  firstFix: string;
  workspaceAdminMessage: string;
  superAdminAction: string;
  lifecycleAuditNoteCount: number;
  lifecycleAuditNoteIsStale: boolean;
  lifecycleAuditNoteStaleThresholdDays: number;
  lifecycleAuditNoteDaysUntilStale: number | null;
  lifecycleAuditDueStatus: string;
  lifecycleAuditNoteCadence: string;
  lifecycleAuditNoteUrgency: string;
  lifecycleAuditNoteRefreshReason: string;
  latestLifecycleAuditNoteAt: string | null;
  latestLifecycleAuditNoteAgeDays: number | null;
  latestLifecycleAuditNote: string | null;
  latestLifecycleAuditFirstFix: string | null;
  warningAcknowledgementCount: number;
  warningAcknowledgementState: string;
  currentWarningNeedsAcknowledgement: boolean;
  warningAcknowledgementNeedsAction: boolean;
  warningAcknowledgementContext: string;
  warningAcknowledgementSignalBasis: string[];
  warningAcknowledgementCurrentStatusKey: string;
  warningAcknowledgementCurrentSeverity: string;
  warningAcknowledgementCurrentSignalSignature: string;
  warningAcknowledgementLatestSignalSignature: string;
  warningAcknowledgementChangedReasons: string[];
  warningAcknowledgementMatchProfile?: {
    fingerprintMatch: boolean;
    statusKeyMatch: boolean;
    severityMatch: boolean;
    subscriptionStatusMatch: boolean;
    providerSyncStatusMatch: boolean;
    planNameMatch: boolean;
    signalKeysMatch: boolean;
    isCurrentMatch: boolean;
    changedReasons: string[];
  };
  latestWarningAcknowledgementAt: string | null;
  latestWarningAcknowledgementTitle: string | null;
  latestWarningAcknowledgementSeverity: string | null;
  latestWarningAcknowledgementStatusKey: string | null;
  latestWarningAcknowledgementStatusLabel: string | null;
  latestWarningAcknowledgementSignalKeys: string[];
  latestWarningAcknowledgementPlanName: string | null;
  latestWarningAcknowledgementSubscriptionStatus: string | null;
  latestWarningAcknowledgementProviderSyncStatus: string | null;
  activationEvidenceState: string;
  activationEvidenceCloseoutNeeded: boolean;
  activationEvidenceIssues: string[];
  activationEvidenceNextStep: string;
};

type WebhookReviewRow = {
  id: string;
  eventId: string;
  eventType: string;
  mode: string;
  livemode: boolean;
  verificationStatus: string;
  handled: boolean;
  providerSyncOutcome: string;
  workspaceSubscriptionStatus: string;
  customerIdMasked: string;
  subscriptionIdMasked: string;
  subscriptionItemIdMasked: string;
  createdAt: string | null;
  reviewResult: string;
};

type AuditRow = {
  id: string;
  action: string;
  summary: string;
  targetType: string | null;
  targetId: string | null;
  createdAt: string | null;
};

type LifecycleAuditNoteRow = {
  id: string;
  createdAt: string | null;
  workspaceId: string;
  workspaceName: string;
  lifecycleStatus: string;
  readinessStatus: string;
  note: string;
  firstFix: string;
  riskReasons: string[];
};

type WarningAcknowledgementRow = {
  id: string;
  createdAt: string | null;
  workspaceId: string;
  workspaceName: string;
  workspaceSlug: string;
  workspaceTypeLabel: string;
  accountClassLabel: string;
  warningTitle: string;
  warningSeverity: string;
  warningStatusKey: string;
  warningStatusLabel: string;
  subscriptionStatus: string;
  providerSyncStatus: string;
  planName: string;
  signalKeys: string[];
  signalCount: number;
  acknowledgedFrom: string;
  workspaceNextStep: string;
  superAdminNextStep: string;
  accessStatement: string;
  billingRecordsStatement: string;
  acknowledgementEffect: string;
  warningFingerprint?: string;
  warningFingerprintVersion?: string;
  signalKeySignature?: string;
  warningMatchBasis?: Record<string, unknown>;
};

type LifecycleAuditThresholds = {
  blockedStaleDays: number;
  checkStaleDays: number;
  readyStaleDays: number;
  historyStaleDays: number;
  dueSoonWindowDays: number;
};

type LifecycleAuditThresholdSetting = {
  key: keyof LifecycleAuditThresholds;
  label: string;
  environmentVariable: string;
  defaultDays: number;
  activeDays: number;
  minDays: number;
  maxDays: number;
  rawValue: string;
  source: string;
  isEnvironmentOverride: boolean;
  isInvalidOverride: boolean;
  wasClamped: boolean;
  appliesTo: string;
  reviewUse: string;
  reviewOnlyEffect: string;
};

type LifecycleAuditThresholdConfiguration = {
  activeThresholds: LifecycleAuditThresholds;
  settings: LifecycleAuditThresholdSetting[];
  environmentOverrideCount: number;
  invalidOverrideCount: number;
  dueSoonWindowDays: number;
  reviewOnlyEffect: string;
};

type SubscriptionLifecycleBillingSyncReview = {
  summary: {
    readinessStatus: LifecycleReviewStatus;
    totalWorkspaces: number;
    subscribedWorkspaces: number;
    missingSubscriptionCount: number;
    trialCount: number;
    activeCount: number;
    pastDueCount: number;
    pausedCount: number;
    canceledCount: number;
    trialEndingSoon: number;
    trialExpired: number;
    syncReadyCount: number;
    syncNeedsReviewCount: number;
    syncBlockedCount: number;
    stripeMappedCount: number;
    duplicateCustomerIdCount: number;
    duplicateSubscriptionIdCount: number;
    staleSyncCount: number;
    liveModeWorkspaceCount: number;
    reviewNeededWithoutAuditNoteCount: number;
    staleLifecycleAuditNoteCount: number;
    lifecycleAuditNoteDueSoonCount: number;
    lifecycleAuditNoteCount: number;
    lifecycleRowsWithAuditNotes: number;
    warningAcknowledgementCount: number;
    warningAcknowledgementNeedsActionCount: number;
    warningAcknowledgedCurrentStatusCount: number;
    warningChangedSinceAcknowledgementCount: number;
    evidenceCloseoutGapCount: number;
    evidenceCloseoutWorkspaceRows: number;
    recentWebhookEvents: number;
    firstFix: string;
  };
  environment: {
    billingStatusSyncReviewOnly: boolean;
    billingStatusMutationRequested: boolean;
    webhookSubscriptionSyncRequested: boolean;
    paymentCollectionRequested: boolean;
    customerPortalRequested: boolean;
    hardBillingGateRequested: boolean;
    subscriptionSyncReviewOnly: boolean;
    trialToPaidReviewOnly: boolean;
    lifecycleAuditThresholds: LifecycleAuditThresholds;
    lifecycleAuditThresholdConfiguration: LifecycleAuditThresholdConfiguration;
  };
  checks: CheckRow[];
  lifecycleSummary: Array<{ status: string; label: string; total: number; ready: number; needsReview: number; blocked: number }>;
  providerSummary: Array<{ provider: string; total: number; ready: number; needsReview: number; blocked: number }>;
  auditNoteCoverageSummary: {
    totalWorkspaceRows: number;
    reviewNeededRows: number;
    rowsWithLifecycleAuditNotes: number;
    reviewNeededWithLifecycleAuditNotes: number;
    reviewNeededWithoutLifecycleAuditNotes: number;
    staleLifecycleAuditNoteRows: number;
    auditDueSoonRows: number;
    auditNotNeededRows: number;
    warningAcknowledgementRows: number;
    staleThresholds: LifecycleAuditThresholds;
    thresholdConfiguration: LifecycleAuditThresholdConfiguration;
    byReadiness: Array<{ key: string; total: number; withNotes: number; missingNotes: number; staleNotes: number }>;
    byLifecycle: Array<{ key: string; total: number; withNotes: number; missingNotes: number; staleNotes: number }>;
    byDueStatus: Array<{ key: string; total: number }>;
    byCadence: Array<{ key: string; total: number }>;
    firstFix: string;
  };
  warningAcknowledgementSummary: {
    totalWorkspaceRows: number;
    totalAcknowledgements: number;
    rowsWithAcknowledgements: number;
    rowsWithoutAcknowledgements: number;
    rowsNeedingAcknowledgement: number;
    rowsAcknowledgedCurrentStatus: number;
    rowsChangedSinceAcknowledgement: number;
    byState: Array<{ key: string; total: number }>;
    bySeverity: Array<{ key: string; total: number }>;
    byStatus: Array<{ key: string; total: number }>;
    byChangedReason: Array<{ key: string; total: number }>;
    firstFix: string;
  };
  activationEvidenceCloseout: {
    overallStatus: LifecycleReviewStatus;
    readyEvidenceRows: number;
    checkEvidenceRows: number;
    blockedEvidenceRows: number;
    evidenceGapCount: number;
    workspaceRowsNeedingCloseout: number;
    rows: Array<{
      key: string;
      label: string;
      status: LifecycleReviewStatus;
      evidenceGapCount: number;
      detail: string;
      firstFix: string;
      reviewOnlyEffect: string;
    }>;
    exportManifest: Array<{ key: string; label: string; filename: string; includes: string }>;
    firstFix: string;
    reviewOnlyEffect: string;
  };
  workspaceRows: LifecycleWorkspaceRow[];
  webhookReviewRows: WebhookReviewRow[];
  recentSyncAuditEvents: AuditRow[];
  lifecycleAuditNotes: LifecycleAuditNoteRow[];
  warningAcknowledgementHistory: WarningAcknowledgementRow[];
  guardrails: {
    reviewOnly: boolean;
    subscriptionStatusMutationActive: boolean;
    providerStatusWritten: boolean;
    paymentCollectionActive: boolean;
    customerPortalActive: boolean;
    hardBillingGatesChanged: boolean;
    brokerDistributionChanged: boolean;
    ownedPortalRulesChanged: boolean;
    internalLoadBoardAccessChanged: boolean;
  };
};

const statusOptions = ["All", "Ready", "Check", "Blocked", "Locked"] as const;
const lifecycleOptions = ["All", "Trial", "Active", "Past due", "Paused", "Canceled", "Missing subscription"] as const;
const providerOptions = ["All", "NONE", "STRIPE", "MANUAL"] as const;
const riskOptions = ["All", "Trial ending soon", "Trial expired", "Missing subscription", "Duplicate Stripe ID", "Past due", "Live mode", "Stale provider sync"] as const;
const auditOptions = ["All", "Needs note", "Has note", "Stale note", "Due soon", "No note needed"] as const;
const acknowledgementOptions = ["All", "Needs acknowledgement", "Acknowledged current status", "Changed since acknowledgement", "Has acknowledgement history", "No acknowledgement history", "History only", "No warning needed"] as const;
const evidenceOptions = ["All", "Evidence current", "Needs evidence closeout", "Missing audit note", "Stale audit note", "Audit due soon", "Warning acknowledgement action", "Lifecycle review issue"] as const;

function statusClasses(status: LifecycleReviewStatus | string) {
  if (status === "Ready") return "bg-emerald-100 text-emerald-700";
  if (status === "Blocked") return "bg-rose-100 text-rose-700";
  if (status === "Locked") return "bg-blue-100 text-blue-700";
  return "bg-amber-100 text-amber-700";
}

function borderClasses(status: LifecycleReviewStatus) {
  if (status === "Ready") return "border-emerald-100";
  if (status === "Blocked") return "border-rose-100";
  if (status === "Locked") return "border-blue-100";
  return "border-amber-100";
}

function csvEscape(value: unknown) {
  const text = Array.isArray(value) ? value.join("; ") : String(value ?? "");
  if (/[",\n]/.test(text)) return `"${text.replace(/"/g, '""')}"`;
  return text;
}

function downloadCsv(filename: string, headers: string[], rows: unknown[][]) {
  const csv = [headers, ...rows].map((row) => row.map(csvEscape).join(",")).join("\n");
  const blob = new Blob([csv], { type: "text/csv;charset=utf-8" });
  const url = URL.createObjectURL(blob);
  const link = document.createElement("a");
  link.href = url;
  link.download = filename;
  document.body.appendChild(link);
  link.click();
  link.remove();
  URL.revokeObjectURL(url);
}

function dateTime(value?: string | null) {
  if (!value) return "Not recorded";
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return "Not recorded";
  return date.toLocaleString();
}

function money(value: number) {
  return `$${Number(value || 0).toLocaleString(undefined, { minimumFractionDigits: 0, maximumFractionDigits: 2 })}`;
}

function trialLabel(row: LifecycleWorkspaceRow) {
  if (row.subscriptionStatus !== "TRIAL") return row.subscriptionStatusLabel;
  if (row.daysUntilTrialEnd === null) return "Trial date missing";
  if (row.daysUntilTrialEnd < 0) return `Trial expired ${Math.abs(row.daysUntilTrialEnd)} days ago`;
  if (row.daysUntilTrialEnd === 0) return "Trial ends today";
  return `Trial ends in ${row.daysUntilTrialEnd} days`;
}

function searchText(...values: Array<unknown>) {
  return values.filter(Boolean).join(" ").toLowerCase();
}

function lifecycleFilterKey(value: string) {
  if (value === "Missing subscription") return "NONE";
  return value.toUpperCase().replace(/ /g, "_");
}

export function AdminSubscriptionLifecycleBillingSyncPanel() {
  const [review, setReview] = useState<SubscriptionLifecycleBillingSyncReview | null>(null);
  const [loaded, setLoaded] = useState(false);
  const [message, setMessage] = useState<string | null>(null);
  const [statusFilter, setStatusFilter] = useState<(typeof statusOptions)[number]>("All");
  const [lifecycleFilter, setLifecycleFilter] = useState<(typeof lifecycleOptions)[number]>("All");
  const [providerFilter, setProviderFilter] = useState<(typeof providerOptions)[number]>("All");
  const [riskFilter, setRiskFilter] = useState<(typeof riskOptions)[number]>("All");
  const [auditFilter, setAuditFilter] = useState<(typeof auditOptions)[number]>("All");
  const [acknowledgementFilter, setAcknowledgementFilter] = useState<(typeof acknowledgementOptions)[number]>("All");
  const [evidenceFilter, setEvidenceFilter] = useState<(typeof evidenceOptions)[number]>("All");
  const [search, setSearch] = useState("");
  const [noteWorkspaceId, setNoteWorkspaceId] = useState<string | null>(null);
  const [noteDraft, setNoteDraft] = useState("");
  const [savingNote, setSavingNote] = useState(false);
  const [auditMessage, setAuditMessage] = useState<string | null>(null);

  useEffect(() => {
    let cancelled = false;

    async function loadReview() {
      try {
        setMessage(null);
        const data = await apiGet<SubscriptionLifecycleBillingSyncReview>("/api/admin/subscription-lifecycle/review");
        if (!cancelled) setReview(data);
      } catch (error: any) {
        if (!cancelled) setMessage(error?.message ?? "Failed to load subscription lifecycle review.");
      } finally {
        if (!cancelled) setLoaded(true);
      }
    }

    void loadReview();

    return () => {
      cancelled = true;
    };
  }, []);

  const needle = search.trim().toLowerCase();

  const filteredRows = useMemo(() => {
    return (review?.workspaceRows ?? []).filter((row) => {
      if (statusFilter !== "All" && row.readinessStatus !== statusFilter) return false;
      if (lifecycleFilter !== "All" && row.lifecycleBucket !== lifecycleFilter) return false;
      if (providerFilter !== "All" && row.billingProvider !== providerFilter) return false;
      if (riskFilter === "Trial ending soon" && !(row.subscriptionStatus === "TRIAL" && row.daysUntilTrialEnd !== null && row.daysUntilTrialEnd >= 0 && row.daysUntilTrialEnd <= 7)) return false;
      if (riskFilter === "Trial expired" && !(row.subscriptionStatus === "TRIAL" && row.daysUntilTrialEnd !== null && row.daysUntilTrialEnd < 0)) return false;
      if (riskFilter === "Missing subscription" && row.subscriptionStatus !== "NONE") return false;
      if (riskFilter === "Duplicate Stripe ID" && !row.duplicateCustomerId && !row.duplicateSubscriptionId) return false;
      if (riskFilter === "Past due" && row.subscriptionStatus !== "PAST_DUE") return false;
      if (riskFilter === "Live mode" && row.billingMode !== "LIVE") return false;
      if (riskFilter === "Stale provider sync" && !(row.billingProvider === "STRIPE" && (row.daysSinceProviderSync === null || row.daysSinceProviderSync > 30))) return false;
      if (auditFilter === "Needs note" && !row.needsLifecycleAuditNote) return false;
      if (auditFilter === "Has note" && !row.hasLifecycleAuditNote) return false;
      if (auditFilter === "Stale note" && row.auditNoteState !== "Stale note") return false;
      if (auditFilter === "Due soon" && row.lifecycleAuditDueStatus !== "Due soon") return false;
      if (auditFilter === "No note needed" && row.auditNoteState !== "Not needed") return false;
      if (acknowledgementFilter === "Needs acknowledgement" && row.warningAcknowledgementState !== "Needs acknowledgement") return false;
      if (acknowledgementFilter === "Acknowledged current status" && row.warningAcknowledgementState !== "Acknowledged current status") return false;
      if (acknowledgementFilter === "Changed since acknowledgement" && row.warningAcknowledgementState !== "Changed since acknowledgement") return false;
      if (acknowledgementFilter === "Has acknowledgement history" && row.warningAcknowledgementCount === 0) return false;
      if (acknowledgementFilter === "No acknowledgement history" && row.warningAcknowledgementCount > 0) return false;
      if (acknowledgementFilter === "History only" && row.warningAcknowledgementState !== "History only") return false;
      if (acknowledgementFilter === "No warning needed" && row.warningAcknowledgementState !== "No warning needed") return false;
      if (evidenceFilter === "Evidence current" && row.activationEvidenceState !== "Evidence current") return false;
      if (evidenceFilter === "Needs evidence closeout" && !row.activationEvidenceCloseoutNeeded) return false;
      if (evidenceFilter === "Missing audit note" && !row.activationEvidenceIssues.includes("Missing lifecycle audit note")) return false;
      if (evidenceFilter === "Stale audit note" && !row.activationEvidenceIssues.includes("Stale lifecycle audit note")) return false;
      if (evidenceFilter === "Audit due soon" && !row.activationEvidenceIssues.includes("Lifecycle audit note due soon")) return false;
      if (evidenceFilter === "Warning acknowledgement action" && !row.warningAcknowledgementNeedsAction) return false;
      if (evidenceFilter === "Lifecycle review issue" && !row.activationEvidenceIssues.some((issue) => issue.includes("Lifecycle"))) return false;
      if (!needle) return true;
      return searchText(
        row.workspaceName,
        row.workspaceSlug,
        row.adminEmail,
        row.workspaceTypeLabel,
        row.accountClassLabel,
        row.subscriptionStatusLabel,
        row.lifecycleBucket,
        row.planName,
        row.planFamily,
        row.billingProvider,
        row.billingMode,
        row.providerSyncStatus,
        row.billingProviderStatus,
        row.latestWebhook?.eventType,
        row.riskReasons,
        row.auditNoteState,
        row.auditExportGroup,
        row.latestLifecycleAuditNote,
        row.lifecycleAuditDueStatus,
        row.lifecycleAuditNoteCadence,
        row.lifecycleAuditNoteUrgency,
        row.lifecycleAuditNoteRefreshReason,
        row.warningAcknowledgementState,
        row.warningAcknowledgementContext,
        row.warningAcknowledgementCurrentStatusKey,
        row.warningAcknowledgementCurrentSeverity,
        row.warningAcknowledgementCurrentSignalSignature,
        row.warningAcknowledgementLatestSignalSignature,
        row.warningAcknowledgementChangedReasons,
        row.latestWarningAcknowledgementTitle,
        row.latestWarningAcknowledgementSeverity,
        row.latestWarningAcknowledgementStatusLabel,
        row.latestWarningAcknowledgementSignalKeys,
        row.activationEvidenceState,
        row.activationEvidenceIssues,
        row.activationEvidenceNextStep,
        row.firstFix,
      ).includes(needle);
    });
  }, [review, statusFilter, lifecycleFilter, providerFilter, riskFilter, auditFilter, acknowledgementFilter, evidenceFilter, needle]);

  const webhookRows = useMemo(() => {
    return (review?.webhookReviewRows ?? []).filter((row) => {
      if (!needle) return true;
      return searchText(row.eventId, row.eventType, row.mode, row.verificationStatus, row.providerSyncOutcome, row.workspaceSubscriptionStatus, row.reviewResult, row.customerIdMasked, row.subscriptionIdMasked).includes(needle);
    });
  }, [review, needle]);

  const filteredAuditNotes = useMemo(() => {
    return (review?.lifecycleAuditNotes ?? []).filter((note) => {
      if (statusFilter !== "All" && note.readinessStatus !== statusFilter) return false;
      if (lifecycleFilter !== "All" && note.lifecycleStatus !== lifecycleFilterKey(lifecycleFilter)) return false;
      if (!needle) return true;
      return searchText(note.workspaceName, note.lifecycleStatus, note.readinessStatus, note.riskReasons, note.firstFix, note.note).includes(needle);
    });
  }, [review, statusFilter, lifecycleFilter, needle]);

  const acknowledgementStateByWorkspace = useMemo(() => {
    const map = new Map<string, string>();
    for (const row of review?.workspaceRows ?? []) map.set(row.workspaceId, row.warningAcknowledgementState);
    return map;
  }, [review]);

  const filteredAcknowledgements = useMemo(() => {
    return (review?.warningAcknowledgementHistory ?? []).filter((item) => {
      const workspaceAcknowledgementState = acknowledgementStateByWorkspace.get(item.workspaceId) ?? "Has acknowledgement history";
      if (["Needs acknowledgement", "No acknowledgement history", "No warning needed"].includes(acknowledgementFilter)) return false;
      if (["Acknowledged current status", "Changed since acknowledgement", "History only"].includes(acknowledgementFilter) && workspaceAcknowledgementState !== acknowledgementFilter) return false;
      if (!needle) return true;
      return searchText(
        item.workspaceName,
        item.workspaceSlug,
        item.warningTitle,
        item.warningSeverity,
        item.warningStatusLabel,
        item.subscriptionStatus,
        item.providerSyncStatus,
        item.planName,
        item.signalKeys,
        item.workspaceNextStep,
        item.superAdminNextStep,
        item.acknowledgementEffect,
        item.warningFingerprintVersion,
        item.signalKeySignature,
      ).includes(needle);
    });
  }, [review, acknowledgementStateByWorkspace, acknowledgementFilter, needle]);

  function resetFilters() {
    setStatusFilter("All");
    setLifecycleFilter("All");
    setProviderFilter("All");
    setRiskFilter("All");
    setAuditFilter("All");
    setAcknowledgementFilter("All");
    setEvidenceFilter("All");
    setSearch("");
  }

  function exportLifecycleRows() {
    downloadCsv(
      "dispatchspot-subscription-lifecycle-review.csv",
      ["Workspace", "Slug", "Admin email", "Workspace type", "Account class", "Lifecycle", "Readiness", "Evidence state", "Evidence issues", "Evidence next step", "Audit note state", "Audit cadence", "Audit urgency", "Audit due status", "Stale threshold days", "Days until stale", "Audit note count", "Latest audit note", "Latest audit note age days", "Warning acknowledgement count", "Acknowledgement state", "Current warning type", "Current warning severity", "Current warning signal signature", "Latest acknowledgement signal signature", "Changed reasons", "Acknowledgement context", "Latest warning acknowledgement", "Latest acknowledgement severity", "Latest acknowledgement status", "Latest acknowledgement signals", "Plan", "Monthly price", "Provider", "Mode", "Sync status", "Provider status", "Trial end", "Current period end", "Last provider sync", "Customer", "Subscription", "Latest webhook", "Risks", "First fix", "Workspace Admin message"],
      filteredRows.map((row) => [
        row.workspaceName,
        row.workspaceSlug,
        row.adminEmail,
        row.workspaceTypeLabel,
        row.accountClassLabel,
        row.subscriptionStatusLabel,
        row.readinessStatus,
        row.activationEvidenceState,
        row.activationEvidenceIssues,
        row.activationEvidenceNextStep,
        row.auditNoteState,
        row.lifecycleAuditNoteCadence,
        row.lifecycleAuditNoteUrgency,
        row.lifecycleAuditDueStatus,
        row.lifecycleAuditNoteStaleThresholdDays,
        row.lifecycleAuditNoteDaysUntilStale ?? "",
        row.lifecycleAuditNoteCount,
        row.latestLifecycleAuditNote ?? "",
        row.latestLifecycleAuditNoteAgeDays ?? "",
        row.warningAcknowledgementCount,
        row.warningAcknowledgementState,
        row.warningAcknowledgementCurrentStatusKey,
        row.warningAcknowledgementCurrentSeverity,
        row.warningAcknowledgementCurrentSignalSignature,
        row.warningAcknowledgementLatestSignalSignature,
        row.warningAcknowledgementChangedReasons,
        row.warningAcknowledgementContext,
        row.latestWarningAcknowledgementTitle ?? "",
        row.latestWarningAcknowledgementSeverity ?? "",
        row.latestWarningAcknowledgementStatusLabel ?? "",
        row.latestWarningAcknowledgementSignalKeys,
        row.planName,
        row.planMonthlyPrice,
        row.billingProvider,
        row.billingMode,
        row.providerSyncStatus,
        row.billingProviderStatus,
        dateTime(row.trialEndsAt),
        dateTime(row.currentPeriodEndsAt),
        dateTime(row.lastProviderSyncAt),
        row.stripeCustomerIdMasked,
        row.stripeSubscriptionIdMasked,
        row.latestWebhook?.eventType ?? "",
        row.riskReasons,
        row.firstFix,
        row.workspaceAdminMessage,
      ]),
    );
  }

  function exportWebhookRows() {
    downloadCsv(
      "dispatchspot-review-only-webhook-billing-sync-events.csv",
      ["Created", "Event", "Event ID", "Mode", "Live", "Verification", "Handled", "Provider outcome", "Workspace status", "Customer", "Subscription", "Item", "Review result"],
      webhookRows.map((row) => [
        dateTime(row.createdAt),
        row.eventType,
        row.eventId,
        row.mode,
        row.livemode ? "yes" : "no",
        row.verificationStatus,
        row.handled ? "yes" : "no",
        row.providerSyncOutcome,
        row.workspaceSubscriptionStatus,
        row.customerIdMasked,
        row.subscriptionIdMasked,
        row.subscriptionItemIdMasked,
        row.reviewResult,
      ]),
    );
  }

  function exportFilteredAuditNotes() {
    downloadCsv(
      "dispatchspot-filtered-lifecycle-sync-audit-notes.csv",
      ["Created", "Workspace", "Lifecycle", "Readiness", "Risk reasons", "First fix", "Note"],
      filteredAuditNotes.map((note) => [dateTime(note.createdAt), note.workspaceName, note.lifecycleStatus, note.readinessStatus, note.riskReasons, note.firstFix, note.note]),
    );
  }

  function exportRowsNeedingAuditNotes() {
    const rows = filteredRows.filter((row) => row.needsLifecycleAuditNote);
    downloadCsv(
      "dispatchspot-lifecycle-rows-needing-audit-notes.csv",
      ["Workspace", "Slug", "Lifecycle", "Readiness", "Risks", "First fix", "Admin email", "Plan", "Provider", "Mode", "Sync status"],
      rows.map((row) => [row.workspaceName, row.workspaceSlug, row.subscriptionStatusLabel, row.readinessStatus, row.riskReasons, row.firstFix, row.adminEmail, row.planName, row.billingProvider, row.billingMode, row.providerSyncStatus]),
    );
  }

  function exportWarningAcknowledgements() {
    downloadCsv(
      "dispatchspot-warning-acknowledgement-context.csv",
      ["Created", "Workspace", "Slug", "Warning", "Severity", "Warning status", "Subscription status", "Plan", "Provider sync", "Signals", "Signal signature", "Fingerprint version", "Match basis", "Access statement", "Billing Records statement", "Acknowledged from", "Workspace next step", "Super Admin next step", "Effect"],
      filteredAcknowledgements.map((item) => [
        dateTime(item.createdAt),
        item.workspaceName,
        item.workspaceSlug,
        item.warningTitle,
        item.warningSeverity,
        item.warningStatusLabel,
        item.subscriptionStatus,
        item.planName,
        item.providerSyncStatus,
        item.signalKeys,
        item.signalKeySignature ?? "",
        item.warningFingerprintVersion ?? "",
        JSON.stringify(item.warningMatchBasis ?? {}),
        item.accessStatement,
        item.billingRecordsStatement,
        item.acknowledgedFrom,
        item.workspaceNextStep,
        item.superAdminNextStep,
        item.acknowledgementEffect,
      ]),
    );
  }

  function exportThresholdConfiguration() {
    if (!review) return;
    downloadCsv(
      "dispatchspot-lifecycle-audit-threshold-configuration.csv",
      ["Setting", "Environment variable", "Active days", "Default days", "Source", "Raw value", "Allowed range", "Invalid override", "Clamped", "Applies to", "Review use", "Review-only effect"],
      review.environment.lifecycleAuditThresholdConfiguration.settings.map((setting) => [
        setting.label,
        setting.environmentVariable,
        setting.activeDays,
        setting.defaultDays,
        setting.source,
        setting.rawValue || "not set",
        `${setting.minDays}-${setting.maxDays} days`,
        setting.isInvalidOverride ? "yes" : "no",
        setting.wasClamped ? "yes" : "no",
        setting.appliesTo,
        setting.reviewUse,
        setting.reviewOnlyEffect,
      ]),
    );
  }

  function exportEvidenceCloseout() {
    if (!review) return;
    const closeoutRows = review.activationEvidenceCloseout.rows.map((row) => [
      "Closeout section",
      row.label,
      row.key,
      row.status,
      row.evidenceGapCount,
      row.detail,
      row.firstFix,
      row.reviewOnlyEffect,
    ]);
    const manifestRows = review.activationEvidenceCloseout.exportManifest.map((item) => [
      "Export manifest",
      item.label,
      item.key,
      "Ready",
      0,
      item.includes,
      item.filename,
      "Export-only evidence; no subscription or access behavior changes.",
    ]);
    const workspaceRows = filteredRows
      .filter((row) => row.activationEvidenceCloseoutNeeded)
      .map((row) => [
        "Workspace evidence gap",
        row.workspaceName,
        row.workspaceSlug,
        row.activationEvidenceState,
        row.activationEvidenceIssues,
        row.riskReasons,
        row.activationEvidenceNextStep,
        "Workspace evidence closeout is review-only and does not block workspace activity.",
      ]);
    downloadCsv(
      "dispatchspot-final-warning-audit-evidence-closeout.csv",
      ["Record type", "Section or workspace", "Key or slug", "Status or state", "Gap count or issues", "Detail or risk reasons", "First fix or next step", "Review-only effect"],
      [...closeoutRows, ...manifestRows, ...workspaceRows],
    );
  }

  function beginAuditNote(row: LifecycleWorkspaceRow) {
    setNoteWorkspaceId(row.workspaceId);
    setNoteDraft("");
    setAuditMessage(null);
  }

  async function saveAuditNote(row: LifecycleWorkspaceRow) {
    const note = noteDraft.trim();
    if (!note) {
      setAuditMessage("Enter a lifecycle review note before saving.");
      return;
    }
    setSavingNote(true);
    setAuditMessage(null);
    try {
      await apiPost<{ auditNote: LifecycleAuditNoteRow }>("/api/admin/subscription-lifecycle/audit-note", {
        workspaceId: row.workspaceId,
        note,
      });
      const data = await apiGet<SubscriptionLifecycleBillingSyncReview>("/api/admin/subscription-lifecycle/review");
      setReview(data);
      setNoteWorkspaceId(null);
      setNoteDraft("");
      setAuditMessage("Lifecycle sync audit note saved. No subscription or billing state was changed.");
    } catch (error: any) {
      setAuditMessage(error?.message ?? "Failed to save lifecycle sync audit note.");
    } finally {
      setSavingNote(false);
    }
  }

  if (!loaded) {
    return <section className="rounded-2xl border bg-white p-6 text-sm text-slate-500 shadow-sm">Loading subscription lifecycle and billing sync review...</section>;
  }

  if (message) {
    return <section className="rounded-2xl border border-rose-100 bg-rose-50 p-6 text-sm text-rose-700 shadow-sm">{message}</section>;
  }

  if (!review) return null;

  return (
    <section className="space-y-5 rounded-2xl border border-slate-200 bg-white p-6 shadow-sm">
      <div className="flex flex-col gap-3 xl:flex-row xl:items-start xl:justify-between">
        <div>
          <div className="text-xs font-semibold uppercase tracking-[0.18em] text-blue-700">Subscription lifecycle</div>
          <h2 className="mt-1 text-xl font-semibold text-slate-900">Review-only billing sync and lifecycle status</h2>
          <p className="mt-1 max-w-5xl text-sm leading-6 text-slate-600">
            Review trials, active subscriptions, past-due states, provider sync posture, Stripe ID mapping, and webhook billing-sync signals before any payment collection, customer portal session, hard billing gate, or subscription mutation is activated.
          </p>
        </div>
        <span className={`w-fit rounded-full px-3 py-1 text-xs font-semibold ${statusClasses(review.summary.readinessStatus)}`}>{review.summary.readinessStatus}</span>
      </div>

      <div className="grid gap-3 md:grid-cols-4 xl:grid-cols-12">
        <div className="rounded-xl border border-slate-100 bg-slate-50 p-3"><div className="text-xs font-semibold text-slate-500">Workspaces</div><div className="mt-1 text-2xl font-semibold text-slate-900">{review.summary.totalWorkspaces}</div></div>
        <div className="rounded-xl border border-slate-100 bg-slate-50 p-3"><div className="text-xs font-semibold text-slate-500">Subscribed</div><div className="mt-1 text-2xl font-semibold text-slate-900">{review.summary.subscribedWorkspaces}</div></div>
        <div className="rounded-xl border border-slate-100 bg-slate-50 p-3"><div className="text-xs font-semibold text-slate-500">Trial</div><div className="mt-1 text-2xl font-semibold text-slate-900">{review.summary.trialCount}</div></div>
        <div className="rounded-xl border border-slate-100 bg-slate-50 p-3"><div className="text-xs font-semibold text-slate-500">Active</div><div className="mt-1 text-2xl font-semibold text-slate-900">{review.summary.activeCount}</div></div>
        <div className="rounded-xl border border-slate-100 bg-slate-50 p-3"><div className="text-xs font-semibold text-slate-500">Past due</div><div className="mt-1 text-2xl font-semibold text-slate-900">{review.summary.pastDueCount}</div></div>
        <div className="rounded-xl border border-slate-100 bg-slate-50 p-3"><div className="text-xs font-semibold text-slate-500">Needs review</div><div className="mt-1 text-2xl font-semibold text-slate-900">{review.summary.syncNeedsReviewCount}</div></div>
        <div className="rounded-xl border border-slate-100 bg-slate-50 p-3"><div className="text-xs font-semibold text-slate-500">Blocked</div><div className="mt-1 text-2xl font-semibold text-slate-900">{review.summary.syncBlockedCount}</div></div>
        <div className="rounded-xl border border-slate-100 bg-slate-50 p-3"><div className="text-xs font-semibold text-slate-500">Stripe mapped</div><div className="mt-1 text-2xl font-semibold text-slate-900">{review.summary.stripeMappedCount}</div></div>
        <div className="rounded-xl border border-slate-100 bg-slate-50 p-3"><div className="text-xs font-semibold text-slate-500">Need notes</div><div className="mt-1 text-2xl font-semibold text-slate-900">{review.summary.reviewNeededWithoutAuditNoteCount}</div></div>
        <div className="rounded-xl border border-slate-100 bg-slate-50 p-3"><div className="text-xs font-semibold text-slate-500">Have notes</div><div className="mt-1 text-2xl font-semibold text-slate-900">{review.summary.lifecycleRowsWithAuditNotes}</div></div>
        <div className="rounded-xl border border-slate-100 bg-slate-50 p-3"><div className="text-xs font-semibold text-slate-500">Stale notes</div><div className="mt-1 text-2xl font-semibold text-slate-900">{review.summary.staleLifecycleAuditNoteCount}</div></div>
        <div className="rounded-xl border border-slate-100 bg-slate-50 p-3"><div className="text-xs font-semibold text-slate-500">Notes due soon</div><div className="mt-1 text-2xl font-semibold text-slate-900">{review.summary.lifecycleAuditNoteDueSoonCount}</div></div>
        <div className="rounded-xl border border-slate-100 bg-slate-50 p-3"><div className="text-xs font-semibold text-slate-500">Ack history</div><div className="mt-1 text-2xl font-semibold text-slate-900">{review.summary.warningAcknowledgementCount}</div></div>
        <div className="rounded-xl border border-slate-100 bg-slate-50 p-3"><div className="text-xs font-semibold text-slate-500">Ack needs review</div><div className="mt-1 text-2xl font-semibold text-slate-900">{review.summary.warningAcknowledgementNeedsActionCount}</div></div>
        <div className="rounded-xl border border-slate-100 bg-slate-50 p-3"><div className="text-xs font-semibold text-slate-500">Ack current</div><div className="mt-1 text-2xl font-semibold text-slate-900">{review.summary.warningAcknowledgedCurrentStatusCount}</div></div>
        <div className="rounded-xl border border-slate-100 bg-slate-50 p-3"><div className="text-xs font-semibold text-slate-500">Ack changed</div><div className="mt-1 text-2xl font-semibold text-slate-900">{review.summary.warningChangedSinceAcknowledgementCount}</div></div>
        <div className="rounded-xl border border-slate-100 bg-slate-50 p-3"><div className="text-xs font-semibold text-slate-500">Evidence gaps</div><div className="mt-1 text-2xl font-semibold text-slate-900">{review.summary.evidenceCloseoutGapCount}</div></div>
        <div className="rounded-xl border border-slate-100 bg-slate-50 p-3"><div className="text-xs font-semibold text-slate-500">Rows to close</div><div className="mt-1 text-2xl font-semibold text-slate-900">{review.summary.evidenceCloseoutWorkspaceRows}</div></div>
      </div>

      <div className="rounded-2xl border border-blue-100 bg-blue-50 p-4 text-sm leading-6 text-blue-900">
        <span className="font-semibold">Review posture:</span> {review.summary.firstFix}
        <div className="mt-1 text-blue-800">
          Billing status mutation is {review.guardrails.subscriptionStatusMutationActive ? "active" : "locked"}. Provider status writes are {review.guardrails.providerStatusWritten ? "active" : "not performed"}. Payment collection, customer portal sessions, and hard billing gates remain {review.guardrails.paymentCollectionActive || review.guardrails.customerPortalActive || review.guardrails.hardBillingGatesChanged ? "under review" : "off"}.
        </div>
      </div>

      {auditMessage ? <div className="rounded-2xl border border-blue-100 bg-blue-50 p-4 text-sm text-blue-900">{auditMessage}</div> : null}

      <div className="grid gap-3 md:grid-cols-2 xl:grid-cols-4">
        {review.checks.map((check) => (
          <div key={check.key} className="rounded-2xl border border-slate-100 bg-slate-50 p-4">
            <div className="flex items-start justify-between gap-3">
              <div className="font-semibold text-slate-900">{check.label}</div>
              <span className={`rounded-full px-2 py-1 text-[10px] font-semibold uppercase tracking-[0.12em] ${statusClasses(check.status)}`}>{check.status}</span>
            </div>
            <p className="mt-2 text-sm leading-6 text-slate-600">{check.detail}</p>
            <div className="mt-3 rounded-xl bg-white p-3 text-xs leading-5 text-slate-600"><span className="font-semibold text-slate-900">First fix:</span> {check.firstFix}</div>
          </div>
        ))}
      </div>

      <div className="grid gap-3 lg:grid-cols-2">
        <div className="rounded-2xl border border-slate-100 bg-slate-50 p-4">
          <h3 className="text-sm font-semibold text-slate-900">Lifecycle summary</h3>
          <div className="mt-3 grid gap-2 md:grid-cols-3">
            {review.lifecycleSummary.map((item) => (
              <div key={item.status} className="rounded-xl bg-white p-3 text-sm">
                <div className="font-semibold text-slate-900">{item.label}</div>
                <div className="mt-1 text-xs text-slate-500">Total {item.total} · Ready {item.ready} · Review {item.needsReview} · Blocked {item.blocked}</div>
              </div>
            ))}
          </div>
        </div>
        <div className="rounded-2xl border border-slate-100 bg-slate-50 p-4">
          <h3 className="text-sm font-semibold text-slate-900">Provider summary</h3>
          <div className="mt-3 grid gap-2 md:grid-cols-3">
            {review.providerSummary.map((item) => (
              <div key={item.provider} className="rounded-xl bg-white p-3 text-sm">
                <div className="font-semibold text-slate-900">{item.provider}</div>
                <div className="mt-1 text-xs text-slate-500">Total {item.total} · Ready {item.ready} · Review {item.needsReview} · Blocked {item.blocked}</div>
              </div>
            ))}
          </div>
        </div>
      </div>

      <div className="rounded-2xl border border-emerald-100 bg-emerald-50 p-4">
        <div className="flex flex-col gap-2 md:flex-row md:items-start md:justify-between">
          <div>
            <h3 className="text-sm font-semibold text-emerald-950">Final warning/audit evidence closeout</h3>
            <p className="mt-1 text-sm leading-6 text-emerald-900">Bundle the last warning acknowledgement, audit-note, threshold, guardrail, and export evidence checks before moving into customer portal or billing activation testing. This panel is review-only.</p>
          </div>
          <div className="rounded-xl bg-white/80 p-3 text-xs leading-5 text-emerald-900">
            <span className="font-semibold">First fix:</span> {review.activationEvidenceCloseout.firstFix}
          </div>
        </div>
        <div className="mt-4 grid gap-2 md:grid-cols-4">
          <div className="rounded-xl bg-white/80 p-3 text-sm"><div className="font-semibold text-slate-900">Overall</div><div className="mt-1 text-xs text-slate-500">{review.activationEvidenceCloseout.overallStatus}</div></div>
          <div className="rounded-xl bg-white/80 p-3 text-sm"><div className="font-semibold text-slate-900">Evidence gaps</div><div className="mt-1 text-xs text-slate-500">{review.activationEvidenceCloseout.evidenceGapCount} closeout gap(s)</div></div>
          <div className="rounded-xl bg-white/80 p-3 text-sm"><div className="font-semibold text-slate-900">Workspace rows</div><div className="mt-1 text-xs text-slate-500">{review.activationEvidenceCloseout.workspaceRowsNeedingCloseout} need closeout review</div></div>
          <div className="rounded-xl bg-white/80 p-3 text-sm"><div className="font-semibold text-slate-900">Exports</div><div className="mt-1 text-xs text-slate-500">{review.activationEvidenceCloseout.exportManifest.length} evidence export(s)</div></div>
        </div>
        <div className="mt-3 grid gap-2 md:grid-cols-2 xl:grid-cols-3">
          {review.activationEvidenceCloseout.rows.map((row) => (
            <div key={row.key} className="rounded-xl bg-white/90 p-3 text-xs leading-5 text-slate-600">
              <div className="flex items-start justify-between gap-2">
                <div className="font-semibold text-slate-900">{row.label}</div>
                <span className={`rounded-full px-2 py-1 text-[10px] font-semibold uppercase tracking-[0.12em] ${statusClasses(row.status)}`}>{row.status}</span>
              </div>
              <div className="mt-1">{row.detail}</div>
              <div className="mt-2 rounded-lg bg-emerald-50 p-2 text-emerald-900"><span className="font-semibold">Next:</span> {row.firstFix}</div>
            </div>
          ))}
        </div>
        <div className="mt-3 grid gap-2 md:grid-cols-3">
          {review.activationEvidenceCloseout.exportManifest.map((item) => (
            <div key={item.key} className="rounded-xl bg-white/80 p-3 text-xs leading-5 text-slate-600">
              <div className="font-semibold text-slate-900">{item.label}</div>
              <div className="break-words text-slate-500">{item.filename}</div>
              <div>{item.includes}</div>
            </div>
          ))}
        </div>
        <div className="mt-3 rounded-xl bg-white/80 p-3 text-xs leading-5 text-emerald-900">{review.activationEvidenceCloseout.reviewOnlyEffect}</div>
      </div>

      <div className="rounded-2xl border border-slate-100 bg-slate-50 p-4">
        <div className="flex flex-col gap-2 md:flex-row md:items-start md:justify-between">
          <div>
            <h3 className="text-sm font-semibold text-slate-900">Lifecycle audit-note coverage</h3>
            <p className="mt-1 text-sm leading-6 text-slate-600">Track which lifecycle-risk rows have review notes before any billing mutation or hard gate is activated. Stale-note review now uses risk-based thresholds: blocked rows {review.auditNoteCoverageSummary.staleThresholds.blockedStaleDays} days, review-needed rows {review.auditNoteCoverageSummary.staleThresholds.checkStaleDays} days, ready rows {review.auditNoteCoverageSummary.staleThresholds.readyStaleDays} days, and historical rows {review.auditNoteCoverageSummary.staleThresholds.historyStaleDays} days.</p>
          </div>
          <div className="rounded-xl bg-white p-3 text-xs leading-5 text-slate-600"><span className="font-semibold text-slate-900">First fix:</span> {review.auditNoteCoverageSummary.firstFix}</div>
        </div>
        <div className="mt-4 grid gap-2 md:grid-cols-4">
          {review.auditNoteCoverageSummary.byReadiness.map((item) => (
            <div key={item.key} className="rounded-xl bg-white p-3 text-sm">
              <div className="font-semibold text-slate-900">{item.key}</div>
              <div className="mt-1 text-xs text-slate-500">Total {item.total} · Notes {item.withNotes} · Missing {item.missingNotes} · Stale {item.staleNotes}</div>
            </div>
          ))}
        </div>
        <div className="mt-3 grid gap-2 md:grid-cols-3 xl:grid-cols-6">
          {review.auditNoteCoverageSummary.byLifecycle.map((item) => (
            <div key={item.key} className="rounded-xl bg-white p-3 text-sm">
              <div className="font-semibold text-slate-900">{item.key}</div>
              <div className="mt-1 text-xs text-slate-500">Total {item.total} · Notes {item.withNotes} · Missing {item.missingNotes}</div>
            </div>
          ))}
        </div>
        <div className="mt-3 grid gap-2 md:grid-cols-2 xl:grid-cols-5">
          {review.auditNoteCoverageSummary.byDueStatus.map((item) => (
            <div key={item.key} className="rounded-xl bg-white p-3 text-sm">
              <div className="font-semibold text-slate-900">{item.key}</div>
              <div className="mt-1 text-xs text-slate-500">{item.total} workspace rows</div>
            </div>
          ))}
        </div>
        <div className="mt-3 grid gap-2 md:grid-cols-2 xl:grid-cols-4">
          {review.auditNoteCoverageSummary.byCadence.map((item) => (
            <div key={item.key} className="rounded-xl bg-white p-3 text-xs text-slate-600"><span className="font-semibold text-slate-900">{item.key}:</span> {item.total}</div>
          ))}
        </div>
      </div>

      <div className="rounded-2xl border border-indigo-100 bg-indigo-50 p-4">
        <div className="flex flex-col gap-2 md:flex-row md:items-start md:justify-between">
          <div>
            <h3 className="text-sm font-semibold text-indigo-950">Lifecycle audit-note threshold configuration</h3>
            <p className="mt-1 text-sm leading-6 text-indigo-900">
              Super Admin can now see the active stale-review settings, the default values, whether each value came from an environment override, and the review-only effect before any billing activation work.
            </p>
          </div>
          <div className="rounded-xl bg-white/80 p-3 text-xs leading-5 text-indigo-900">
            <span className="font-semibold">Review-only effect:</span> {review.environment.lifecycleAuditThresholdConfiguration.reviewOnlyEffect}
          </div>
        </div>
        <div className="mt-4 grid gap-2 md:grid-cols-3">
          <div className="rounded-xl bg-white/80 p-3 text-sm">
            <div className="font-semibold text-slate-900">Environment overrides</div>
            <div className="mt-1 text-xs text-slate-500">{review.environment.lifecycleAuditThresholdConfiguration.environmentOverrideCount} active override(s)</div>
          </div>
          <div className="rounded-xl bg-white/80 p-3 text-sm">
            <div className="font-semibold text-slate-900">Invalid overrides</div>
            <div className="mt-1 text-xs text-slate-500">{review.environment.lifecycleAuditThresholdConfiguration.invalidOverrideCount} ignored invalid value(s)</div>
          </div>
          <div className="rounded-xl bg-white/80 p-3 text-sm">
            <div className="font-semibold text-slate-900">Due-soon window</div>
            <div className="mt-1 text-xs text-slate-500">{review.environment.lifecycleAuditThresholdConfiguration.dueSoonWindowDays} day(s) before a note reaches its stale threshold</div>
          </div>
        </div>
        <div className="mt-4 grid gap-3 xl:grid-cols-5">
          {review.environment.lifecycleAuditThresholdConfiguration.settings.map((setting) => (
            <div key={setting.key} className="rounded-xl bg-white/90 p-3 text-xs leading-5 text-slate-600">
              <div className="font-semibold text-slate-900">{setting.label}</div>
              <div className="mt-1 text-lg font-semibold text-slate-900">{setting.activeDays} days</div>
              <div>Default: {setting.defaultDays} days</div>
              <div>Source: {setting.source}{setting.isInvalidOverride ? " · invalid env value ignored" : ""}{setting.wasClamped ? " · clamped to allowed range" : ""}</div>
              <div className="break-words text-slate-500">{setting.environmentVariable}{setting.rawValue ? ` = ${setting.rawValue}` : " not set"}</div>
              <div className="mt-2 rounded-lg bg-indigo-50 p-2 text-indigo-900">{setting.reviewUse}</div>
            </div>
          ))}
        </div>
      </div>

      <div className="rounded-2xl border border-blue-100 bg-blue-50 p-4">
        <div className="flex flex-col gap-2 md:flex-row md:items-start md:justify-between">
          <div>
            <h3 className="text-sm font-semibold text-blue-950">Warning acknowledgement context</h3>
            <p className="mt-1 text-sm leading-6 text-blue-900">Review which soft billing notices were seen, which changed afterward, and which still need acknowledgement. Acknowledgements never mute warnings or change account access.</p>
          </div>
          <div className="rounded-xl bg-white/80 p-3 text-xs leading-5 text-blue-900"><span className="font-semibold">First fix:</span> {review.warningAcknowledgementSummary.firstFix}</div>
        </div>
        <div className="mt-4 grid gap-2 md:grid-cols-2 xl:grid-cols-5">
          {review.warningAcknowledgementSummary.byState.map((item) => (
            <div key={item.key} className="rounded-xl bg-white/80 p-3 text-sm">
              <div className="font-semibold text-slate-900">{item.key}</div>
              <div className="mt-1 text-xs text-slate-500">{item.total} workspace rows</div>
            </div>
          ))}
        </div>
        {review.warningAcknowledgementSummary.byStatus.length > 0 ? (
          <div className="mt-3 grid gap-2 md:grid-cols-3">
            {review.warningAcknowledgementSummary.byStatus.slice(0, 6).map((item) => (
              <div key={item.key} className="rounded-xl bg-white/80 p-3 text-xs text-slate-600"><span className="font-semibold text-slate-900">{item.key}:</span> {item.total}</div>
            ))}
          </div>
        ) : null}
        {review.warningAcknowledgementSummary.byChangedReason.length > 0 ? (
          <div className="mt-3 grid gap-2 md:grid-cols-2">
            {review.warningAcknowledgementSummary.byChangedReason.slice(0, 6).map((item) => (
              <div key={item.key} className="rounded-xl bg-white/80 p-3 text-xs text-slate-600"><span className="font-semibold text-slate-900">Changed:</span> {item.key} · {item.total}</div>
            ))}
          </div>
        ) : null}
      </div>

      <div className="grid gap-3 md:grid-cols-3 xl:grid-cols-8">
        <label className="text-sm font-medium text-slate-700">Readiness
          <select value={statusFilter} onChange={(event) => setStatusFilter(event.target.value as (typeof statusOptions)[number])} className="mt-1 w-full rounded-xl border border-slate-200 px-3 py-2 text-sm">
            {statusOptions.map((option) => <option key={option} value={option}>{option}</option>)}
          </select>
        </label>
        <label className="text-sm font-medium text-slate-700">Lifecycle
          <select value={lifecycleFilter} onChange={(event) => setLifecycleFilter(event.target.value as (typeof lifecycleOptions)[number])} className="mt-1 w-full rounded-xl border border-slate-200 px-3 py-2 text-sm">
            {lifecycleOptions.map((option) => <option key={option} value={option}>{option}</option>)}
          </select>
        </label>
        <label className="text-sm font-medium text-slate-700">Provider
          <select value={providerFilter} onChange={(event) => setProviderFilter(event.target.value as (typeof providerOptions)[number])} className="mt-1 w-full rounded-xl border border-slate-200 px-3 py-2 text-sm">
            {providerOptions.map((option) => <option key={option} value={option}>{option}</option>)}
          </select>
        </label>
        <label className="text-sm font-medium text-slate-700">Risk
          <select value={riskFilter} onChange={(event) => setRiskFilter(event.target.value as (typeof riskOptions)[number])} className="mt-1 w-full rounded-xl border border-slate-200 px-3 py-2 text-sm">
            {riskOptions.map((option) => <option key={option} value={option}>{option}</option>)}
          </select>
        </label>
        <label className="text-sm font-medium text-slate-700">Audit notes
          <select value={auditFilter} onChange={(event) => setAuditFilter(event.target.value as (typeof auditOptions)[number])} className="mt-1 w-full rounded-xl border border-slate-200 px-3 py-2 text-sm">
            {auditOptions.map((option) => <option key={option} value={option}>{option}</option>)}
          </select>
        </label>
        <label className="text-sm font-medium text-slate-700">Acknowledgements
          <select value={acknowledgementFilter} onChange={(event) => setAcknowledgementFilter(event.target.value as (typeof acknowledgementOptions)[number])} className="mt-1 w-full rounded-xl border border-slate-200 px-3 py-2 text-sm">
            {acknowledgementOptions.map((option) => <option key={option} value={option}>{option}</option>)}
          </select>
        </label>
        <label className="text-sm font-medium text-slate-700">Evidence closeout
          <select value={evidenceFilter} onChange={(event) => setEvidenceFilter(event.target.value as (typeof evidenceOptions)[number])} className="mt-1 w-full rounded-xl border border-slate-200 px-3 py-2 text-sm">
            {evidenceOptions.map((option) => <option key={option} value={option}>{option}</option>)}
          </select>
        </label>
        <label className="text-sm font-medium text-slate-700">Search
          <input value={search} onChange={(event) => setSearch(event.target.value)} placeholder="Workspace, plan, Stripe, status..." className="mt-1 w-full rounded-xl border border-slate-200 px-3 py-2 text-sm" />
        </label>
      </div>

      <div className="flex flex-wrap items-center gap-2">
        <button type="button" onClick={exportLifecycleRows} className="rounded-xl bg-slate-900 px-4 py-2 text-sm font-semibold text-white">Export lifecycle CSV</button>
        <button type="button" onClick={exportWebhookRows} className="rounded-xl bg-slate-700 px-4 py-2 text-sm font-semibold text-white">Export webhook sync CSV</button>
        <button type="button" onClick={exportFilteredAuditNotes} className="rounded-xl bg-slate-600 px-4 py-2 text-sm font-semibold text-white">Export filtered audit notes CSV</button>
        <button type="button" onClick={exportRowsNeedingAuditNotes} className="rounded-xl bg-amber-700 px-4 py-2 text-sm font-semibold text-white">Export rows needing notes CSV</button>
        <button type="button" onClick={exportWarningAcknowledgements} className="rounded-xl bg-blue-700 px-4 py-2 text-sm font-semibold text-white">Export warning acknowledgements CSV</button>
        <button type="button" onClick={exportThresholdConfiguration} className="rounded-xl bg-indigo-700 px-4 py-2 text-sm font-semibold text-white">Export threshold config CSV</button>
        <button type="button" onClick={exportEvidenceCloseout} className="rounded-xl bg-emerald-700 px-4 py-2 text-sm font-semibold text-white">Export evidence closeout CSV</button>
        <button type="button" onClick={resetFilters} className="rounded-xl border border-slate-200 bg-white px-4 py-2 text-sm font-semibold text-slate-700">Reset filters</button>
        <span className="text-sm text-slate-500">Showing {filteredRows.length} workspace records, {webhookRows.length} webhook records, {filteredAuditNotes.length} audit notes, and {filteredAcknowledgements.length} acknowledgements. Audit stale thresholds are risk-based, not one fixed age.</span>
      </div>

      <div className="grid gap-4 xl:grid-cols-2">
        <div className="space-y-3">
          <h3 className="text-sm font-semibold text-slate-900">Workspace lifecycle records</h3>
          {filteredRows.length === 0 ? (
            <div className="rounded-2xl border border-slate-100 bg-slate-50 p-4 text-sm text-slate-600">No workspace lifecycle rows match these filters.</div>
          ) : filteredRows.slice(0, 40).map((row) => (
            <div key={row.workspaceId} className={`rounded-2xl border bg-white p-4 shadow-sm ${borderClasses(row.readinessStatus)}`}>
              <div className="flex flex-col gap-3 md:flex-row md:items-start md:justify-between">
                <div>
                  <div className="font-semibold text-slate-900">{row.workspaceName}</div>
                  <div className="mt-1 text-xs text-slate-500">{row.workspaceSlug} · {row.workspaceTypeLabel} · {row.accountClassLabel}</div>
                  <div className="mt-1 text-xs text-slate-500">Admin: {row.adminEmail} · {row.adminEmailVerified ? "verified" : "not verified"}</div>
                </div>
                <span className={`w-fit rounded-full px-2 py-1 text-[10px] font-semibold uppercase tracking-[0.12em] ${statusClasses(row.readinessStatus)}`}>{row.readinessStatus}</span>
              </div>

              <div className="mt-4 grid gap-2 text-xs text-slate-600 md:grid-cols-2">
                <div><span className="font-semibold text-slate-900">Lifecycle:</span> {trialLabel(row)}</div>
                <div><span className="font-semibold text-slate-900">Plan:</span> {row.planName} ({money(row.planMonthlyPrice)}/mo)</div>
                <div><span className="font-semibold text-slate-900">Provider:</span> {row.billingProvider}/{row.billingMode}</div>
                <div><span className="font-semibold text-slate-900">Sync:</span> {row.providerSyncStatus || "Not recorded"}</div>
                <div><span className="font-semibold text-slate-900">Evidence:</span> {row.activationEvidenceState}</div>
                <div><span className="font-semibold text-slate-900">Customer:</span> {row.stripeCustomerIdMasked}</div>
                <div><span className="font-semibold text-slate-900">Subscription:</span> {row.stripeSubscriptionIdMasked}</div>
                <div><span className="font-semibold text-slate-900">Period end:</span> {dateTime(row.currentPeriodEndsAt)}</div>
                <div><span className="font-semibold text-slate-900">Last provider sync:</span> {dateTime(row.lastProviderSyncAt)}</div>
              </div>

              {row.latestWebhook ? (
                <div className="mt-3 rounded-xl bg-blue-50 p-3 text-xs leading-5 text-blue-900">
                  <span className="font-semibold">Latest webhook:</span> {row.latestWebhook.eventType} · {row.latestWebhook.mode} · {row.latestWebhook.verificationStatus} · {dateTime(row.latestWebhook.createdAt)}
                </div>
              ) : null}

              {row.riskReasons.length > 0 ? (
                <div className="mt-3 flex flex-wrap gap-2">
                  {row.riskReasons.map((risk) => <span key={risk} className="rounded-full bg-amber-100 px-2 py-1 text-[10px] font-semibold uppercase tracking-[0.12em] text-amber-700">{risk}</span>)}
                </div>
              ) : null}

              <div className="mt-3 rounded-xl bg-slate-50 p-3 text-xs leading-5 text-slate-600">
                <span className="font-semibold text-slate-900">Audit state:</span> {row.auditNoteState} · {row.auditExportGroup} · {row.lifecycleAuditNoteCadence} · {row.lifecycleAuditDueStatus}
                {row.latestLifecycleAuditNoteAgeDays !== null ? ` · latest note age ${row.latestLifecycleAuditNoteAgeDays} days` : ""}
                {row.lifecycleAuditNoteDaysUntilStale !== null ? ` · stale threshold ${row.lifecycleAuditNoteStaleThresholdDays} days · ${row.lifecycleAuditNoteDaysUntilStale >= 0 ? `${row.lifecycleAuditNoteDaysUntilStale} days left` : `${Math.abs(row.lifecycleAuditNoteDaysUntilStale)} days overdue`}` : ` · stale threshold ${row.lifecycleAuditNoteStaleThresholdDays} days`}
                <div className="mt-1 text-slate-500">{row.lifecycleAuditNoteRefreshReason}</div>
              </div>
              <div className="mt-2 rounded-xl bg-slate-50 p-3 text-xs leading-5 text-slate-600"><span className="font-semibold text-slate-900">First fix:</span> {row.firstFix}</div>
              <div className="mt-2 rounded-xl bg-slate-50 p-3 text-xs leading-5 text-slate-600"><span className="font-semibold text-slate-900">Workspace Admin message:</span> {row.workspaceAdminMessage}</div>
              <div className="mt-2 rounded-xl bg-emerald-50 p-3 text-xs leading-5 text-emerald-900">
                <span className="font-semibold">Evidence closeout:</span> {row.activationEvidenceState}
                {row.activationEvidenceIssues.length > 0 ? <div className="mt-1">Issues: {row.activationEvidenceIssues.join(", ")}</div> : null}
                <div className="mt-1">{row.activationEvidenceNextStep}</div>
              </div>
              <div className="mt-2 rounded-xl bg-slate-50 p-3 text-xs leading-5 text-slate-600">
                <div className="flex flex-col gap-2 md:flex-row md:items-center md:justify-between">
                  <div>
                    <span className="font-semibold text-slate-900">Lifecycle audit notes:</span> {row.lifecycleAuditNoteCount}
                    {row.latestLifecycleAuditNoteAt ? ` · latest ${dateTime(row.latestLifecycleAuditNoteAt)}` : " · none yet"}
                    {row.warningAcknowledgementCount > 0 ? ` · warning acknowledgements ${row.warningAcknowledgementCount}` : ""}
                  </div>
                  <button type="button" onClick={() => beginAuditNote(row)} className="w-fit rounded-lg border border-slate-200 bg-white px-3 py-1.5 text-xs font-semibold text-slate-700">
                    {row.lifecycleAuditNoteCount > 0 ? "Add another note" : "Add review note"}
                  </button>
                </div>
                {row.latestLifecycleAuditNote ? <div className="mt-2 rounded-lg bg-white p-2"><span className="font-semibold text-slate-900">Latest note:</span> {row.latestLifecycleAuditNote}</div> : null}
                <div className="mt-2 rounded-lg bg-white p-2">
                  <span className="font-semibold text-slate-900">Warning acknowledgement:</span> {row.warningAcknowledgementState}
                  <div className="mt-1 text-slate-600">{row.warningAcknowledgementContext}</div>
                  {row.latestWarningAcknowledgementAt ? (
                    <div className="mt-1 text-slate-500">
                      Latest: {dateTime(row.latestWarningAcknowledgementAt)} · {row.latestWarningAcknowledgementTitle ?? "Subscription notice"}
                      {row.latestWarningAcknowledgementStatusLabel ? " · " + row.latestWarningAcknowledgementStatusLabel : ""}
                      {row.latestWarningAcknowledgementSeverity ? " · " + row.latestWarningAcknowledgementSeverity : ""}
                    </div>
                  ) : null}
                  {row.warningAcknowledgementSignalBasis.length > 0 ? <div className="mt-1 text-slate-500">Current warning basis: {row.warningAcknowledgementCurrentStatusKey} · {row.warningAcknowledgementCurrentSeverity} · {row.warningAcknowledgementSignalBasis.join(", ")}</div> : null}
                  {row.latestWarningAcknowledgementSignalKeys.length > 0 ? <div className="mt-1 text-slate-500">Acknowledged signals: {row.latestWarningAcknowledgementSignalKeys.join(", ")}</div> : null}
                  {row.warningAcknowledgementChangedReasons.length > 0 ? <div className="mt-1 text-amber-700">Changed reasons: {row.warningAcknowledgementChangedReasons.join("; ")}</div> : null}
                  {row.warningAcknowledgementCurrentSignalSignature || row.warningAcknowledgementLatestSignalSignature ? <div className="mt-1 text-slate-400">Signal signature: current {row.warningAcknowledgementCurrentSignalSignature || "none"} · latest {row.warningAcknowledgementLatestSignalSignature || "none"}</div> : null}
                </div>
                {noteWorkspaceId === row.workspaceId ? (
                  <div className="mt-3 space-y-2">
                    <textarea
                      value={noteDraft}
                      onChange={(event) => setNoteDraft(event.target.value)}
                      placeholder="Record what Super Admin reviewed, what needs fixing, or why this row is safe to leave review-only."
                      className="min-h-24 w-full rounded-xl border border-slate-200 bg-white p-3 text-sm text-slate-700"
                    />
                    <div className="flex flex-wrap gap-2">
                      <button type="button" onClick={() => saveAuditNote(row)} disabled={savingNote} className="rounded-xl bg-slate-900 px-4 py-2 text-sm font-semibold text-white disabled:cursor-not-allowed disabled:opacity-60">
                        {savingNote ? "Saving..." : "Save lifecycle note"}
                      </button>
                      <button type="button" onClick={() => { setNoteWorkspaceId(null); setNoteDraft(""); }} className="rounded-xl border border-slate-200 bg-white px-4 py-2 text-sm font-semibold text-slate-700">Cancel</button>
                    </div>
                  </div>
                ) : null}
              </div>
            </div>
          ))}
        </div>

        <div className="space-y-3">
          <h3 className="text-sm font-semibold text-slate-900">Review-only webhook billing sync signals</h3>
          {webhookRows.length === 0 ? (
            <div className="rounded-2xl border border-slate-100 bg-slate-50 p-4 text-sm text-slate-600">No webhook rows match this search.</div>
          ) : webhookRows.slice(0, 30).map((row) => (
            <div key={row.id} className="rounded-2xl border border-slate-100 bg-slate-50 p-4 text-sm">
              <div className="flex items-start justify-between gap-3">
                <div>
                  <div className="font-semibold text-slate-900">{row.eventType}</div>
                  <div className="mt-1 text-xs text-slate-500">{row.eventId} · {dateTime(row.createdAt)}</div>
                </div>
                <span className={`rounded-full px-2 py-1 text-[10px] font-semibold uppercase tracking-[0.12em] ${row.livemode ? "bg-rose-100 text-rose-700" : "bg-blue-100 text-blue-700"}`}>{row.livemode ? "Live ignored" : "Test/review"}</span>
              </div>
              <div className="mt-3 grid gap-2 text-xs text-slate-600 md:grid-cols-2">
                <div><span className="font-semibold text-slate-900">Verification:</span> {row.verificationStatus}</div>
                <div><span className="font-semibold text-slate-900">Outcome:</span> {row.providerSyncOutcome}</div>
                <div><span className="font-semibold text-slate-900">Customer:</span> {row.customerIdMasked}</div>
                <div><span className="font-semibold text-slate-900">Subscription:</span> {row.subscriptionIdMasked}</div>
              </div>
              <div className="mt-3 rounded-xl bg-white p-3 text-xs leading-5 text-slate-600"><span className="font-semibold text-slate-900">Review result:</span> {row.reviewResult}</div>
            </div>
          ))}

          <div className="rounded-2xl border border-slate-100 bg-slate-50 p-4">
            <h3 className="text-sm font-semibold text-slate-900">Recent lifecycle audit notes</h3>
            <div className="mt-3 space-y-2">
              {review.lifecycleAuditNotes.length === 0 ? (
                <div className="rounded-xl bg-white p-3 text-sm text-slate-600">No lifecycle sync audit notes have been saved yet.</div>
              ) : review.lifecycleAuditNotes.slice(0, 6).map((note) => (
                <div key={note.id} className="rounded-xl bg-white p-3 text-xs leading-5 text-slate-600">
                  <div className="font-semibold text-slate-900">{note.workspaceName || "Workspace"} · {note.readinessStatus || "Review"}</div>
                  <div>{note.note}</div>
                  <div className="text-slate-500">{dateTime(note.createdAt)}</div>
                </div>
              ))}
            </div>
          </div>

          <div className="rounded-2xl border border-slate-100 bg-slate-50 p-4">
            <h3 className="text-sm font-semibold text-slate-900">Recent warning acknowledgements</h3>
            <div className="mt-3 space-y-2">
              {review.warningAcknowledgementHistory.length === 0 ? (
                <div className="rounded-xl bg-white p-3 text-sm text-slate-600">No Workspace Admin billing warning acknowledgements found yet.</div>
              ) : review.warningAcknowledgementHistory.slice(0, 6).map((item) => (
                <div key={item.id} className="rounded-xl bg-white p-3 text-xs leading-5 text-slate-600">
                  <div className="font-semibold text-slate-900">{item.workspaceName || "Workspace"} · {item.warningSeverity || "notice"} · {item.warningStatusLabel || "Billing review"}</div>
                  <div>{item.warningTitle || "Subscription notice"}</div>
                  <div className="text-slate-500">{dateTime(item.createdAt)} · {item.acknowledgedFrom} · {item.subscriptionStatus || "No status"}</div>
                  {item.signalKeys.length > 0 ? <div className="text-slate-500">Signals: {item.signalKeys.join(", ")}{item.signalKeySignature ? ` · signature ${item.signalKeySignature}` : ""}{item.warningFingerprintVersion ? ` · ${item.warningFingerprintVersion}` : ""}</div> : null}
                  <div className="mt-1 rounded-lg bg-slate-50 p-2">{item.acknowledgementEffect}</div>
                </div>
              ))}
            </div>
          </div>

          <div className="rounded-2xl border border-slate-100 bg-slate-50 p-4">
            <h3 className="text-sm font-semibold text-slate-900">Recent related audit records</h3>
            <div className="mt-3 space-y-2">
              {review.recentSyncAuditEvents.length === 0 ? (
                <div className="rounded-xl bg-white p-3 text-sm text-slate-600">No related checkout/webhook audit records found yet.</div>
              ) : review.recentSyncAuditEvents.slice(0, 8).map((event) => (
                <div key={event.id} className="rounded-xl bg-white p-3 text-xs leading-5 text-slate-600">
                  <div className="font-semibold text-slate-900">{event.action}</div>
                  <div>{event.summary}</div>
                  <div className="text-slate-500">{dateTime(event.createdAt)}</div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>

      <div className="rounded-2xl border border-slate-100 bg-slate-50 p-4 text-xs leading-5 text-slate-600">
        Guardrails: review-only={String(review.guardrails.reviewOnly)} · subscription mutation active={String(review.guardrails.subscriptionStatusMutationActive)} · payment collection={String(review.guardrails.paymentCollectionActive)} · customer portal={String(review.guardrails.customerPortalActive)} · hard billing gates={String(review.guardrails.hardBillingGatesChanged)} · broker distribution changed={String(review.guardrails.brokerDistributionChanged)} · owned portal rules changed={String(review.guardrails.ownedPortalRulesChanged)} · internal load-board access changed={String(review.guardrails.internalLoadBoardAccessChanged)}
      </div>
    </section>
  );
}
