"use client";

import { useEffect, useMemo, useState } from 'react';
import type { FormEvent, ReactNode } from 'react';
import { apiGet, apiPatch, apiPost } from '@/lib/api';
import type { Organization, User } from '@/types';
import {
  evaluateFeatureAccess,
  evaluateSubscriptionLimits,
  getStagedPlanForWorkspace,
  planLimitSummary,
  subscriptionFirstFix,
  type SubscriptionFeatureSignal,
  type SubscriptionLimitSignal,
  type SubscriptionPlanDraft,
} from '@/src/modules/subscriptions/subscription-entitlements';
import { evaluateWorkspaceAddOnReadiness, type WorkspaceAddOnReadinessSnapshot, type SubscriptionAddOnReadinessItem } from '@/src/modules/subscriptions/subscription-add-on-readiness';
import {
  evaluateWorkspaceSubscriptionEntitlements,
  type EntitlementFeatureState,
  type EntitlementLimitState,
  type WorkspaceEntitlementSnapshot,
} from '@/src/modules/subscriptions/subscription-entitlement-evaluator';

type WorkspaceRow = Organization & {
  users?: Array<Pick<User, 'id' | 'email' | 'firstName' | 'lastName' | 'isActive' | 'role'>>;
  workspaceSubscription?: { id: string; status: string; subscriptionPlanId: string; billingProvider?: string | null; billingMode?: string | null; providerSyncStatus?: string | null; stripeCustomerId?: string | null; stripeSubscriptionId?: string | null; stripeSubscriptionItemId?: string | null; billingProviderStatus?: string | null; lastProviderSyncAt?: string | null; plan: SubscriptionPlanDraft } | null;
};

type ReadinessStatus = 'Ready' | 'Check' | 'Blocked';
type AdminWorkspaceView = 'readiness' | 'create' | 'roster' | 'identity' | 'team' | 'dispatch' | 'documents' | 'billing' | 'subscriptions' | 'entitlements' | 'addOns' | 'stripeReadiness' | 'stripeScaffold' | 'stripeSyncReview' | 'stripeWebhooks' | 'operations' | 'all';
type ReadinessItem = { key: string; label: string; status: ReadinessStatus; result: string; simpleAction: string };

type StripeReadiness = {
  configured: boolean;
  mode: string;
  secretKeyConfigured: boolean;
  publishableKeyConfigured: boolean;
  webhookSecretConfigured: boolean;
  chargingEnabled: boolean;
  checkoutEnabled: boolean;
  customerPortalEnabled: boolean;
  provider: string;
  firstFix: string;
  safetyNote: string;
};

type StripeSyncReview = {
  mode: string;
  overallStatus: string;
  stripeStatus: string;
  savedCustomerId: string;
  stripeCustomerMatch: boolean;
  savedSubscriptionId: string;
  savedSubscriptionItemId: string;
  selectedPlanPriceId: string;
  matchingItemId: string;
  priceMatch: boolean;
  providerSyncStatus: string;
  firstFix: string;
  safetyNote: string;
};

type StripeWebhookEventLog = {
  id: string;
  eventId: string;
  eventType: string;
  livemode: boolean;
  mode: string;
  signatureVerified: boolean;
  verificationStatus: string;
  handled: boolean;
  matchedWorkspaceName: string;
  providerSyncOutcome: string;
  workspaceSubscriptionStatus: string;
  errorNote: string;
  firstFix: string;
  createdAt: string;
};

type WorkspacePreview = {
  items: ReadinessItem[];
  overallStatus: ReadinessStatus;
  safeLaunch: string;
  firstFix: string;
  nextAction: string;
  identity: ReadinessItem[];
  team: ReadinessItem[];
  dispatch: ReadinessItem[];
  documents: ReadinessItem[];
  billing: ReadinessItem[];
  notifications: ReadinessItem[];
  subscription: {
    plan: SubscriptionPlanDraft;
    usage: { users: number; trucks: number; phoneNumbers: number };
    limits: SubscriptionLimitSignal[];
    features: SubscriptionFeatureSignal[];
    firstFix: string;
    summary: string;
    entitlements: WorkspaceEntitlementSnapshot;
    addOns: WorkspaceAddOnReadinessSnapshot;
  };
};

const BUILD_REVIEW_STORAGE_KEY = 'dispatchspot-super-admin-build-review';

function statusClasses(status: ReadinessStatus) {
  if (status === 'Ready') return 'bg-emerald-100 text-emerald-700';
  if (status === 'Check') return 'bg-amber-100 text-amber-700';
  return 'bg-rose-100 text-rose-700';
}

function limitStatusClasses(status: SubscriptionLimitSignal['status']) {
  return status === 'Included' ? 'bg-emerald-100 text-emerald-700' : 'bg-rose-100 text-rose-700';
}

function featureStatusClasses(status: SubscriptionFeatureSignal['status']) {
  return status === 'Included' ? 'bg-emerald-100 text-emerald-700' : 'bg-slate-100 text-slate-600';
}

function entitlementStatusClasses(status: EntitlementFeatureState['status'] | EntitlementLimitState['status'] | WorkspaceEntitlementSnapshot['overallStatus']) {
  if (status === 'Allowed' || status === 'Within plan') return 'bg-emerald-100 text-emerald-700';
  if (status === 'Needs review' || status === 'Over limit' || status === 'Locked') return 'bg-amber-100 text-amber-700';
  return 'bg-rose-100 text-rose-700';
}

function entitlementFeatureCard(item: EntitlementFeatureState) {
  return (
    <div key={item.key} className="rounded-xl border border-slate-100 bg-white p-4 text-sm shadow-sm">
      <div className="flex items-start justify-between gap-3">
        <div className="font-semibold text-slate-900">{item.label}</div>
        <span className={`shrink-0 rounded-full px-2 py-0.5 text-[10px] font-semibold ${entitlementStatusClasses(item.status)}`}>{item.status}</span>
      </div>
      <div className="mt-2 text-xs leading-5 text-slate-600">Workspace Admin mode: {item.workspaceAdminMode}</div>
      <div className="mt-3 rounded-lg bg-slate-50 px-3 py-2 text-xs font-medium text-slate-700">{item.superAdminAction}</div>
    </div>
  );
}

function entitlementLimitCard(item: EntitlementLimitState) {
  return (
    <div key={item.key} className="rounded-xl border border-slate-100 bg-white p-4 text-sm shadow-sm">
      <div className="flex items-start justify-between gap-3">
        <div className="font-semibold text-slate-900">{item.label}</div>
        <span className={`shrink-0 rounded-full px-2 py-0.5 text-[10px] font-semibold ${entitlementStatusClasses(item.status)}`}>{item.status}</span>
      </div>
      <div className="mt-2 text-xs leading-5 text-slate-600">Using {item.used}. Included: {item.included}. Over: {item.over}.</div>
      <div className="mt-2 text-xs leading-5 text-slate-600">Workspace Admin mode: {item.workspaceAdminMode}</div>
      <div className="mt-3 rounded-lg bg-slate-50 px-3 py-2 text-xs font-medium text-slate-700">{item.superAdminAction}</div>
    </div>
  );
}

function addOnStatusClasses(status: SubscriptionAddOnReadinessItem["status"]) {
  if (status === "Ready add-on") return "bg-blue-100 text-blue-700";
  if (status === "Included") return "bg-emerald-100 text-emerald-700";
  if (status === "Plan upgrade") return "bg-amber-100 text-amber-700";
  return "bg-slate-100 text-slate-600";
}

function addOnReadinessCard(item: SubscriptionAddOnReadinessItem) {
  return (
    <div key={item.key} className="rounded-xl border border-slate-100 bg-white p-4 text-sm shadow-sm">
      <div className="flex items-start justify-between gap-3">
        <div className="font-semibold text-slate-900">{item.label}</div>
        <span className={`shrink-0 rounded-full px-2 py-0.5 text-[10px] font-semibold ${addOnStatusClasses(item.status)}`}>{item.status}</span>
      </div>
      <div className="mt-2 text-xs leading-5 text-slate-600">Included: {item.included}. Used: {item.used}. Over: {item.over}.</div>
      <div className="mt-1 text-xs leading-5 text-slate-600">Price: {item.unitPrice === null ? "Set later" : `${item.unitPrice}/month`}</div>
      <div className="mt-1 text-xs leading-5 text-slate-600">Billing path: {item.billingPath}</div>
      <div className="mt-3 rounded-lg bg-slate-50 px-3 py-2 text-xs font-medium text-slate-700">{item.superAdminAction}</div>
    </div>
  );
}

function adminName(user: Pick<User, 'email' | 'firstName' | 'lastName'>) {
  return [user.firstName, user.lastName].filter(Boolean).join(' ') || user.email;
}

function readinessCard(item: ReadinessItem) {
  return (
    <div key={item.key} className="rounded-xl border border-slate-100 bg-white p-4 text-sm shadow-sm">
      <div className="flex items-start justify-between gap-3">
        <div className="font-semibold text-slate-900">{item.label}</div>
        <span className={`shrink-0 rounded-full px-2 py-0.5 text-[10px] font-semibold ${statusClasses(item.status)}`}>{item.status}</span>
      </div>
      <div className="mt-2 text-xs leading-5 text-slate-600">{item.result}</div>
      <div className="mt-3 rounded-lg bg-slate-50 px-3 py-2 text-xs font-medium text-slate-700">{item.simpleAction}</div>
    </div>
  );
}

function subscriptionLimitCard(item: SubscriptionLimitSignal) {
  return (
    <div key={item.key} className="rounded-xl border border-slate-100 bg-white p-4 text-sm shadow-sm">
      <div className="flex items-start justify-between gap-3">
        <div className="font-semibold text-slate-900">{item.label}</div>
        <span className={`shrink-0 rounded-full px-2 py-0.5 text-[10px] font-semibold ${limitStatusClasses(item.status)}`}>{item.status}</span>
      </div>
      <div className="mt-2 text-xs leading-5 text-slate-600">Using {item.used}. Included: {item.included}. Over: {item.over}.</div>
      <div className="mt-3 rounded-lg bg-slate-50 px-3 py-2 text-xs font-medium text-slate-700">{item.note}</div>
    </div>
  );
}

function subscriptionFeatureCard(item: SubscriptionFeatureSignal) {
  return (
    <div key={item.key} className="rounded-xl border border-slate-100 bg-white p-3 text-sm shadow-sm">
      <div className="flex items-center justify-between gap-3">
        <div className="font-semibold text-slate-900">{item.label}</div>
        <span className={`shrink-0 rounded-full px-2 py-0.5 text-[10px] font-semibold ${featureStatusClasses(item.status)}`}>{item.status}</span>
      </div>
    </div>
  );
}

function countLabel(value: number | undefined, singular: string, plural = `${singular}s`) {
  const count = value ?? 0;
  return `${count} ${count === 1 ? singular : plural}`;
}

function billingProviderLabel(value?: string | null) {
  if (value === 'STRIPE') return 'Stripe';
  if (value === 'MANUAL') return 'Manual';
  return 'None';
}

function billingModeLabel(value?: string | null) {
  if (value === 'TEST') return 'Test';
  if (value === 'LIVE') return 'Live';
  if (value === 'MANUAL') return 'Manual';
  return 'Not connected';
}

function providerSyncStatusLabel(value?: string | null) {
  if (value === 'READY') return 'Ready';
  if (value === 'SYNCED') return 'Synced';
  if (value === 'NEEDS_REVIEW') return 'Needs review';
  if (value === 'ERROR') return 'Error';
  return 'Not ready';
}

function stripeReadinessStatus(item: { ok: boolean; review?: boolean }): ReadinessStatus {
  if (item.ok) return 'Ready';
  if (item.review) return 'Check';
  return 'Blocked';
}

function stripeReadinessCard(label: string, status: ReadinessStatus, note: string) {
  return (
    <div key={label} className="rounded-xl border border-slate-100 bg-white p-4 text-sm shadow-sm">
      <div className="flex items-start justify-between gap-3">
        <div className="font-semibold text-slate-900">{label}</div>
        <span className={`shrink-0 rounded-full px-2 py-0.5 text-[10px] font-semibold ${statusClasses(status)}`}>{status}</span>
      </div>
      <div className="mt-2 text-xs leading-5 text-slate-600">{note}</div>
    </div>
  );
}

function stripeIdStatus(value: string, expectedPrefix: string): ReadinessStatus {
  const clean = value.trim();
  if (!clean) return 'Blocked';
  return clean.startsWith(expectedPrefix) ? 'Ready' : 'Check';
}

function previewStripeMetadata(workspace: WorkspaceRow | null, plan: SubscriptionPlanDraft | undefined) {
  return {
    dispatchSpotWorkspaceId: workspace?.id ?? 'workspace-id',
    dispatchSpotWorkspaceSlug: workspace?.slug ?? 'workspace-slug',
    dispatchSpotPlanName: plan?.name ?? 'selected-plan',
    billingPath: 'platform-subscription',
    mode: 'test-only-scaffold',
  };
}

function buildWorkspacePreview(workspace: WorkspaceRow | null): WorkspacePreview | null {
  if (!workspace) return null;
  const users = workspace.users ?? [];
  const activeUsers = users.filter((user) => user.isActive);
  const adminUsers = activeUsers.filter((user) => user.role === 'ORG_ADMIN');
  const dispatchers = activeUsers.filter((user) => user.role === 'DISPATCHER');
  const driverPortalUsers = activeUsers.filter((user) => user.role === 'COMPANY_DRIVER');
  const ownerOperatorUsers = activeUsers.filter((user) => user.role === 'OWNER_OPERATOR');
  const accountingUsers = activeUsers.filter((user) => user.role === 'ACCOUNTING');
  const count = workspace._count ?? {};
  const usersReady = activeUsers.length > 0 && adminUsers.length > 0;
  const dispatcherCoverage: ReadinessStatus = dispatchers.length > 0 ? 'Ready' : usersReady ? 'Check' : 'Blocked';
  const hasAssets = Boolean((count.trucks ?? 0) > 0 && (count.drivers ?? 0) > 0);
  const hasOperatingRecords = Boolean((count.trucks ?? 0) > 0 || (count.drivers ?? 0) > 0 || (count.loads ?? 0) > 0);
  const hasLoads = Boolean((count.loads ?? 0) > 0);
  const hasDocuments = Boolean((count.documents ?? 0) > 0);
  const hasPayments = Boolean((count.loadPayments ?? 0) > 0);
  const hasContacts = Boolean((count.brokers ?? 0) > 0 || (count.companies ?? 0) > 0 || (count.shippers ?? 0) > 0 || (count.ownerOperators ?? 0) > 0);
  const hasNotificationPrefs = Boolean((count.notificationPreferences ?? 0) > 0);
  const phoneStatus: ReadinessStatus = workspace.isActive ? 'Check' : 'Blocked';

  const identity: ReadinessItem[] = [
    { key: 'name', label: 'Workspace name', status: workspace.name?.trim() ? 'Ready' : 'Blocked', result: workspace.name?.trim() ? `Workspace name is ${workspace.name}.` : 'Workspace name needs review.', simpleAction: 'Check company name' },
    { key: 'slug', label: 'Workspace link', status: workspace.slug?.trim() ? 'Ready' : 'Blocked', result: workspace.slug?.trim() ? `Workspace link is /${workspace.slug}.` : 'Workspace link is missing.', simpleAction: 'Check workspace link' },
    { key: 'active', label: 'Workspace state', status: workspace.isActive ? 'Ready' : 'Blocked', result: workspace.isActive ? 'Workspace is active.' : 'Workspace is inactive and should not be launched.', simpleAction: workspace.isActive ? 'Keep active' : 'Reactivate when ready' },
  ];

  const team: ReadinessItem[] = [
    { key: 'admins', label: 'Workspace admins', status: adminUsers.length > 0 ? 'Ready' : 'Blocked', result: adminUsers.length > 0 ? `${adminUsers.length} active workspace admin${adminUsers.length === 1 ? '' : 's'} found.` : 'At least one active workspace admin is needed.', simpleAction: 'Review admin users' },
    { key: 'dispatchers', label: 'Dispatcher coverage', status: dispatcherCoverage, result: dispatchers.length > 0 ? `${dispatchers.length} dispatcher${dispatchers.length === 1 ? '' : 's'} available.` : usersReady ? 'Workspace has admins, but no dispatcher is visible yet.' : 'Add workspace admin first, then review dispatchers.', simpleAction: 'Check dispatch team' },
    { key: 'externalUsers', label: 'Portal users', status: 'Check', result: driverPortalUsers.length + ' driver portal, ' + ownerOperatorUsers.length + ' owner operator, and ' + accountingUsers.length + ' accounting user records visible in this preview.', simpleAction: 'Review portal coverage later' },
  ];

  const dispatch: ReadinessItem[] = [
    { key: 'assets', label: 'Truck and driver setup', status: hasAssets ? 'Ready' : hasOperatingRecords ? 'Check' : 'Blocked', result: `${countLabel(count.trucks, 'truck')} and ${countLabel(count.drivers, 'driver')} visible.`, simpleAction: 'Review assets' },
    { key: 'loads', label: 'Load workflow', status: hasLoads ? 'Ready' : hasOperatingRecords ? 'Check' : 'Blocked', result: hasLoads ? `${count.loads} load record${count.loads === 1 ? '' : 's'} visible for workflow review.` : 'No load records are visible yet.', simpleAction: 'Review load flow' },
    { key: 'contacts', label: 'Customer and broker records', status: hasContacts ? 'Ready' : 'Check', result: `${countLabel(count.brokers, 'broker')}, ${countLabel(count.shippers, 'shipper')}, ${countLabel(count.companies, 'company', 'companies')}, and ${countLabel(count.ownerOperators, 'owner operator')} visible.`, simpleAction: 'Review business contacts' },
  ];

  const documents: ReadinessItem[] = [
    { key: 'documentCount', label: 'Document records', status: hasDocuments ? 'Ready' : 'Check', result: hasDocuments ? `${count.documents} document record${count.documents === 1 ? '' : 's'} visible.` : 'No document records are visible yet.', simpleAction: 'Check document intake' },
    { key: 'compliancePath', label: 'Compliance path', status: hasDocuments && hasLoads ? 'Ready' : 'Check', result: hasDocuments && hasLoads ? 'Documents and loads are both present for compliance review.' : 'Compliance review needs documents and live load context.', simpleAction: 'Review compliance readiness' },
  ];

  const billing: ReadinessItem[] = [
    { key: 'payments', label: 'Load payment records', status: hasPayments ? 'Ready' : hasLoads ? 'Check' : 'Blocked', result: hasPayments ? `${count.loadPayments} load payment record${count.loadPayments === 1 ? '' : 's'} visible.` : hasLoads ? 'Loads exist, but payment records need review.' : 'Add load workflow before payment review.', simpleAction: 'Review payment readiness' },
    { key: 'billingFlow', label: 'Billing workflow', status: hasPayments && hasLoads ? 'Ready' : 'Check', result: hasPayments && hasLoads ? 'Billing has load and payment context.' : 'Billing should be reviewed after load activity is present.', simpleAction: 'Check billing handoff' },
  ];

  const notifications: ReadinessItem[] = [
    { key: 'notificationPrefs', label: 'Notification setup', status: hasNotificationPrefs ? 'Ready' : 'Check', result: hasNotificationPrefs ? `${count.notificationPreferences} notification preference record${count.notificationPreferences === 1 ? '' : 's'} visible.` : 'No workspace notification preference records are visible yet.', simpleAction: 'Review notification page' },
    { key: 'phone', label: 'Business phone setup', status: phoneStatus, result: workspace.isActive ? 'Phone setup should be reviewed from the Super Admin phone page before live calling.' : 'Workspace must be active before phone readiness can be trusted.', simpleAction: 'Review phone setup' },
  ];

  const subscriptionUsage = {
    users: count.users ?? activeUsers.length,
    trucks: count.trucks ?? 0,
    phoneNumbers: workspace.isActive ? 1 : 0,
  };
  const subscriptionPlan = workspace.workspaceSubscription?.plan ?? getStagedPlanForWorkspace(subscriptionUsage);
  const subscriptionLimits = evaluateSubscriptionLimits(subscriptionPlan, subscriptionUsage);
  const subscriptionFeatures = evaluateFeatureAccess(subscriptionPlan);
  const subscriptionFix = subscriptionFirstFix(subscriptionPlan, subscriptionUsage);
  const entitlementSnapshot = evaluateWorkspaceSubscriptionEntitlements({
    plan: subscriptionPlan,
    usage: subscriptionUsage,
    subscriptionStatus: workspace.workspaceSubscription?.status ?? 'TRIAL',
  });
  const addOnSnapshot = evaluateWorkspaceAddOnReadiness({ plan: subscriptionPlan, usage: subscriptionUsage });

  const items = [identity[0], team[0], team[1], notifications[1], dispatch[1]];
  const allSignals = [...identity, ...team, ...dispatch, ...documents, ...billing, ...notifications];
  const blocked = allSignals.filter((item) => item.status === 'Blocked');
  const check = allSignals.filter((item) => item.status === 'Check');
  const overallStatus: ReadinessStatus = blocked.length ? 'Blocked' : check.length ? 'Check' : 'Ready';
  const firstFix = blocked[0] ?? check[0] ?? allSignals[0];

  return {
    items,
    identity,
    team,
    dispatch,
    documents,
    billing,
    notifications,
    subscription: {
      plan: subscriptionPlan,
      usage: subscriptionUsage,
      limits: subscriptionLimits,
      features: subscriptionFeatures,
      firstFix: subscriptionFix,
      summary: `${workspace.name} is on ${subscriptionPlan.name}: ${planLimitSummary(subscriptionPlan)}.`,
      entitlements: entitlementSnapshot,
      addOns: addOnSnapshot,
    },
    overallStatus,
    safeLaunch: overallStatus === 'Ready' ? 'Ready for a small admin-led launch check.' : overallStatus === 'Check' ? 'Close, but Super Admin should review one area first.' : 'Not ready for live operation yet.',
    firstFix: firstFix ? `${firstFix.label}: ${firstFix.result}` : 'Review workspace setup.',
    nextAction: firstFix?.simpleAction ?? 'Review workspace setup',
  };
}

function SectionShell({ title, subtitle, children }: { title: string; subtitle: string; children: ReactNode }) {
  return <section className="rounded-2xl border bg-white p-6 shadow-sm"><h2 className="text-lg font-semibold text-slate-900">{title}</h2><p className="mt-1 text-sm leading-6 text-slate-500">{subtitle}</p><div className="mt-5">{children}</div></section>;
}

export function AdminWorkspacesPageClient({ view = 'all' }: { view?: AdminWorkspaceView }) {
  const [currentUser, setCurrentUser] = useState<User | null>(null);
  const [workspaces, setWorkspaces] = useState<WorkspaceRow[]>([]);
  const [selectedWorkspaceId, setSelectedWorkspaceId] = useState<string | null>(null);
  const [buildReviewOn, setBuildReviewOn] = useState(false);
  const [plans, setPlans] = useState<SubscriptionPlanDraft[]>([]);
  const [stripeReadiness, setStripeReadiness] = useState<StripeReadiness | null>(null);
  const [assignmentPlanId, setAssignmentPlanId] = useState('');
  const [assignmentStatus, setAssignmentStatus] = useState('TRIAL');
  const [assignmentBillingProvider, setAssignmentBillingProvider] = useState('Stripe');
  const [assignmentBillingMode, setAssignmentBillingMode] = useState('Not connected');
  const [assignmentProviderSyncStatus, setAssignmentProviderSyncStatus] = useState('Not ready');
  const [stripeCustomerId, setStripeCustomerId] = useState('');
  const [stripeSubscriptionId, setStripeSubscriptionId] = useState('');
  const [stripeSubscriptionItemId, setStripeSubscriptionItemId] = useState('');
  const [billingProviderStatus, setBillingProviderStatus] = useState('');
  const [stripeCustomerCreating, setStripeCustomerCreating] = useState(false);
  const [stripeSubscriptionCreating, setStripeSubscriptionCreating] = useState(false);
  const [stripeSyncReviewing, setStripeSyncReviewing] = useState(false);
  const [stripeSyncReview, setStripeSyncReview] = useState<StripeSyncReview | null>(null);
  const [stripeWebhookEvents, setStripeWebhookEvents] = useState<StripeWebhookEventLog[]>([]);
  const [stripeWebhookEventsLoading, setStripeWebhookEventsLoading] = useState(false);
  const [stripeActionMessage, setStripeActionMessage] = useState('');
  const [form, setForm] = useState({ companyName: '', companySlug: '', adminFirstName: '', adminLastName: '', adminEmail: '', adminPassword: '' });
  const [error, setError] = useState<string | null>(null);
  const [loaded, setLoaded] = useState(false);
  const [saving, setSaving] = useState(false);
  const isSuperAdmin = !!currentUser?.isSuperAdmin;

  async function loadAll() {
    try {
      setError(null);
      const me = await apiGet<{ user: User }>('/api/auth/me');
      setCurrentUser(me.user);
      if (!me.user.isSuperAdmin) { setLoaded(true); return; }
      const [data, planData, stripeData] = await Promise.all([
        apiGet<{ workspaces: WorkspaceRow[] }>('/api/workspaces'),
        apiGet<{ plans: SubscriptionPlanDraft[] }>('/api/subscriptions'),
        apiGet<{ readiness: StripeReadiness }>('/api/subscriptions/stripe-readiness'),
      ]);
      setWorkspaces(data.workspaces);
      setPlans(planData.plans);
      setStripeReadiness(stripeData.readiness);
      setSelectedWorkspaceId((current) => current ?? data.workspaces[0]?.id ?? null);
    } catch (err: any) {
      setError(err?.message ?? 'Failed to load workspace control');
    } finally { setLoaded(true); }
  }

  useEffect(() => { loadAll(); }, []);

  useEffect(() => {
    function readBuildReview() {
      try { setBuildReviewOn(window.localStorage.getItem(BUILD_REVIEW_STORAGE_KEY) === 'on'); } catch { setBuildReviewOn(false); }
    }
    readBuildReview();
    window.addEventListener('dispatchspot-build-review-change', readBuildReview as EventListener);
    window.addEventListener('storage', readBuildReview);
    return () => {
      window.removeEventListener('dispatchspot-build-review-change', readBuildReview as EventListener);
      window.removeEventListener('storage', readBuildReview);
    };
  }, []);

  async function createWorkspace(e: FormEvent) {
    e.preventDefault();
    try {
      setSaving(true); setError(null);
      await apiPost('/api/workspaces', form);
      setForm({ companyName: '', companySlug: '', adminFirstName: '', adminLastName: '', adminEmail: '', adminPassword: '' });
      await loadAll();
    } catch (err: any) { setError(err?.message ?? 'Failed to create workspace'); }
    finally { setSaving(false); }
  }

  async function toggleWorkspace(workspace: WorkspaceRow) {
    try {
      setError(null);
      await apiPost(`/api/workspaces/${workspace.id}/${workspace.isActive ? 'deactivate' : 'reactivate'}`, {});
      await loadAll();
    } catch (err: any) { setError(err?.message ?? 'Failed to update workspace'); }
  }

  const stats = useMemo(() => ([
    { label: 'Workspaces', value: String(workspaces.length) },
    { label: 'Active', value: String(workspaces.filter((w) => w.isActive).length) },
    { label: 'Needs review', value: String(workspaces.filter((w) => buildWorkspacePreview(w)?.overallStatus !== 'Ready').length) },
  ]), [workspaces]);
  const selectedWorkspace = useMemo(() => workspaces.find((workspace) => workspace.id === selectedWorkspaceId) ?? workspaces[0] ?? null, [selectedWorkspaceId, workspaces]);
  const preview = useMemo(() => buildWorkspacePreview(selectedWorkspace), [selectedWorkspace]);

  useEffect(() => {
    if (!selectedWorkspace) return;
    setAssignmentPlanId(selectedWorkspace.workspaceSubscription?.subscriptionPlanId ?? preview?.subscription.plan.id ?? plans[0]?.id ?? '');
    setAssignmentStatus(selectedWorkspace.workspaceSubscription?.status ?? 'TRIAL');
    setAssignmentBillingProvider(billingProviderLabel(selectedWorkspace.workspaceSubscription?.billingProvider));
    setAssignmentBillingMode(billingModeLabel(selectedWorkspace.workspaceSubscription?.billingMode));
    setAssignmentProviderSyncStatus(providerSyncStatusLabel(selectedWorkspace.workspaceSubscription?.providerSyncStatus));
    setStripeCustomerId(selectedWorkspace.workspaceSubscription?.stripeCustomerId ?? '');
    setStripeSubscriptionId(selectedWorkspace.workspaceSubscription?.stripeSubscriptionId ?? '');
    setStripeSubscriptionItemId(selectedWorkspace.workspaceSubscription?.stripeSubscriptionItemId ?? '');
    setBillingProviderStatus(selectedWorkspace.workspaceSubscription?.billingProviderStatus ?? '');
  }, [selectedWorkspace?.id, selectedWorkspace?.workspaceSubscription?.subscriptionPlanId, selectedWorkspace?.workspaceSubscription?.status, selectedWorkspace?.workspaceSubscription?.billingProvider, selectedWorkspace?.workspaceSubscription?.billingMode, selectedWorkspace?.workspaceSubscription?.providerSyncStatus, selectedWorkspace?.workspaceSubscription?.stripeCustomerId, selectedWorkspace?.workspaceSubscription?.stripeSubscriptionId, selectedWorkspace?.workspaceSubscription?.stripeSubscriptionItemId, selectedWorkspace?.workspaceSubscription?.billingProviderStatus, preview?.subscription.plan.id, plans]);

  async function assignWorkspaceSubscription() {
    if (!selectedWorkspace || !assignmentPlanId) return;
    try {
      setError(null);
      await apiPatch(`/api/workspaces/${selectedWorkspace.id}/subscription`, {
        subscriptionPlanId: assignmentPlanId,
        status: assignmentStatus,
        billingProvider: assignmentBillingProvider,
        billingMode: assignmentBillingMode,
        providerSyncStatus: assignmentProviderSyncStatus,
        stripeCustomerId,
        stripeSubscriptionId,
        stripeSubscriptionItemId,
        billingProviderStatus,
      });
      await loadAll();
    } catch (err: any) {
      setError(err?.message ?? 'Failed to save workspace subscription');
    }
  }

  async function saveStripeTestScaffold() {
    if (!selectedWorkspace || !assignmentPlanId) return;
    try {
      setError(null);
      await apiPatch(`/api/workspaces/${selectedWorkspace.id}/subscription`, {
        subscriptionPlanId: assignmentPlanId,
        status: assignmentStatus,
        billingProvider: 'Stripe',
        billingMode: 'Test',
        providerSyncStatus: stripeCustomerId.trim() && stripeSubscriptionId.trim() ? 'Synced' : 'Ready',
        stripeCustomerId,
        stripeSubscriptionId,
        stripeSubscriptionItemId,
        billingProviderStatus: billingProviderStatus.trim() || 'Manual test-mode Stripe scaffold saved by Super Admin. No live charge was created.',
      });
      await loadAll();
    } catch (err: any) {
      setError(err?.message ?? 'Failed to save Stripe test scaffold');
    }
  }


  async function createStripeTestCustomer() {
    if (!selectedWorkspace) return;
    try {
      setStripeCustomerCreating(true);
      setError(null);
      setStripeActionMessage('');
      const response = await apiPost<{ result: { customerId: string; safetyNote: string; providerSyncStatus: string } }>('/api/subscriptions/stripe-test/customer', {
        organizationId: selectedWorkspace.id,
      });
      setStripeCustomerId(response.result.customerId);
      setBillingProviderStatus(response.result.safetyNote);
      setStripeActionMessage('Stripe test customer saved: ' + response.result.customerId);
      await loadAll();
    } catch (err: any) {
      setError(err?.message ?? 'Failed to create Stripe test customer');
    } finally {
      setStripeCustomerCreating(false);
    }
  }


  async function createStripeTestSubscription() {
    if (!selectedWorkspace) return;
    try {
      setStripeSubscriptionCreating(true);
      setError(null);
      setStripeActionMessage('');
      const response = await apiPost<{ result: { subscriptionId: string; subscriptionItemId: string; safetyNote: string; providerSyncStatus: string } }>('/api/subscriptions/stripe-test/subscription', {
        organizationId: selectedWorkspace.id,
      });
      setStripeSubscriptionId(response.result.subscriptionId);
      setStripeSubscriptionItemId(response.result.subscriptionItemId);
      setBillingProviderStatus(response.result.safetyNote);
      setStripeActionMessage('Stripe test subscription saved: ' + response.result.subscriptionId);
      await loadAll();
    } catch (err: any) {
      setError(err?.message ?? 'Failed to create Stripe test subscription');
    } finally {
      setStripeSubscriptionCreating(false);
    }
  }

  async function reviewStripeTestSync() {
    if (!selectedWorkspace) return;
    try {
      setStripeSyncReviewing(true);
      setError(null);
      setStripeActionMessage('');
      const response = await apiPost<{ result: StripeSyncReview }>('/api/subscriptions/stripe-test/sync-review', {
        organizationId: selectedWorkspace.id,
      });
      setStripeSyncReview(response.result);
      setBillingProviderStatus(response.result.firstFix);
      setStripeActionMessage('Stripe sync review: ' + response.result.overallStatus);
      await loadAll();
    } catch (err: any) {
      setError(err?.message ?? 'Failed to review Stripe test sync');
    } finally {
      setStripeSyncReviewing(false);
    }
  }

  async function loadStripeWebhookEvents(organizationId: string) {
    try {
      setStripeWebhookEventsLoading(true);
      const response = await apiGet<{ events: StripeWebhookEventLog[] }>(`/api/subscriptions/stripe-test/webhook-events?organizationId=${organizationId}`);
      setStripeWebhookEvents(response.events);
    } catch {
      setStripeWebhookEvents([]);
    } finally {
      setStripeWebhookEventsLoading(false);
    }
  }

  useEffect(() => {
    if (!selectedWorkspace?.id) return;
    loadStripeWebhookEvents(selectedWorkspace.id);
  }, [selectedWorkspace?.id]);

  if (!loaded) return <div className="text-sm text-gray-500">Loading workspace control...</div>;
  if (!isSuperAdmin) return <div className="rounded-2xl border border-amber-200 bg-amber-50 p-6 text-sm text-amber-900">Super admin access is required.</div>;

  const showReadiness = view === 'all' || view === 'readiness';
  const showCreate = view === 'all' || view === 'create';
  const showRoster = view === 'all' || view === 'roster';
  const showIdentity = view === 'identity' || view === 'operations';
  const showTeam = view === 'team' || view === 'operations';
  const showDispatch = view === 'dispatch' || view === 'operations';
  const showDocuments = view === 'documents' || view === 'operations';
  const showBilling = view === 'billing' || view === 'operations';
  const showOperationsSummary = view === 'operations';
  const showSubscriptions = view === 'subscriptions';
  const showEntitlements = view === 'entitlements';
  const showAddOns = view === 'addOns';
  const showStripeReadiness = view === 'stripeReadiness';
  const showStripeScaffold = view === 'stripeScaffold';
  const showStripeSyncReview = view === 'stripeSyncReview';
  const showStripeWebhooks = view === 'stripeWebhooks';

  const workspacePicker = (
    <div className="rounded-2xl border border-blue-100 bg-white p-4">
      <label className="block text-sm"><div className="mb-1 font-semibold text-slate-900">Workspace to review</div><select value={selectedWorkspace?.id ?? ''} onChange={(e) => setSelectedWorkspaceId(e.target.value)} className="w-full rounded-xl border px-3 py-2">{workspaces.map((workspace) => <option key={workspace.id} value={workspace.id}>{workspace.name}</option>)}</select></label>
      {selectedWorkspace ? <div className="mt-4 space-y-2 text-sm text-slate-600"><div><span className="font-semibold text-slate-900">Slug:</span> {selectedWorkspace.slug}</div><div><span className="font-semibold text-slate-900">Status:</span> {selectedWorkspace.isActive ? 'Active' : 'Inactive'}</div><div><span className="font-semibold text-slate-900">Admins:</span> {selectedWorkspace.users?.filter((user) => user.isActive && user.role === 'ORG_ADMIN').map(adminName).join(', ') || 'None found'}</div>{preview ? <div><span className="font-semibold text-slate-900">Plan:</span> {preview.subscription.plan.name}</div> : null}<button onClick={() => toggleWorkspace(selectedWorkspace)} className="mt-2 w-full rounded-xl border border-slate-200 bg-white px-3 py-2 text-sm font-semibold text-slate-700 hover:bg-slate-50">{selectedWorkspace.isActive ? 'Deactivate workspace' : 'Reactivate workspace'}</button></div> : null}
    </div>
  );

  return (
    <div className="space-y-6">
      {error ? <div className="rounded-xl border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">{error}</div> : null}
      {(showReadiness || view === 'operations' || showIdentity || showTeam || showDispatch || showDocuments || showBilling || showSubscriptions || showAddOns || showStripeReadiness || showStripeScaffold || showStripeSyncReview || showStripeWebhooks) && <div className="grid gap-4 md:grid-cols-3">{stats.map((s) => <div key={s.label} className="rounded-2xl border bg-white p-4 shadow-sm"><div className="text-sm text-gray-500">{s.label}</div><div className="mt-2 text-2xl font-semibold">{s.value}</div></div>)}</div>}
      {preview && showOperationsSummary ? <section className="rounded-2xl border border-indigo-100 bg-indigo-50 p-6 shadow-sm">
        <div className="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
          <div><div className="text-xs font-semibold uppercase tracking-[0.18em] text-indigo-700">Core AI operations</div><h2 className="mt-1 text-lg font-semibold text-slate-900">CORI operations review</h2><p className="mt-1 max-w-3xl text-sm leading-6 text-slate-600">Monitor operational health from Super Admin while Workspace Admin and dispatcher pages stay clean and focused on daily work.</p></div>
          <span className={`w-fit rounded-full px-3 py-1 text-xs font-semibold uppercase tracking-[0.14em] ${statusClasses(preview.overallStatus)}`}>{preview.overallStatus}</span>
        </div>
        <div className="mt-4 grid gap-4 lg:grid-cols-[320px_1fr]">
          {workspacePicker}
          <div className="space-y-4">
            <div className="rounded-2xl border border-indigo-100 bg-white p-4">
              <div className="flex flex-col gap-3 md:flex-row md:items-start md:justify-between">
                <div><div className="text-sm font-semibold text-slate-900">Operational command summary</div><div className="mt-1 text-sm leading-6 text-slate-600">Use this view to monitor the workspace without pushing review panels back into the normal user screens.</div></div>
                <div className="rounded-full bg-indigo-100 px-3 py-1 text-xs font-semibold text-indigo-700">Next action: {preview.nextAction}</div>
              </div>
              <div className="mt-4 grid gap-3 md:grid-cols-3">
                <div className="rounded-xl bg-slate-50 p-3 text-sm"><div className="font-semibold text-slate-900">Dashboard health</div><div className="mt-1 text-slate-600">{preview.safeLaunch}</div></div>
                <div className="rounded-xl bg-slate-50 p-3 text-sm"><div className="font-semibold text-slate-900">CORI guidance</div><div className="mt-1 text-slate-600">{preview.firstFix}</div></div>
                <div className="rounded-xl bg-slate-50 p-3 text-sm"><div className="font-semibold text-slate-900">Simplicity check</div><div className="mt-1 text-slate-600">Normal users should see one main action, not the full review logic.</div></div>
              </div>
            </div>
            <div className="grid gap-3 md:grid-cols-2 xl:grid-cols-3">
              <div className="rounded-xl border border-indigo-100 bg-white p-4 text-sm"><div className="font-semibold text-slate-900">Load flow</div><div className="mt-1 text-slate-600">{preview.dispatch[1]?.result ?? 'Review load workflow.'}</div><div className="mt-3 rounded-lg bg-indigo-50 px-3 py-2 text-xs font-medium text-indigo-800">Super Admin check: loads should have a clear next work step.</div></div>
              <div className="rounded-xl border border-indigo-100 bg-white p-4 text-sm"><div className="font-semibold text-slate-900">Document blockers</div><div className="mt-1 text-slate-600">{preview.documents[0]?.result ?? 'Review document intake.'}</div><div className="mt-3 rounded-lg bg-indigo-50 px-3 py-2 text-xs font-medium text-indigo-800">Super Admin check: missing paperwork should not hide invoice readiness.</div></div>
              <div className="rounded-xl border border-indigo-100 bg-white p-4 text-sm"><div className="font-semibold text-slate-900">Billing blockers</div><div className="mt-1 text-slate-600">{preview.billing[0]?.result ?? 'Review payment readiness.'}</div><div className="mt-3 rounded-lg bg-indigo-50 px-3 py-2 text-xs font-medium text-indigo-800">Super Admin check: billing should point to the next invoice or unpaid load.</div></div>
              <div className="rounded-xl border border-indigo-100 bg-white p-4 text-sm"><div className="font-semibold text-slate-900">Dispatch next action</div><div className="mt-1 text-slate-600">{preview.dispatch[0]?.simpleAction ?? 'Review truck and driver setup.'}</div><div className="mt-3 rounded-lg bg-indigo-50 px-3 py-2 text-xs font-medium text-indigo-800">Super Admin check: the dispatcher screen should not need extra training to know where to start.</div></div>
              <div className="rounded-xl border border-indigo-100 bg-white p-4 text-sm"><div className="font-semibold text-slate-900">Route / driver readiness</div><div className="mt-1 text-slate-600">{preview.dispatch[0]?.result ?? 'Review truck and driver setup.'}</div><div className="mt-3 rounded-lg bg-indigo-50 px-3 py-2 text-xs font-medium text-indigo-800">Super Admin check: route work should start from load, truck, and driver context.</div></div>
              <div className="rounded-xl border border-indigo-100 bg-white p-4 text-sm"><div className="font-semibold text-slate-900">Team coverage</div><div className="mt-1 text-slate-600">{preview.team[1]?.result ?? 'Review dispatcher coverage.'}</div><div className="mt-3 rounded-lg bg-indigo-50 px-3 py-2 text-xs font-medium text-indigo-800">Super Admin check: each active workspace needs clear dispatcher ownership.</div></div>
            </div>
            <div className="grid gap-3 md:grid-cols-3">
              {preview.team.slice(0, 2).map(readinessCard)}
              {preview.dispatch.slice(0, 1).map(readinessCard)}
            </div>
            {buildReviewOn ? <div className="rounded-2xl border border-dashed border-indigo-200 bg-white p-4"><div className="text-xs font-semibold uppercase tracking-[0.18em] text-indigo-700">Build Review detail</div><div className="mt-2 text-sm leading-6 text-slate-600">v356 deepens Super Admin operational monitoring for dashboard health, load flow, document blockers, billing blockers, dispatch next actions, CORI guidance, and user-facing simplicity without returning that detail to Workspace Admin or dispatcher screens.</div></div> : null}
          </div>
        </div>
      </section> : null}
      {showReadiness ? <section className="rounded-2xl border border-blue-100 bg-blue-50 p-6 shadow-sm">
        <div className="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
          <div><div className="text-xs font-semibold uppercase tracking-[0.18em] text-blue-700">Super Admin workspace view</div><h2 className="mt-1 text-lg font-semibold text-slate-900">Workspace readiness</h2><p className="mt-1 max-w-3xl text-sm leading-6 text-slate-600">Review setup and subscription fit from Super Admin. Workspace Admin stays clean and only shows daily-use settings.</p></div>
          <div className="rounded-xl border border-blue-200 bg-white px-3 py-2 text-xs font-semibold text-blue-800">Build Review: {buildReviewOn ? 'On' : 'Off'}</div>
        </div>
        <div className="mt-4 grid gap-4 lg:grid-cols-[320px_1fr]">
          {workspacePicker}
          {preview ? <div className="space-y-4 rounded-2xl border border-blue-100 bg-white p-4">
            <div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between"><div><div className="text-sm font-semibold text-slate-900">{selectedWorkspace?.name} setup status</div><div className="mt-1 text-sm text-slate-600">{preview.safeLaunch}</div></div><span className={`w-fit rounded-full px-3 py-1 text-xs font-semibold uppercase tracking-[0.14em] ${statusClasses(preview.overallStatus)}`}>{preview.overallStatus}</span></div>
            <div className="grid gap-3 md:grid-cols-3"><div className="rounded-xl border border-slate-100 bg-slate-50 p-3 text-sm"><div className="font-semibold text-slate-900">First fix</div><div className="mt-1 text-slate-600">{preview.firstFix}</div></div><div className="rounded-xl border border-slate-100 bg-slate-50 p-3 text-sm"><div className="font-semibold text-slate-900">Subscription fix</div><div className="mt-1 text-slate-600">{preview.subscription.firstFix}</div></div><div className="rounded-xl border border-slate-100 bg-slate-50 p-3 text-sm"><div className="font-semibold text-slate-900">User-facing rule</div><div className="mt-1 text-slate-600">Only daily-use settings belong in Workspace Admin.</div></div></div>
            <div className="grid gap-3 md:grid-cols-2 xl:grid-cols-5">{preview.items.map(readinessCard)}</div>
            <div className="rounded-2xl border border-slate-100 bg-slate-50 p-4"><div className="flex flex-col gap-3 md:flex-row md:items-start md:justify-between"><div><div className="text-sm font-semibold text-slate-900">Subscription assignment</div><div className="mt-1 text-sm text-slate-600">{preview.subscription.summary}</div></div><div className="rounded-xl bg-white px-3 py-2 text-xs font-semibold text-slate-700">{preview.subscription.plan.name}</div></div></div>
            {buildReviewOn ? <div className="rounded-2xl border border-dashed border-blue-200 bg-blue-50 p-4"><div className="text-xs font-semibold uppercase tracking-[0.18em] text-blue-700">Build Review detail</div><div className="mt-3 grid gap-3 md:grid-cols-3"><div className="rounded-xl border border-blue-100 bg-white p-3 text-xs leading-5 text-slate-600"><span className="font-semibold text-slate-900">Synced surfaces:</span> readiness, subscription assignment, plan limits, and feature access now feed Super Admin review.</div><div className="rounded-xl border border-blue-100 bg-white p-3 text-xs leading-5 text-slate-600"><span className="font-semibold text-slate-900">Workspace Admin:</span> subscription detail stays out of the customer-facing page until simple entitlement prompts are ready.</div><div className="rounded-xl border border-blue-100 bg-white p-3 text-xs leading-5 text-slate-600"><span className="font-semibold text-slate-900">Next control path:</span> enforce saved plan entitlements across Workspace Admin after this persisted model is approved.</div></div></div> : null}
          </div> : null}
        </div>
      </section> : null}

      {(showIdentity || showTeam || showDispatch || showDocuments || showBilling || showSubscriptions || showEntitlements || showAddOns || showStripeReadiness || showStripeScaffold || showStripeSyncReview || showStripeWebhooks) && <div className="grid gap-4 lg:grid-cols-[320px_1fr]">{workspacePicker}<div className="space-y-6">
        {preview && showIdentity ? <SectionShell title="Workspace Identity" subtitle="Company name, workspace link, and active state for the selected workspace."><div className="grid gap-3 md:grid-cols-3">{preview.identity.map(readinessCard)}</div></SectionShell> : null}
        {preview && showTeam ? <SectionShell title="Team and Roles" subtitle="Workspace admins, dispatcher coverage, and portal user visibility."><div className="grid gap-3 md:grid-cols-3">{preview.team.map(readinessCard)}</div></SectionShell> : null}
        {preview && showDispatch ? <SectionShell title="Dispatch Workflow Readiness" subtitle="Trucks, drivers, loads, and business contact records that help prove the workspace is operationally ready."><div className="grid gap-3 md:grid-cols-3">{preview.dispatch.map(readinessCard)}</div></SectionShell> : null}
        {preview && showDocuments ? <SectionShell title="Documents and Compliance" subtitle="Document intake and compliance review signals Super Admin can monitor without cluttering Workspace Admin."><div className="grid gap-3 md:grid-cols-2">{preview.documents.map(readinessCard)}</div></SectionShell> : null}
        {preview && showBilling ? <SectionShell title="Billing and Load Payments" subtitle="Load payment and billing handoff signals for Super Admin review."><div className="grid gap-3 md:grid-cols-2">{preview.billing.map(readinessCard)}</div></SectionShell> : null}
        {preview && showSubscriptions ? <SectionShell title="Subscription and Entitlements" subtitle="Assign a saved plan, review included limits, and confirm feature access for the selected workspace."><div className="space-y-5"><div className="rounded-2xl border border-blue-100 bg-blue-50 p-4"><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">Saved workspace plan</div><div className="mt-1 text-lg font-semibold text-slate-900">{preview.subscription.plan.name}</div><div className="mt-1 text-sm leading-6 text-slate-600">{preview.subscription.summary}</div></div><div className="rounded-xl border border-blue-100 bg-white px-4 py-3 text-sm font-semibold text-blue-800">${preview.subscription.plan.monthlyPrice}/month</div></div><div className="mt-3 rounded-xl border border-blue-100 bg-white p-3 text-sm text-slate-700"><span className="font-semibold text-slate-900">First subscription fix:</span> {preview.subscription.firstFix}</div></div><div className="rounded-2xl border bg-white p-4"><div className="grid gap-3 md:grid-cols-[1fr_220px_auto]"><label className="block text-sm"><div className="mb-1 font-semibold text-slate-900">Assign plan</div><select value={assignmentPlanId} onChange={(e) => setAssignmentPlanId(e.target.value)} className="w-full rounded-xl border px-3 py-2">{plans.map((plan) => <option key={plan.id} value={plan.id}>{plan.name}</option>)}</select></label><label className="block text-sm"><div className="mb-1 font-semibold text-slate-900">Status</div><select value={assignmentStatus} onChange={(e) => setAssignmentStatus(e.target.value)} className="w-full rounded-xl border px-3 py-2"><option value="TRIAL">Trial</option><option value="ACTIVE">Active</option><option value="PAST_DUE">Past due</option><option value="PAUSED">Paused</option><option value="CANCELED">Canceled</option></select></label><button type="button" onClick={assignWorkspaceSubscription} className="self-end rounded-xl bg-slate-950 px-4 py-2 text-sm font-semibold text-white">Save assignment</button></div><div className="mt-3 text-xs leading-5 text-slate-500">This saves the workspace subscription assignment to the database. Workspace Admin still stays clean until enforcement is turned on.</div></div><div><h3 className="text-sm font-semibold text-slate-900">Included vs over limit</h3><div className="mt-3 grid gap-3 md:grid-cols-3">{preview.subscription.limits.map(subscriptionLimitCard)}</div></div><div><h3 className="text-sm font-semibold text-slate-900">Feature access</h3><div className="mt-3 grid gap-3 sm:grid-cols-2 xl:grid-cols-3">{preview.subscription.features.map(subscriptionFeatureCard)}</div></div></div></SectionShell> : null}


        {preview && showSubscriptions ? <SectionShell title="Stripe Billing Setup" subtitle="Prepare this workspace for future platform subscription billing. These fields do not charge the customer yet."><div className="space-y-5"><div className="rounded-2xl border border-blue-100 bg-blue-50 p-4"><div className="text-xs font-semibold uppercase tracking-[0.18em] text-blue-700">Platform subscription path</div><h3 className="mt-1 text-lg font-semibold text-slate-900">Super Admin Stripe setup</h3><p className="mt-1 text-sm leading-6 text-slate-600">Use this for Dispatch Spot platform subscriptions only. Workspace Admin dispatcher services will use a separate Stripe path to bill carriers. Carrier and company billing to brokers or shippers remains factoring or Net 30.</p></div><div className="grid gap-4 md:grid-cols-3"><label className="block text-sm"><div className="mb-1 font-semibold text-slate-900">Billing provider</div><select value={assignmentBillingProvider} onChange={(e) => setAssignmentBillingProvider(e.target.value)} className="w-full rounded-xl border px-3 py-2"><option>Stripe</option><option>None</option><option>Manual</option></select></label><label className="block text-sm"><div className="mb-1 font-semibold text-slate-900">Billing mode</div><select value={assignmentBillingMode} onChange={(e) => setAssignmentBillingMode(e.target.value)} className="w-full rounded-xl border px-3 py-2"><option>Not connected</option><option>Test</option><option>Live</option><option>Manual</option></select></label><label className="block text-sm"><div className="mb-1 font-semibold text-slate-900">Provider sync</div><select value={assignmentProviderSyncStatus} onChange={(e) => setAssignmentProviderSyncStatus(e.target.value)} className="w-full rounded-xl border px-3 py-2"><option>Not ready</option><option>Ready</option><option>Synced</option><option>Needs review</option><option>Error</option></select></label><label className="block text-sm"><div className="mb-1 font-semibold text-slate-900">Stripe customer ID</div><input value={stripeCustomerId} onChange={(e) => setStripeCustomerId(e.target.value)} placeholder="cus_..." className="w-full rounded-xl border px-3 py-2" /></label><label className="block text-sm"><div className="mb-1 font-semibold text-slate-900">Stripe subscription ID</div><input value={stripeSubscriptionId} onChange={(e) => setStripeSubscriptionId(e.target.value)} placeholder="sub_..." className="w-full rounded-xl border px-3 py-2" /></label><label className="block text-sm"><div className="mb-1 font-semibold text-slate-900">Subscription item ID</div><input value={stripeSubscriptionItemId} onChange={(e) => setStripeSubscriptionItemId(e.target.value)} placeholder="si_..." className="w-full rounded-xl border px-3 py-2" /></label><label className="block text-sm md:col-span-3"><div className="mb-1 font-semibold text-slate-900">Provider status note</div><input value={billingProviderStatus} onChange={(e) => setBillingProviderStatus(e.target.value)} placeholder="Internal Stripe setup status" className="w-full rounded-xl border px-3 py-2" /></label></div><div className="rounded-xl border border-slate-100 bg-slate-50 p-3 text-sm leading-6 text-slate-600"><span className="font-semibold text-slate-900">Current saved billing state:</span> {billingProviderLabel(selectedWorkspace?.workspaceSubscription?.billingProvider)} · {billingModeLabel(selectedWorkspace?.workspaceSubscription?.billingMode)} · {providerSyncStatusLabel(selectedWorkspace?.workspaceSubscription?.providerSyncStatus)}</div></div></SectionShell> : null}

        {preview && showStripeReadiness ? <SectionShell title="Stripe Test-Mode Readiness" subtitle="Super Admin check for platform subscription billing setup. This does not enable live Stripe charges."><div className="space-y-5"><div className="rounded-2xl border border-blue-100 bg-blue-50 p-4"><div className="text-xs font-semibold uppercase tracking-[0.18em] text-blue-700">Platform billing provider</div><h3 className="mt-1 text-lg font-semibold text-slate-900">Stripe readiness, not live charging</h3><p className="mt-1 text-sm leading-6 text-slate-600">Use this page to confirm test-mode setup, plan identifiers, workspace customer IDs, and provider sync status before live billing is connected. Workspace Admin dispatcher service billing will use a separate Stripe path later.</p><div className="mt-3 rounded-xl border border-blue-100 bg-white p-3 text-sm leading-6 text-slate-700"><span className="font-semibold text-slate-900">Safety note:</span> {stripeReadiness?.safetyNote ?? 'This readiness check does not create Stripe charges.'}</div></div><div className="grid gap-3 md:grid-cols-3">{stripeReadinessCard('Stripe configured', stripeReadinessStatus({ ok: Boolean(stripeReadiness?.configured), review: Boolean(stripeReadiness?.secretKeyConfigured || stripeReadiness?.publishableKeyConfigured) }), stripeReadiness?.configured ? 'Secret and publishable keys are present for readiness review.' : 'Stripe keys are not fully configured yet.')}{stripeReadinessCard('Billing mode', stripeReadinessStatus({ ok: stripeReadiness?.mode === 'Test', review: stripeReadiness?.mode === 'Live' || stripeReadiness?.mode === 'Review' }), `Detected mode: ${stripeReadiness?.mode ?? 'Not configured'}. Test mode is expected before live charging.`)}{stripeReadinessCard('Webhook secret', stripeReadinessStatus({ ok: Boolean(stripeReadiness?.webhookSecretConfigured), review: Boolean(stripeReadiness?.configured) }), stripeReadiness?.webhookSecretConfigured ? 'Webhook secret is present for future provider sync.' : 'Webhook secret is missing or not configured yet.')}</div><div className="rounded-2xl border bg-white p-4"><h3 className="text-sm font-semibold text-slate-900">Plan Stripe IDs</h3><p className="mt-1 text-sm text-slate-500">Each live plan should eventually have a Stripe product ID and monthly price ID before checkout is enabled.</p><div className="mt-3 grid gap-3 md:grid-cols-2 xl:grid-cols-3">{plans.map((plan) => { const hasProduct = Boolean(plan.billing?.stripeProductId); const hasMonthlyPrice = Boolean(plan.billing?.stripeMonthlyPriceId); const status = stripeReadinessStatus({ ok: hasProduct && hasMonthlyPrice, review: plan.status !== 'Live' }); return stripeReadinessCard(plan.name, status, hasProduct && hasMonthlyPrice ? 'Product and monthly price IDs are staged.' : `Product ID: ${hasProduct ? 'set' : 'missing'} · Monthly price ID: ${hasMonthlyPrice ? 'set' : 'missing'}`); })}</div></div><div className="rounded-2xl border bg-white p-4"><h3 className="text-sm font-semibold text-slate-900">Selected workspace Stripe setup</h3><p className="mt-1 text-sm text-slate-500">Workspace Stripe identifiers are stored for future platform subscription sync. They do not charge the customer yet.</p><div className="mt-3 grid gap-3 md:grid-cols-3">{stripeReadinessCard('Stripe customer', stripeReadinessStatus({ ok: Boolean(selectedWorkspace?.workspaceSubscription?.stripeCustomerId), review: Boolean(selectedWorkspace?.workspaceSubscription) }), selectedWorkspace?.workspaceSubscription?.stripeCustomerId ? 'Customer ID is saved.' : 'Customer ID is missing.')}{stripeReadinessCard('Stripe subscription', stripeReadinessStatus({ ok: Boolean(selectedWorkspace?.workspaceSubscription?.stripeSubscriptionId), review: Boolean(selectedWorkspace?.workspaceSubscription?.stripeCustomerId) }), selectedWorkspace?.workspaceSubscription?.stripeSubscriptionId ? 'Subscription ID is saved.' : 'Subscription ID is missing.')}{stripeReadinessCard('Provider sync', stripeReadinessStatus({ ok: selectedWorkspace?.workspaceSubscription?.providerSyncStatus === 'SYNCED', review: selectedWorkspace?.workspaceSubscription?.providerSyncStatus === 'READY' || selectedWorkspace?.workspaceSubscription?.providerSyncStatus === 'NEEDS_REVIEW' }), providerSyncStatusLabel(selectedWorkspace?.workspaceSubscription?.providerSyncStatus))}</div><div className="mt-3 rounded-xl border border-slate-100 bg-slate-50 p-3 text-sm leading-6 text-slate-600"><span className="font-semibold text-slate-900">First Stripe fix:</span> {stripeReadiness?.firstFix ?? 'Review Stripe configuration.'}</div></div></div></SectionShell> : null}


        {preview && showStripeScaffold ? (() => { const selectedPlan = plans.find((plan) => plan.id === assignmentPlanId) ?? preview.subscription.plan; const monthlyPriceId = selectedPlan.billing?.stripeMonthlyPriceId ?? ''; const metadata = previewStripeMetadata(selectedWorkspace, selectedPlan); const customerPreview = { email: selectedWorkspace?.users?.find((user) => user.role === 'ORG_ADMIN')?.email ?? 'workspace-admin@example.com', name: selectedWorkspace?.name ?? 'Selected workspace', metadata }; const subscriptionPreview = { customer: stripeCustomerId.trim() || '(create or paste test customer ID first)', items: [{ price: monthlyPriceId || '(missing monthly Stripe price ID)' }], metadata }; return <SectionShell title="Stripe Test-Mode Customer and Subscription Scaffold" subtitle="Super Admin-only test billing preparation. This page previews the Stripe test payload, can create a Stripe test customer and test subscription, and stores confirmed test IDs. It does not collect payment or enable live charges."><div className="space-y-5"><div className="rounded-2xl border border-blue-100 bg-blue-50 p-4"><div className="text-xs font-semibold uppercase tracking-[0.18em] text-blue-700">Safe test-mode scaffold</div><h3 className="mt-1 text-lg font-semibold text-slate-900">Preview first. Store IDs only after manual confirmation.</h3><p className="mt-1 text-sm leading-6 text-slate-600">Use this to prepare a selected workspace for platform subscription billing tests. This is for Super Admin platform subscriptions only. Workspace Admin dispatcher-service billing remains a separate future Stripe path.</p><div className="mt-3 rounded-xl border border-blue-100 bg-white p-3 text-sm leading-6 text-slate-700"><span className="font-semibold text-slate-900">Safety note:</span> This scaffold can create a Stripe test customer and then a Stripe test subscription only. It does not create checkout sessions, payment method collection, or live charges.</div></div><div className="grid gap-3 md:grid-cols-3">{stripeReadinessCard('Stripe test mode', stripeReadinessStatus({ ok: stripeReadiness?.mode === 'Test', review: stripeReadiness?.mode === 'Review' || stripeReadiness?.mode === 'Live' }), `Detected mode: ${stripeReadiness?.mode ?? 'Not configured'}. Test mode is required before using this scaffold.`)}{stripeReadinessCard('Plan price ID', stripeIdStatus(monthlyPriceId, 'price_'), monthlyPriceId ? `Monthly price ID: ${monthlyPriceId}` : 'Select a plan with a monthly Stripe price ID before test subscription creation.')}{stripeReadinessCard('Workspace customer', stripeIdStatus(stripeCustomerId, 'cus_'), stripeCustomerId ? 'A test customer ID is staged or saved.' : 'Paste the test customer ID after creating or confirming it in Stripe test mode.')}</div><div className="grid gap-4 lg:grid-cols-2"><div className="rounded-2xl border bg-white p-4"><h3 className="text-sm font-semibold text-slate-900">Customer preview</h3><p className="mt-1 text-sm text-slate-500">This is the safe customer shape Super Admin can compare to Stripe test mode.</p><pre className="mt-3 overflow-auto rounded-xl bg-slate-950 p-3 text-xs leading-5 text-slate-100">{JSON.stringify(customerPreview, null, 2)}</pre></div><div className="rounded-2xl border bg-white p-4"><h3 className="text-sm font-semibold text-slate-900">Subscription preview</h3><p className="mt-1 text-sm text-slate-500">This shows the test subscription request that the controlled Super Admin action can now create after a test customer and monthly price ID are ready.</p><pre className="mt-3 overflow-auto rounded-xl bg-slate-950 p-3 text-xs leading-5 text-slate-100">{JSON.stringify(subscriptionPreview, null, 2)}</pre></div></div><div className="rounded-2xl border bg-white p-4"><h3 className="text-sm font-semibold text-slate-900">Store manually confirmed test IDs</h3><p className="mt-1 text-sm text-slate-500">Paste IDs only after you confirm them in Stripe test mode. Saving here records them for future provider sync review and does not charge the workspace.</p><div className="mt-4 grid gap-4 md:grid-cols-3"><label className="block text-sm"><div className="mb-1 font-semibold text-slate-900">Test customer ID</div><input value={stripeCustomerId} onChange={(e) => setStripeCustomerId(e.target.value)} placeholder="cus_test..." className="w-full rounded-xl border px-3 py-2" /></label><label className="block text-sm"><div className="mb-1 font-semibold text-slate-900">Test subscription ID</div><input value={stripeSubscriptionId} onChange={(e) => setStripeSubscriptionId(e.target.value)} placeholder="sub_test..." className="w-full rounded-xl border px-3 py-2" /></label><label className="block text-sm"><div className="mb-1 font-semibold text-slate-900">Test subscription item ID</div><input value={stripeSubscriptionItemId} onChange={(e) => setStripeSubscriptionItemId(e.target.value)} placeholder="si_test..." className="w-full rounded-xl border px-3 py-2" /></label><label className="block text-sm md:col-span-3"><div className="mb-1 font-semibold text-slate-900">Internal status note</div><input value={billingProviderStatus} onChange={(e) => setBillingProviderStatus(e.target.value)} placeholder="Manual test-mode scaffold reviewed. No live billing enabled." className="w-full rounded-xl border px-3 py-2" /></label></div><div className="mt-4 flex flex-col gap-2 sm:flex-row"><button onClick={createStripeTestCustomer} disabled={!selectedWorkspace || stripeCustomerCreating || stripeReadiness?.mode !== 'Test'} className="rounded-xl bg-blue-700 px-4 py-2 text-sm font-semibold text-white disabled:opacity-50">{stripeCustomerCreating ? 'Creating test customer...' : 'Create Stripe test customer'}</button><button onClick={createStripeTestSubscription} disabled={!selectedWorkspace || stripeSubscriptionCreating || stripeReadiness?.mode !== 'Test' || !stripeCustomerId.trim()} className="rounded-xl bg-emerald-700 px-4 py-2 text-sm font-semibold text-white disabled:opacity-50">{stripeSubscriptionCreating ? 'Creating test subscription...' : 'Create Stripe test subscription'}</button><button onClick={saveStripeTestScaffold} disabled={!selectedWorkspace || !assignmentPlanId} className="rounded-xl bg-black px-4 py-2 text-sm font-semibold text-white disabled:opacity-50">Save test scaffold IDs</button></div>{stripeActionMessage ? <div className="mt-3 rounded-xl border border-emerald-100 bg-emerald-50 p-3 text-sm font-semibold text-emerald-800">{stripeActionMessage}</div> : null}</div><div className="rounded-xl border border-amber-100 bg-amber-50 p-3 text-sm leading-6 text-amber-800"><span className="font-semibold">Next safe step:</span> Super Admin can now create or confirm a Stripe test customer and create a controlled Stripe test subscription. Payment collection, checkout, customer portal, and live billing remain off.</div></div></SectionShell>; })() : null}


        {preview && showStripeSyncReview ? <SectionShell title="Stripe Test Subscription Sync Review" subtitle="Fetch and compare saved Stripe test IDs against Stripe before live billing or add-ons are enabled."><div className="space-y-5"><div className="rounded-2xl border border-blue-100 bg-blue-50 p-4"><div className="text-xs font-semibold uppercase tracking-[0.18em] text-blue-700">Test-mode sync only</div><h3 className="mt-1 text-lg font-semibold text-slate-900">Review saved workspace Stripe subscription</h3><p className="mt-1 text-sm leading-6 text-slate-600">Use this to confirm the saved Stripe test customer, test subscription, subscription item, and selected plan price still match. This does not collect payment or create live charges.</p></div><div className="grid gap-3 md:grid-cols-4">{stripeReadinessCard('Saved customer', stripeReadinessStatus({ ok: Boolean(selectedWorkspace?.workspaceSubscription?.stripeCustomerId), review: Boolean(selectedWorkspace?.workspaceSubscription) }), selectedWorkspace?.workspaceSubscription?.stripeCustomerId ? 'Customer ID is saved.' : 'Customer ID is missing.')}{stripeReadinessCard('Saved subscription', stripeReadinessStatus({ ok: Boolean(selectedWorkspace?.workspaceSubscription?.stripeSubscriptionId), review: Boolean(selectedWorkspace?.workspaceSubscription?.stripeCustomerId) }), selectedWorkspace?.workspaceSubscription?.stripeSubscriptionId ? 'Subscription ID is saved.' : 'Subscription ID is missing.')}{stripeReadinessCard('Plan price ID', stripeIdStatus(preview.subscription.plan.billing?.stripeMonthlyPriceId ?? '', 'price_'), preview.subscription.plan.billing?.stripeMonthlyPriceId ? 'Selected plan has a monthly Stripe price ID.' : 'Selected plan monthly Stripe price ID is missing.')}{stripeReadinessCard('Provider sync', stripeReadinessStatus({ ok: selectedWorkspace?.workspaceSubscription?.providerSyncStatus === 'SYNCED', review: selectedWorkspace?.workspaceSubscription?.providerSyncStatus === 'READY' || selectedWorkspace?.workspaceSubscription?.providerSyncStatus === 'NEEDS_REVIEW' }), providerSyncStatusLabel(selectedWorkspace?.workspaceSubscription?.providerSyncStatus))}</div><div className="rounded-2xl border bg-white p-4"><div className="flex flex-col gap-3 md:flex-row md:items-start md:justify-between"><div><h3 className="text-sm font-semibold text-slate-900">Fetch Stripe test sync status</h3><p className="mt-1 text-sm leading-6 text-slate-500">This calls Stripe in test mode only, compares IDs, updates provider sync status, and gives Super Admin the first fix.</p></div><button type="button" onClick={reviewStripeTestSync} disabled={!selectedWorkspace || stripeSyncReviewing} className="rounded-xl bg-slate-950 px-4 py-2 text-sm font-semibold text-white disabled:opacity-50">{stripeSyncReviewing ? 'Reviewing...' : 'Review Stripe test sync'}</button></div>{stripeSyncReview ? <div className="mt-4 grid gap-3 md:grid-cols-3"><div className="rounded-xl border border-slate-100 bg-slate-50 p-3 text-sm"><div className="font-semibold text-slate-900">Overall status</div><div className="mt-1 text-slate-600">{stripeSyncReview.overallStatus}</div></div><div className="rounded-xl border border-slate-100 bg-slate-50 p-3 text-sm"><div className="font-semibold text-slate-900">Stripe status</div><div className="mt-1 text-slate-600">{stripeSyncReview.stripeStatus}</div></div><div className="rounded-xl border border-slate-100 bg-slate-50 p-3 text-sm"><div className="font-semibold text-slate-900">First fix</div><div className="mt-1 text-slate-600">{stripeSyncReview.firstFix}</div></div><div className="rounded-xl border border-slate-100 bg-slate-50 p-3 text-sm"><div className="font-semibold text-slate-900">Customer match</div><div className="mt-1 text-slate-600">{stripeSyncReview.stripeCustomerMatch ? 'Matches' : 'Needs review'}</div></div><div className="rounded-xl border border-slate-100 bg-slate-50 p-3 text-sm"><div className="font-semibold text-slate-900">Price match</div><div className="mt-1 text-slate-600">{stripeSyncReview.priceMatch ? 'Matches plan price' : 'Needs review'}</div></div><div className="rounded-xl border border-slate-100 bg-slate-50 p-3 text-sm"><div className="font-semibold text-slate-900">Matched item</div><div className="mt-1 break-all text-slate-600">{stripeSyncReview.matchingItemId || 'None found'}</div></div></div> : null}{stripeActionMessage ? <div className="mt-3 rounded-xl border border-emerald-100 bg-emerald-50 p-3 text-sm font-semibold text-emerald-800">{stripeActionMessage}</div> : null}</div><div className="rounded-xl border border-amber-100 bg-amber-50 p-3 text-sm leading-6 text-amber-800"><span className="font-semibold">Safety rule:</span> sync review is test-mode only. No checkout, payment method collection, invoice payment, customer portal, or live billing action is performed.</div></div></SectionShell> : null}
        {preview && showStripeWebhooks ? <SectionShell title="Stripe Webhook Test Events" subtitle="Review platform subscription webhook readiness before add-ons or live billing are enabled."><div className="space-y-5"><div className="rounded-2xl border border-blue-100 bg-blue-50 p-4"><div className="text-xs font-semibold uppercase tracking-[0.18em] text-blue-700">Webhook test handling</div><h3 className="mt-1 text-lg font-semibold text-slate-900">Stripe event feedback loop</h3><p className="mt-1 text-sm leading-6 text-slate-600">Dispatch Spot can now receive safe Stripe test events, verify the webhook signature when a webhook secret is configured, match events to a workspace by Stripe customer or subscription ID, and update provider sync status.</p></div><div className="grid gap-3 md:grid-cols-4">{stripeReadinessCard('Webhook secret', stripeReadinessStatus({ ok: Boolean(stripeReadiness?.webhookSecretConfigured), review: Boolean(stripeReadiness?.configured) }), stripeReadiness?.webhookSecretConfigured ? 'Webhook secret is configured for signature checks.' : 'Webhook secret is missing. Test events can still be reviewed, but signed webhook verification is not ready.')}{stripeReadinessCard('Test mode', stripeReadinessStatus({ ok: stripeReadiness?.mode === 'Test', review: stripeReadiness?.mode === 'Review' }), `Detected mode: ${stripeReadiness?.mode ?? 'Not configured'}.`)}{stripeReadinessCard('Saved customer', stripeReadinessStatus({ ok: Boolean(selectedWorkspace?.workspaceSubscription?.stripeCustomerId), review: Boolean(selectedWorkspace?.workspaceSubscription) }), selectedWorkspace?.workspaceSubscription?.stripeCustomerId || 'Missing customer ID')}{stripeReadinessCard('Saved subscription', stripeReadinessStatus({ ok: Boolean(selectedWorkspace?.workspaceSubscription?.stripeSubscriptionId), review: Boolean(selectedWorkspace?.workspaceSubscription?.stripeCustomerId) }), selectedWorkspace?.workspaceSubscription?.stripeSubscriptionId || 'Missing subscription ID')}</div><div className="rounded-2xl border bg-white p-4"><h3 className="text-sm font-semibold text-slate-900">Webhook endpoint</h3><p className="mt-1 text-sm leading-6 text-slate-500">Use this endpoint in Stripe test mode only when configuring the platform subscription webhook.</p><div className="mt-3 rounded-xl border border-slate-100 bg-slate-50 p-3 text-sm font-mono text-slate-700">/api/subscriptions/stripe-test/webhook</div><div className="mt-4 grid gap-3 md:grid-cols-3"><div className="rounded-xl border border-slate-100 bg-slate-50 p-3 text-sm"><div className="font-semibold text-slate-900">Recent event status</div><div className="mt-1 text-slate-600">{selectedWorkspace?.workspaceSubscription?.billingProviderStatus || 'No Stripe webhook event has updated this workspace yet.'}</div></div><div className="rounded-xl border border-slate-100 bg-slate-50 p-3 text-sm"><div className="font-semibold text-slate-900">Provider sync</div><div className="mt-1 text-slate-600">{providerSyncStatusLabel(selectedWorkspace?.workspaceSubscription?.providerSyncStatus)}</div></div><div className="rounded-xl border border-slate-100 bg-slate-50 p-3 text-sm"><div className="font-semibold text-slate-900">Last sync</div><div className="mt-1 text-slate-600">{selectedWorkspace?.workspaceSubscription?.lastProviderSyncAt ? new Date(selectedWorkspace.workspaceSubscription.lastProviderSyncAt).toLocaleString() : 'Not synced yet'}</div></div></div></div><div className="rounded-2xl border bg-white p-4"><div className="flex flex-col gap-3 md:flex-row md:items-start md:justify-between"><div><h3 className="text-sm font-semibold text-slate-900">Recent persisted webhook events</h3><p className="mt-1 text-sm leading-6 text-slate-500">These records help Super Admin confirm what Stripe sent, whether it was verified, whether a workspace matched, and what changed.</p></div><button type="button" onClick={() => selectedWorkspace?.id ? loadStripeWebhookEvents(selectedWorkspace.id) : undefined} disabled={!selectedWorkspace || stripeWebhookEventsLoading} className="rounded-xl border border-slate-200 bg-white px-4 py-2 text-sm font-semibold text-slate-700 disabled:opacity-50">{stripeWebhookEventsLoading ? 'Refreshing...' : 'Refresh event log'}</button></div><div className="mt-4 space-y-3">{stripeWebhookEvents.length === 0 ? <div className="rounded-xl border border-slate-100 bg-slate-50 p-3 text-sm text-slate-600">No persisted Stripe webhook events found for this workspace yet.</div> : stripeWebhookEvents.map((event) => <div key={event.id} className="rounded-xl border border-slate-100 bg-slate-50 p-3 text-sm"><div className="flex flex-col gap-2 md:flex-row md:items-start md:justify-between"><div><div className="font-semibold text-slate-900">{event.eventType}</div><div className="mt-1 break-all text-xs text-slate-500">{event.eventId}</div></div><div className="flex flex-wrap gap-2 text-[10px] font-semibold uppercase tracking-[0.12em]"><span className="rounded-full bg-white px-2 py-1 text-slate-700">{event.mode}</span><span className={`rounded-full px-2 py-1 ${event.handled ? 'bg-emerald-100 text-emerald-700' : 'bg-amber-100 text-amber-700'}`}>{event.handled ? 'Handled' : 'Review'}</span><span className={`rounded-full px-2 py-1 ${event.signatureVerified ? 'bg-emerald-100 text-emerald-700' : 'bg-slate-100 text-slate-600'}`}>{event.signatureVerified ? 'Verified' : event.verificationStatus}</span></div></div><div className="mt-3 grid gap-3 md:grid-cols-3"><div><div className="text-xs font-semibold text-slate-900">Outcome</div><div className="mt-1 text-slate-600">{event.providerSyncOutcome}</div></div><div><div className="text-xs font-semibold text-slate-900">Subscription status</div><div className="mt-1 text-slate-600">{event.workspaceSubscriptionStatus}</div></div><div><div className="text-xs font-semibold text-slate-900">Received</div><div className="mt-1 text-slate-600">{new Date(event.createdAt).toLocaleString()}</div></div></div><div className="mt-3 rounded-lg bg-white p-2 text-xs leading-5 text-slate-600"><span className="font-semibold text-slate-900">First fix:</span> {event.firstFix}</div>{event.errorNote ? <div className="mt-2 rounded-lg bg-rose-50 p-2 text-xs leading-5 text-rose-700">{event.errorNote}</div> : null}</div>)}</div></div><div className="rounded-xl border border-amber-100 bg-amber-50 p-3 text-sm leading-6 text-amber-800"><span className="font-semibold">Safety rule:</span> webhook handling is test-mode only. Live events are ignored, and this does not create checkout, portal sessions, payment collection, add-ons, or charges.</div></div></SectionShell> : null}

        {preview && showAddOns ? <SectionShell title="Add-on and Usage Billing Readiness" subtitle="Super Admin review of what is included, what is over limit, and what should become a paid add-on before Stripe billing is connected."><div className="space-y-5"><div className="rounded-2xl border border-blue-100 bg-blue-50 p-4"><div className="text-xs font-semibold uppercase tracking-[0.18em] text-blue-700">Billing architecture</div><h3 className="mt-1 text-lg font-semibold text-slate-900">Separate Stripe paths</h3><div className="mt-3 grid gap-3 md:grid-cols-3"><div className="rounded-xl border border-blue-100 bg-white p-3 text-sm leading-6 text-slate-600"><span className="font-semibold text-slate-900">Platform subscription:</span> {preview.subscription.addOns.platformBillingPath}</div><div className="rounded-xl border border-blue-100 bg-white p-3 text-sm leading-6 text-slate-600"><span className="font-semibold text-slate-900">Dispatcher service billing:</span> {preview.subscription.addOns.dispatcherBillingPath}</div><div className="rounded-xl border border-blue-100 bg-white p-3 text-sm leading-6 text-slate-600"><span className="font-semibold text-slate-900">Broker / shipper billing:</span> {preview.subscription.addOns.carrierCompanyBillingPath}</div></div></div><div className="rounded-2xl border border-slate-100 bg-white p-4"><div className="grid gap-3 md:grid-cols-3"><div className="rounded-xl bg-slate-50 p-3 text-sm"><div className="font-semibold text-slate-900">Ready add-ons</div><div className="mt-1 text-2xl font-semibold text-slate-900">{preview.subscription.addOns.overLimitAddOnCount}</div></div><div className="rounded-xl bg-slate-50 p-3 text-sm"><div className="font-semibold text-slate-900">Future feature add-ons</div><div className="mt-1 text-2xl font-semibold text-slate-900">{preview.subscription.addOns.futureFeatureAddOnCount}</div></div><div className="rounded-xl bg-slate-50 p-3 text-sm"><div className="font-semibold text-slate-900">First billing fix</div><div className="mt-1 text-sm leading-5 text-slate-600">{preview.subscription.addOns.firstBillingFix}</div></div></div></div><div><h3 className="text-sm font-semibold text-slate-900">Add-on readiness</h3><div className="mt-3 grid gap-3 md:grid-cols-2 xl:grid-cols-3">{preview.subscription.addOns.items.map(addOnReadinessCard)}</div></div></div></SectionShell> : null}

        {preview && showEntitlements ? <SectionShell title="Entitlement Enforcement Preview" subtitle="Shared plan checks that Workspace Admin pages and functions will use before hard enforcement is turned on."><div className="space-y-5"><div className="rounded-2xl border border-indigo-100 bg-indigo-50 p-4"><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-indigo-700">Shared entitlement layer</div><div className="mt-1 text-lg font-semibold text-slate-900">{preview.subscription.entitlements.overallStatus}</div><div className="mt-1 text-sm leading-6 text-slate-600">{preview.subscription.entitlements.summary}</div></div><span className={`rounded-full px-3 py-1 text-xs font-semibold ${entitlementStatusClasses(preview.subscription.entitlements.overallStatus)}`}>{preview.subscription.entitlements.enforcementReady ? 'Ready for enforcement' : 'Review before enforcement'}</span></div><div className="mt-3 grid gap-3 md:grid-cols-2"><div className="rounded-xl border border-indigo-100 bg-white p-3 text-sm text-slate-700"><span className="font-semibold text-slate-900">First fix:</span> {preview.subscription.entitlements.firstFix}</div><div className="rounded-xl border border-indigo-100 bg-white p-3 text-sm text-slate-700"><span className="font-semibold text-slate-900">Workspace Admin message:</span> {preview.subscription.entitlements.workspaceAdminMessage}</div></div></div><div><h3 className="text-sm font-semibold text-slate-900">Limit enforcement</h3><div className="mt-3 grid gap-3 md:grid-cols-3">{preview.subscription.entitlements.limitStates.map(entitlementLimitCard)}</div></div><div><h3 className="text-sm font-semibold text-slate-900">Feature enforcement</h3><div className="mt-3 grid gap-3 sm:grid-cols-2 xl:grid-cols-3">{preview.subscription.entitlements.featureStates.map(entitlementFeatureCard)}</div></div></div></SectionShell> : null}
        {preview && buildReviewOn ? <SectionShell title="Build Review Notes" subtitle="Temporary Super Admin-only progress notes for the current build cycle."><div className="grid gap-3 md:grid-cols-2">{preview.notifications.map(readinessCard)}</div></SectionShell> : null}
      </div></div>}

      {showCreate ? <section className="rounded-2xl border bg-white p-6 shadow-sm"><h2 className="text-lg font-semibold">Create workspace</h2><p className="mt-1 text-sm text-gray-500">Provision a new company workspace and assign its first workspace admin in one step.</p><form onSubmit={createWorkspace} className="mt-6 space-y-4"><div className="grid gap-4 md:grid-cols-2"><label className="block text-sm"><div className="mb-1 font-medium">Company name</div><input value={form.companyName} onChange={(e) => setForm((p) => ({ ...p, companyName: e.target.value }))} className="w-full rounded-xl border px-3 py-2" /></label><label className="block text-sm"><div className="mb-1 font-medium">Workspace slug</div><input value={form.companySlug} onChange={(e) => setForm((p) => ({ ...p, companySlug: e.target.value }))} className="w-full rounded-xl border px-3 py-2" placeholder="optional-auto-generated" /></label></div><div className="grid gap-4 md:grid-cols-2"><label className="block text-sm"><div className="mb-1 font-medium">Admin first name</div><input value={form.adminFirstName} onChange={(e) => setForm((p) => ({ ...p, adminFirstName: e.target.value }))} className="w-full rounded-xl border px-3 py-2" /></label><label className="block text-sm"><div className="mb-1 font-medium">Admin last name</div><input value={form.adminLastName} onChange={(e) => setForm((p) => ({ ...p, adminLastName: e.target.value }))} className="w-full rounded-xl border px-3 py-2" /></label></div><div className="grid gap-4 md:grid-cols-[1fr_260px]"><label className="block text-sm"><div className="mb-1 font-medium">Admin email</div><input type="email" value={form.adminEmail} onChange={(e) => setForm((p) => ({ ...p, adminEmail: e.target.value }))} className="w-full rounded-xl border px-3 py-2" /></label><label className="block text-sm"><div className="mb-1 font-medium">Temporary password</div><input type="password" value={form.adminPassword} onChange={(e) => setForm((p) => ({ ...p, adminPassword: e.target.value }))} className="w-full rounded-xl border px-3 py-2" /></label></div><button type="submit" disabled={saving} className="rounded-xl bg-black px-4 py-2 text-sm font-medium text-white disabled:opacity-60">{saving ? 'Creating...' : 'Create workspace'}</button></form></section> : null}
      {showRoster ? <section className="rounded-2xl border bg-white p-6 shadow-sm"><h2 className="text-lg font-semibold">Workspace roster</h2><p className="mt-1 text-sm text-gray-500">Use the roster for quick status checks and activation control. Open Workspace Readiness for deeper review.</p><div className="mt-6 overflow-hidden rounded-2xl border"><table className="min-w-full divide-y divide-gray-200 text-sm"><thead className="bg-gray-50"><tr><th className="px-4 py-3 text-left font-medium text-gray-600">Workspace</th><th className="px-4 py-3 text-left font-medium text-gray-600">Slug</th><th className="px-4 py-3 text-left font-medium text-gray-600">Primary admins</th><th className="px-4 py-3 text-left font-medium text-gray-600">Plan</th><th className="px-4 py-3 text-left font-medium text-gray-600">Users</th><th className="px-4 py-3 text-left font-medium text-gray-600">Loads</th><th className="px-4 py-3 text-left font-medium text-gray-600">Status</th><th className="px-4 py-3 text-right font-medium text-gray-600">Action</th></tr></thead><tbody className="divide-y divide-gray-100 bg-white">{workspaces.map((workspace) => { const rowPreview = buildWorkspacePreview(workspace); return <tr key={workspace.id} className={selectedWorkspace?.id === workspace.id ? 'bg-blue-50/60' : undefined}><td className="px-4 py-3 font-medium">{workspace.name}</td><td className="px-4 py-3">{workspace.slug}</td><td className="px-4 py-3">{workspace.users?.filter((u) => u.role === 'ORG_ADMIN').map(adminName).join(', ') || '—'}</td><td className="px-4 py-3">{rowPreview?.subscription.plan.name ?? '—'}</td><td className="px-4 py-3">{workspace._count?.users ?? 0}</td><td className="px-4 py-3">{workspace._count?.loads ?? 0}</td><td className="px-4 py-3">{workspace.isActive ? 'Active' : 'Inactive'}</td><td className="px-4 py-3 text-right"><div className="flex justify-end gap-2"><button onClick={() => setSelectedWorkspaceId(workspace.id)} className="rounded-lg border px-3 py-1.5 text-xs font-medium">Select</button><button onClick={() => toggleWorkspace(workspace)} className="rounded-lg border px-3 py-1.5 text-xs font-medium">{workspace.isActive ? 'Deactivate' : 'Reactivate'}</button></div></td></tr>; })}</tbody></table></div></section> : null}
    </div>
  );
}
