"use client";

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

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

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

type MappingRow = {
  id: string;
  workspaceName: string;
  workspaceSlug: string;
  adminEmail: string;
  workspaceType: string;
  accountClass: string;
  status: string;
  planName: string;
  providerSyncStatus: string;
  billingProvider: string;
  billingMode: string;
  stripeCustomerIdMasked: string;
  stripeSubscriptionIdMasked: string;
  stripeSubscriptionItemIdMasked: string;
  trialEndsAt: string | null;
  lastProviderSyncAt: string | null;
  billingProviderStatus: string;
  readinessStatus: ReadinessStatus;
  firstFix: string;
};

type TrialRow = {
  id: string;
  workspaceName: string;
  workspaceSlug: string;
  adminEmail: string;
  workspaceType: string;
  planName: string;
  trialEndsAt: string | null;
  daysRemaining: number | null;
  providerSyncStatus: string;
  stripeCustomerIdMasked: string;
  stripeSubscriptionIdMasked: string;
  planPriceIdMasked: string;
  readinessStatus: ReadinessStatus;
  firstFix: string;
};

type WebhookPreviewRow = {
  id: string;
  eventId: string;
  eventType: string;
  mode: string;
  livemode: boolean;
  signatureVerified: boolean;
  verificationStatus: string;
  matchedWorkspaceName: string | null;
  matchedWorkspaceSlug: string | null;
  customerIdMasked: string;
  subscriptionIdMasked: string;
  subscriptionItemIdMasked: string;
  providerSyncOutcome: string;
  handled: boolean;
  currentWorkspaceSubscriptionStatus: string;
  syncPreview: string;
  readinessStatus: ReadinessStatus;
  firstFix: string;
  createdAt: string;
};

type SyncReadinessReview = {
  summary: {
    readinessStatus: ReadinessStatus;
    stripeMappedSubscriptions: number;
    cleanMappings: number;
    duplicateCustomerIds: number;
    duplicateSubscriptionIds: number;
    recentWebhookEvents: number;
    matchedWebhookEvents: number;
    webhookPreviewReady: number;
    testSyncMutationsApplied: number;
    testSyncDuplicatesIgnored: number;
    testSyncMutationAuditCount: number;
    verifiedTestSyncMutationReady: boolean;
    trialWorkspaces: number;
    trialReady: number;
    trialMissingEndDate: number;
    trialEndingSoon: number;
    trialExpired: number;
    approvedCheckoutSwitches: number;
    checkoutUrlReadinessApproved: boolean;
    firstFix: string;
  };
  environment: {
    stripeMode: string;
    secretKeyConfigured: boolean;
    publishableKeyConfigured: boolean;
    webhookSecretConfigured: boolean;
    webhookIntakeFlagRequested: boolean;
    subscriptionSyncFlagRequested: boolean;
    testSyncMutationFlagRequested: boolean;
    trialToPaidReviewOnly: boolean;
    paymentCollectionFlagRequested: boolean;
    customerPortalFlagRequested: boolean;
    hardBillingGateFlagRequested: boolean;
    checkoutUrlReturnRequested: boolean;
  };
  checks: CheckRow[];
  mappingRows: MappingRow[];
  trialRows: TrialRow[];
  webhookPreviewRows: WebhookPreviewRow[];
  approvalSummary: {
    approvedCheckoutSwitches: number;
    checkoutUrlReadinessApproved: boolean;
    approvalEventsReviewed: number;
    urlReadinessEventsReviewed: number;
    testMutationAuditEventsReviewed: number;
  };
  verifiedTestMutationAudit: Array<{
    id: string;
    summary: string;
    targetId: string | null;
    createdAt: string;
  }>;
  guardrails: {
    reviewOnly: boolean;
    verifiedTestProviderSyncMutationActive: boolean;
    subscriptionStatusMutationActive: boolean;
    trialConvertedToPaid: boolean;
    checkoutUrlReturnActive: boolean;
    paymentCollectionActive: boolean;
    customerPortalActive: boolean;
    hardBillingGatesChanged: boolean;
    brokerDistributionChanged: boolean;
    ownedPortalRulesChanged: boolean;
    internalLoadBoardAccessChanged: boolean;
  };
};

function dateTime(value?: string | null) {
  if (!value) return "Not recorded";
  return new Date(value).toLocaleString();
}

function statusClasses(status: ReadinessStatus) {
  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 csvEscape(value: unknown) {
  const text = 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 rowSearchText(...values: Array<unknown>) {
  return values.filter(Boolean).join(" ").toLowerCase();
}

export function AdminStripeSubscriptionSyncReadinessPanel() {
  const [review, setReview] = useState<SyncReadinessReview | null>(null);
  const [loaded, setLoaded] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [mappingFilter, setMappingFilter] = useState("all");
  const [trialFilter, setTrialFilter] = useState("all");
  const [webhookFilter, setWebhookFilter] = useState("all");
  const [search, setSearch] = useState("");

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

    async function loadReview() {
      try {
        setError(null);
        const data = await apiGet<SyncReadinessReview>("/api/admin/stripe-subscription-sync/readiness");
        if (!cancelled) setReview(data);
      } catch (err: any) {
        if (!cancelled) setError(err?.message ?? "Failed to load Stripe subscription sync readiness.");
      } finally {
        if (!cancelled) setLoaded(true);
      }
    }

    void loadReview();

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

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

  const filteredMappings = useMemo(() => {
    return (review?.mappingRows ?? []).filter((row) => {
      const matchesFilter = mappingFilter === "all"
        || row.readinessStatus === mappingFilter
        || (mappingFilter === "stripeIds" && (row.stripeCustomerIdMasked !== "Not set" || row.stripeSubscriptionIdMasked !== "Not set"))
        || (mappingFilter === "needsReview" && row.readinessStatus !== "Ready");
      const matchesSearch = !needle || rowSearchText(row.workspaceName, row.workspaceSlug, row.adminEmail, row.workspaceType, row.accountClass, row.status, row.planName, row.providerSyncStatus, row.billingProviderStatus, row.firstFix).includes(needle);
      return matchesFilter && matchesSearch;
    });
  }, [review, mappingFilter, needle]);

  const filteredTrials = useMemo(() => {
    return (review?.trialRows ?? []).filter((row) => {
      const matchesFilter = trialFilter === "all"
        || row.readinessStatus === trialFilter
        || (trialFilter === "missingTrialEnd" && !row.trialEndsAt)
        || (trialFilter === "endingSoon" && row.daysRemaining !== null && row.daysRemaining >= 0 && row.daysRemaining <= 7)
        || (trialFilter === "expired" && row.daysRemaining !== null && row.daysRemaining < 0)
        || (trialFilter === "needsReview" && row.readinessStatus !== "Ready");
      const matchesSearch = !needle || rowSearchText(row.workspaceName, row.workspaceSlug, row.adminEmail, row.workspaceType, row.planName, row.providerSyncStatus, row.firstFix).includes(needle);
      return matchesFilter && matchesSearch;
    });
  }, [review, trialFilter, needle]);

  const filteredWebhooks = useMemo(() => {
    return (review?.webhookPreviewRows ?? []).filter((row) => {
      const matchesFilter = webhookFilter === "all"
        || row.readinessStatus === webhookFilter
        || (webhookFilter === "matched" && Boolean(row.matchedWorkspaceName))
        || (webhookFilter === "unmatched" && !row.matchedWorkspaceName)
        || (webhookFilter === "verificationFailed" && row.verificationStatus === "verification_failed")
        || (webhookFilter === "testMutation" && row.providerSyncOutcome === "test_subscription_sync_mutation_applied")
        || (webhookFilter === "duplicateIgnored" && row.providerSyncOutcome === "test_subscription_sync_mutation_duplicate_ignored")
        || (webhookFilter === "live" && row.livemode);
      const matchesSearch = !needle || rowSearchText(row.eventId, row.eventType, row.mode, row.verificationStatus, row.matchedWorkspaceName, row.matchedWorkspaceSlug, row.providerSyncOutcome, row.currentWorkspaceSubscriptionStatus, row.syncPreview, row.firstFix).includes(needle);
      return matchesFilter && matchesSearch;
    });
  }, [review, webhookFilter, needle]);

  function exportMappings() {
    downloadCsv(
      "dispatchspot-stripe-subscription-sync-mapping-readiness.csv",
      ["Workspace", "Slug", "Admin email", "Type", "Account class", "Status", "Plan", "Provider", "Mode", "Provider sync", "Customer", "Subscription", "Item", "Trial end", "Last sync", "Readiness", "First fix"],
      filteredMappings.map((row) => [
        row.workspaceName,
        row.workspaceSlug,
        row.adminEmail,
        row.workspaceType,
        row.accountClass,
        row.status,
        row.planName,
        row.billingProvider,
        row.billingMode,
        row.providerSyncStatus,
        row.stripeCustomerIdMasked,
        row.stripeSubscriptionIdMasked,
        row.stripeSubscriptionItemIdMasked,
        dateTime(row.trialEndsAt),
        dateTime(row.lastProviderSyncAt),
        row.readinessStatus,
        row.firstFix,
      ]),
    );
  }

  function exportTrials() {
    downloadCsv(
      "dispatchspot-trial-to-paid-readiness.csv",
      ["Workspace", "Slug", "Admin email", "Type", "Plan", "Trial end", "Days remaining", "Provider sync", "Customer", "Subscription", "Plan price", "Readiness", "First fix"],
      filteredTrials.map((row) => [
        row.workspaceName,
        row.workspaceSlug,
        row.adminEmail,
        row.workspaceType,
        row.planName,
        dateTime(row.trialEndsAt),
        row.daysRemaining ?? "",
        row.providerSyncStatus,
        row.stripeCustomerIdMasked,
        row.stripeSubscriptionIdMasked,
        row.planPriceIdMasked,
        row.readinessStatus,
        row.firstFix,
      ]),
    );
  }

  function exportWebhooks() {
    downloadCsv(
      "dispatchspot-webhook-subscription-sync-preview.csv",
      ["Created", "Event", "Event ID", "Mode", "Verified", "Handled", "Verification", "Workspace", "Customer", "Subscription", "Item", "Outcome", "Current status", "Readiness", "Sync preview", "First fix"],
      filteredWebhooks.map((row) => [
        dateTime(row.createdAt),
        row.eventType,
        row.eventId,
        row.mode,
        row.signatureVerified ? "yes" : "no",
        row.handled ? "yes" : "no",
        row.verificationStatus,
        row.matchedWorkspaceName ?? "",
        row.customerIdMasked,
        row.subscriptionIdMasked,
        row.subscriptionItemIdMasked,
        row.providerSyncOutcome,
        row.currentWorkspaceSubscriptionStatus,
        row.readinessStatus,
        row.syncPreview,
        row.firstFix,
      ]),
    );
  }

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

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

  if (!review) return null;

  return (
    <section className="space-y-5 rounded-2xl border bg-white p-6 shadow-sm">
      <div className="flex flex-col gap-3 md:flex-row md:items-start md:justify-between">
        <div>
          <div className="text-xs font-semibold uppercase tracking-[0.18em] text-blue-700">Stripe subscription sync</div>
          <h2 className="mt-1 text-xl font-semibold text-slate-900">Subscription sync and trial-to-paid readiness</h2>
          <p className="mt-1 max-w-4xl text-sm leading-6 text-slate-600">
            Review Stripe customer/subscription mapping, webhook sync preview, and trial-to-paid readiness before any webhook-driven subscription status change, payment collection, customer portal session, or hard billing gate is activated.
          </p>
        </div>
        <span className={`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-8">
        <div className="rounded-xl border border-slate-100 bg-slate-50 p-3"><div className="text-xs font-semibold text-slate-500">Mapped subs</div><div className="mt-1 text-2xl font-semibold text-slate-900">{review.summary.stripeMappedSubscriptions}</div></div>
        <div className="rounded-xl border border-slate-100 bg-slate-50 p-3"><div className="text-xs font-semibold text-slate-500">Clean mapping</div><div className="mt-1 text-2xl font-semibold text-slate-900">{review.summary.cleanMappings}</div></div>
        <div className="rounded-xl border border-slate-100 bg-slate-50 p-3"><div className="text-xs font-semibold text-slate-500">Webhook events</div><div className="mt-1 text-2xl font-semibold text-slate-900">{review.summary.recentWebhookEvents}</div></div>
        <div className="rounded-xl border border-slate-100 bg-slate-50 p-3"><div className="text-xs font-semibold text-slate-500">Matched events</div><div className="mt-1 text-2xl font-semibold text-slate-900">{review.summary.matchedWebhookEvents}</div></div>
        <div className="rounded-xl border border-slate-100 bg-slate-50 p-3"><div className="text-xs font-semibold text-slate-500">Trials</div><div className="mt-1 text-2xl font-semibold text-slate-900">{review.summary.trialWorkspaces}</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 ready</div><div className="mt-1 text-2xl font-semibold text-slate-900">{review.summary.trialReady}</div></div>
        <div className="rounded-xl border border-slate-100 bg-slate-50 p-3"><div className="text-xs font-semibold text-slate-500">Ending soon</div><div className="mt-1 text-2xl font-semibold text-slate-900">{review.summary.trialEndingSoon}</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 trial</div><div className="mt-1 text-2xl font-semibold text-slate-900">{review.summary.trialExpired}</div></div>
      </div>

      <div className="grid gap-3 md:grid-cols-3">
        <div className="rounded-xl border border-emerald-100 bg-emerald-50 p-3"><div className="text-xs font-semibold text-emerald-700">Verified test mutations</div><div className="mt-1 text-2xl font-semibold text-emerald-900">{review.summary.testSyncMutationsApplied}</div><p className="mt-1 text-xs leading-5 text-emerald-800">Provider sync fields only. Workspace status and access do not change.</p></div>
        <div className="rounded-xl border border-slate-100 bg-slate-50 p-3"><div className="text-xs font-semibold text-slate-500">Duplicate events ignored</div><div className="mt-1 text-2xl font-semibold text-slate-900">{review.summary.testSyncDuplicatesIgnored}</div><p className="mt-1 text-xs leading-5 text-slate-600">Repeated Stripe event IDs are not applied twice.</p></div>
        <div className="rounded-xl border border-blue-100 bg-blue-50 p-3"><div className="text-xs font-semibold text-blue-700">Test mutation switch</div><div className="mt-1 text-sm font-semibold text-blue-950">{review.summary.verifiedTestSyncMutationReady ? "Ready" : "Locked or needs review"}</div><p className="mt-1 text-xs leading-5 text-blue-800">Requires signed test webhooks, Stripe test mode, mapped subscriptions, and all access-changing flags off.</p></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">Verified provider-sync test mutation is {review.guardrails.verifiedTestProviderSyncMutationActive ? "available" : "locked"}. Workspace subscription status mutation is {review.guardrails.subscriptionStatusMutationActive ? "on" : "locked"}. Trial conversion is {review.guardrails.trialConvertedToPaid ? "active" : "review-only"}. Payment collection, customer portal activation, and hard billing gates remain off.</div>
      </div>

      <div className="grid gap-3 md:grid-cols-2 xl:grid-cols-5">
        {review.checks.map((check) => (
          <div key={check.key} className="rounded-2xl border border-slate-100 bg-white p-4 shadow-sm">
            <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-slate-50 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 md:grid-cols-4">
        <label className="text-sm font-medium text-slate-700">Mapping filter
          <select value={mappingFilter} onChange={(event) => setMappingFilter(event.target.value)} className="mt-1 w-full rounded-xl border border-slate-200 px-3 py-2 text-sm">
            <option value="all">All mappings</option>
            <option value="Ready">Ready</option>
            <option value="Check">Needs review</option>
            <option value="Blocked">Blocked</option>
            <option value="Locked">Locked</option>
            <option value="stripeIds">Has Stripe IDs</option>
            <option value="needsReview">Any issue</option>
          </select>
        </label>
        <label className="text-sm font-medium text-slate-700">Trial filter
          <select value={trialFilter} onChange={(event) => setTrialFilter(event.target.value)} className="mt-1 w-full rounded-xl border border-slate-200 px-3 py-2 text-sm">
            <option value="all">All trials</option>
            <option value="Ready">Ready</option>
            <option value="Check">Needs review</option>
            <option value="missingTrialEnd">Missing trial end</option>
            <option value="endingSoon">Ending within 7 days</option>
            <option value="expired">Past trial end</option>
            <option value="needsReview">Any issue</option>
          </select>
        </label>
        <label className="text-sm font-medium text-slate-700">Webhook filter
          <select value={webhookFilter} onChange={(event) => setWebhookFilter(event.target.value)} className="mt-1 w-full rounded-xl border border-slate-200 px-3 py-2 text-sm">
            <option value="all">All webhook previews</option>
            <option value="Ready">Ready</option>
            <option value="Check">Needs review</option>
            <option value="Blocked">Blocked</option>
            <option value="matched">Matched workspace</option>
            <option value="unmatched">Unmatched</option>
            <option value="verificationFailed">Verification failed</option>
            <option value="testMutation">Test mutation applied</option>
            <option value="duplicateIgnored">Duplicate ignored</option>
            <option value="live">Live ignored</option>
          </select>
        </label>
        <label className="text-sm font-medium text-slate-700">Shared search
          <input value={search} onChange={(event) => setSearch(event.target.value)} placeholder="Workspace, plan, event, status..." className="mt-1 w-full rounded-xl border border-slate-200 px-3 py-2 text-sm" />
        </label>
      </div>

      <div className="grid gap-4 xl:grid-cols-3">
        <div className="rounded-2xl border border-slate-100 bg-white p-4">
          <div className="flex items-start justify-between gap-3">
            <div>
              <h3 className="text-sm font-semibold text-slate-900">Stripe ID mapping</h3>
              <p className="mt-1 text-sm text-slate-500">Filtered records: {filteredMappings.length}</p>
            </div>
            <button type="button" onClick={exportMappings} className="rounded-xl bg-slate-900 px-3 py-2 text-xs font-semibold text-white">Export</button>
          </div>
          <div className="mt-4 space-y-3">
            {filteredMappings.length === 0 ? <div className="rounded-xl bg-slate-50 p-4 text-sm text-slate-600">No mapping rows match the filters.</div> : filteredMappings.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.workspaceName}</div>
                    <div className="mt-1 text-xs text-slate-500">{row.workspaceType} · {row.status} · {row.planName}</div>
                  </div>
                  <span className={`rounded-full px-2 py-1 text-[10px] font-semibold uppercase tracking-[0.12em] ${statusClasses(row.readinessStatus)}`}>{row.readinessStatus}</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">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">Provider:</span> {row.billingProvider}/{row.billingMode}</div>
                  <div><span className="font-semibold text-slate-900">Sync:</span> {row.providerSyncStatus}</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">First fix:</span> {row.firstFix}</div>
              </div>
            ))}
          </div>
        </div>

        <div className="rounded-2xl border border-slate-100 bg-white p-4">
          <div className="flex items-start justify-between gap-3">
            <div>
              <h3 className="text-sm font-semibold text-slate-900">Trial-to-paid readiness</h3>
              <p className="mt-1 text-sm text-slate-500">Filtered records: {filteredTrials.length}</p>
            </div>
            <button type="button" onClick={exportTrials} className="rounded-xl bg-slate-900 px-3 py-2 text-xs font-semibold text-white">Export</button>
          </div>
          <div className="mt-4 space-y-3">
            {filteredTrials.length === 0 ? <div className="rounded-xl bg-slate-50 p-4 text-sm text-slate-600">No trial rows match the filters.</div> : filteredTrials.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.workspaceName}</div>
                    <div className="mt-1 text-xs text-slate-500">{row.planName} · {dateTime(row.trialEndsAt)}</div>
                  </div>
                  <span className={`rounded-full px-2 py-1 text-[10px] font-semibold uppercase tracking-[0.12em] ${statusClasses(row.readinessStatus)}`}>{row.readinessStatus}</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">Days left:</span> {row.daysRemaining ?? "Unknown"}</div>
                  <div><span className="font-semibold text-slate-900">Sync:</span> {row.providerSyncStatus}</div>
                  <div><span className="font-semibold text-slate-900">Customer:</span> {row.stripeCustomerIdMasked}</div>
                  <div><span className="font-semibold text-slate-900">Price:</span> {row.planPriceIdMasked}</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">First fix:</span> {row.firstFix}</div>
              </div>
            ))}
          </div>
        </div>

        <div className="rounded-2xl border border-slate-100 bg-white p-4">
          <div className="flex items-start justify-between gap-3">
            <div>
              <h3 className="text-sm font-semibold text-slate-900">Webhook sync preview</h3>
              <p className="mt-1 text-sm text-slate-500">Filtered records: {filteredWebhooks.length}</p>
            </div>
            <button type="button" onClick={exportWebhooks} className="rounded-xl bg-slate-900 px-3 py-2 text-xs font-semibold text-white">Export</button>
          </div>
          <div className="mt-4 space-y-3">
            {filteredWebhooks.length === 0 ? <div className="rounded-xl bg-slate-50 p-4 text-sm text-slate-600">No webhook preview rows match the filters.</div> : filteredWebhooks.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 break-all text-xs text-slate-500">{row.eventId}</div>
                  </div>
                  <span className={`rounded-full px-2 py-1 text-[10px] font-semibold uppercase tracking-[0.12em] ${statusClasses(row.readinessStatus)}`}>{row.readinessStatus}</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">Workspace:</span> {row.matchedWorkspaceName ?? "No match"}</div>
                  <div><span className="font-semibold text-slate-900">Current:</span> {row.currentWorkspaceSubscriptionStatus}</div>
                  <div><span className="font-semibold text-slate-900">Outcome:</span> {row.providerSyncOutcome}</div>
                  <div><span className="font-semibold text-slate-900">Verified:</span> {row.signatureVerified ? "Yes" : row.verificationStatus}</div>
                  <div><span className="font-semibold text-slate-900">Handled:</span> {row.handled ? "Yes" : "No"}</div>
                  <div><span className="font-semibold text-slate-900">Received:</span> {dateTime(row.createdAt)}</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">Preview:</span> {row.syncPreview}</div>
                <div className="mt-2 rounded-xl bg-white p-3 text-xs leading-5 text-slate-600"><span className="font-semibold text-slate-900">First fix:</span> {row.firstFix}</div>
              </div>
            ))}
          </div>
        </div>
      </div>

      <div className="grid gap-4 lg:grid-cols-2">
        <div className="rounded-2xl border border-slate-100 bg-white p-4">
          <h3 className="text-sm font-semibold text-slate-900">Environment and approval posture</h3>
          <div className="mt-3 grid gap-2 text-sm text-slate-600 md:grid-cols-2">
            <div className="rounded-xl bg-slate-50 p-3"><span className="font-semibold text-slate-900">Stripe mode:</span> {review.environment.stripeMode}</div>
            <div className="rounded-xl bg-slate-50 p-3"><span className="font-semibold text-slate-900">Webhook secret:</span> {review.environment.webhookSecretConfigured ? "Present" : "Missing"}</div>
            <div className="rounded-xl bg-slate-50 p-3"><span className="font-semibold text-slate-900">Checkout switches:</span> {review.approvalSummary.approvedCheckoutSwitches} approved</div>
            <div className="rounded-xl bg-slate-50 p-3"><span className="font-semibold text-slate-900">URL readiness:</span> {review.approvalSummary.checkoutUrlReadinessApproved ? "Approved" : "Not approved"}</div>
            <div className="rounded-xl bg-slate-50 p-3"><span className="font-semibold text-slate-900">Webhook intake:</span> {review.environment.webhookIntakeFlagRequested ? "On" : "Off"}</div>
            <div className="rounded-xl bg-slate-50 p-3"><span className="font-semibold text-slate-900">Subscription sync:</span> {review.environment.subscriptionSyncFlagRequested ? "On" : "Off"}</div>
            <div className="rounded-xl bg-slate-50 p-3"><span className="font-semibold text-slate-900">Test mutation:</span> {review.environment.testSyncMutationFlagRequested ? "On" : "Off"}</div>
            <div className="rounded-xl bg-slate-50 p-3"><span className="font-semibold text-slate-900">Trial conversion:</span> {review.environment.trialToPaidReviewOnly ? "Review-only" : "Flag conflict"}</div>
          </div>
        </div>
        <div className="rounded-2xl border border-amber-100 bg-amber-50 p-4 text-sm leading-6 text-amber-800">
          <span className="font-semibold">Safety lock:</span> v449 only permits verified Stripe test webhook provider-sync field mutation behind explicit flags. It does not change workspace subscription status, convert trials to paid, collect payments, activate customer portal access, enforce hard billing gates, change broker distribution, change owned portal rules, or change internal load-board access.
        </div>
      </div>
    </section>
  );
}
