"use client";

import Link from "next/link";
import { useEffect, useMemo, useState } from "react";
import type { ReactNode } from "react";
import { apiGet, apiPatch, apiPost } from "@/lib/api";
import type { Organization, User } from "@/types";
import {
  evaluateFeatureAccess,
  evaluateSubscriptionLimits,
  getStagedPlanForWorkspace,
  planLimitSummary,
  type SubscriptionFeatureSignal,
  type SubscriptionLimitSignal,
  type SubscriptionPlanDraft,
} from "@/src/modules/subscriptions/subscription-entitlements";

type WorkspaceSubscriptionPreview = {
  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;
  trialEndsAt?: string | null;
  currentPeriodEndsAt?: string | null;
  plan: SubscriptionPlanDraft;
};

type SuperAdminAuditEventPreview = {
  id: string;
  action: string;
  summary: string;
  beforeJson?: unknown;
  afterJson?: unknown;
  metadataJson?: unknown;
  createdAt: string;
  actorUser?: {
    email?: string | null;
    firstName?: string | null;
    lastName?: string | null;
  } | null;
};

type WorkspaceRow = Organization & {
  users?: Array<Pick<User, "id" | "email" | "firstName" | "lastName" | "isActive" | "role">>;
  workspaceSubscription?: WorkspaceSubscriptionPreview | null;
  superAdminAuditEvents?: SuperAdminAuditEventPreview[];
  _count?: {
    users?: number;
    trucks?: number;
    drivers?: number;
    brokers?: number;
    loads?: number;
    documents?: number;
    loadPayments?: number;
    notificationPreferences?: number;
    companies?: number;
    ownerOperators?: number;
    shippers?: number;
  };
};

type WorkspaceClassKey =
  | "Dispatcher"
  | "Company / Fleet"
  | "Carrier / Owner-Operator"
  | "Freight Broker"
  | "Driver Interface"
  | "Shipper / Customer Portal"
  | "Platform Marketplace"
  | "Internal Operations"
  | "Unclassified";

type StatusTone = "Ready" | "Check" | "Blocked" | "Planning";

type WorkspaceClassDefinition = {
  key: WorkspaceClassKey;
  accountClass: "Paid workspace" | "Owned interface" | "Invited portal" | "Platform layer" | "Internal workspace" | "Needs classification";
  subscriptionRule: string;
  planVisibilityRule: string;
  ownedInterfaceRule: string;
  superAdminMustControl: string[];
};

type ReadinessWarning = {
  key: string;
  status: Exclude<StatusTone, "Ready">;
  title: string;
  message: string;
};

type ClassificationState = {
  hasStoredPair: boolean;
  hasAnyStoredValue: boolean;
  pairIncomplete: boolean;
  storedClass: WorkspaceClassKey | null;
  signalClass: WorkspaceClassKey;
  effectiveClass: WorkspaceClassKey;
  recommendedAccountClass: string;
  recommendationMismatch: boolean;
  signalMismatch: boolean;
  status: StatusTone;
  label: string;
  note: string;
  warnings: ReadinessWarning[];
};

type PlanVisibilityFit = {
  status: StatusTone;
  label: string;
  note: string;
};

type BulkClassificationResult = {
  requested: number;
  updated: number;
  skipped: number;
  missing: number;
  results: Array<{
    workspaceId: string;
    workspaceName?: string | null;
    status: "updated" | "skipped" | "missing";
    reason?: string;
    workspaceType?: string;
    accountClass?: string;
  }>;
};

const workspaceClassDefinitions: WorkspaceClassDefinition[] = [
  {
    key: "Dispatcher",
    accountClass: "Paid workspace",
    subscriptionRule: "Customer workspace with its own trial, plan, seats, trucks, phone numbers, CORI access, and billing status gate.",
    planVisibilityRule: "Show dispatcher-ready plans with dispatch, billing, notifications, CORI, phone, routes, reports, and load-board access according to tier.",
    ownedInterfaceRule: "May own driver, accounting, carrier/customer contact, and limited portal access.",
    superAdminMustControl: ["Plan and trial", "Seat/truck/phone limits", "Phone usage", "CORI access", "Billing hold", "Support view"],
  },
  {
    key: "Company / Fleet",
    accountClass: "Paid workspace",
    subscriptionRule: "Customer workspace with its own plan, trial, fleet limits, driver access, phone numbers, and billing gate.",
    planVisibilityRule: "Show fleet-ready plans that emphasize trucks, drivers, route planning, maintenance, reporting, CORI Financial, and phone usage.",
    ownedInterfaceRule: "Owns driver interfaces. Drivers do not need independent subscriptions by default.",
    superAdminMustControl: ["Truck and driver limits", "Driver interface access", "Plan add-ons", "Billing status", "Integration health"],
  },
  {
    key: "Carrier / Owner-Operator",
    accountClass: "Paid workspace",
    subscriptionRule: "Independent carrier or owner-operator workspace pays for its own plan when it is the customer.",
    planVisibilityRule: "Show simpler carrier plans with current/next load, route, documents, settlement, phone, and CORI support.",
    ownedInterfaceRule: "May be one driver/truck or a small team; invited driver access remains owned by this workspace.",
    superAdminMustControl: ["Trial/plan", "Truck limit", "Phone number", "Load-board access", "Billing gate", "Support view"],
  },
  {
    key: "Freight Broker",
    accountClass: "Paid workspace",
    subscriptionRule: "Brokerage workspace pays for brokerage operations, carrier list tools, load distribution, posting limits, and load-board access.",
    planVisibilityRule: "Show broker-ready plans with load creation, carrier CRM, controlled carrier distribution, posting limits, margin reporting, and CORI Mail.",
    ownedInterfaceRule: "May own invited carrier-response portals and shipper/customer portal access.",
    superAdminMustControl: ["Carrier email volume", "Load-board posting limits", "Provider readiness", "Abuse controls", "Billing status", "Audit history"],
  },
  {
    key: "Driver Interface",
    accountClass: "Owned interface",
    subscriptionRule: "No independent subscription by default. Driver access is owned by the workspace they drive for.",
    planVisibilityRule: "Not shown as a sold plan. It is an entitlement/owned interface inside a paid workspace plan.",
    ownedInterfaceRule: "Shows current/upcoming loads, truck earnings when allowed, route progress, weather, traffic, fuel/rest planning, repair centers, documents, messages, and road-focused Ask CORI.",
    superAdminMustControl: ["Permission template", "Mobile safety", "Notification/SMS policy", "Workspace ownership", "Support visibility"],
  },
  {
    key: "Shipper / Customer Portal",
    accountClass: "Invited portal",
    subscriptionRule: "Usually invited and owned by broker, fleet, or dispatcher workspace. Large shippers may become paid workspaces later.",
    planVisibilityRule: "Do not sell small portals independently at first. Future large shipper plans can be shown only when ready.",
    ownedInterfaceRule: "Shows shipment requests, active shipments, quotes, documents, appointments, tracking, invoices, issues, and limited Ask CORI.",
    superAdminMustControl: ["Portal rules", "Data visibility", "Invitation ownership", "Future paid shipper option", "Support visibility"],
  },
  {
    key: "Platform Marketplace",
    accountClass: "Platform layer",
    subscriptionRule: "Shared Dispatch Spot platform capability. It is controlled by plan, verification, and policy, not sold as a normal workspace by default.",
    planVisibilityRule: "Keep internal load-board and marketplace access hidden until plan, verification, billing state, and Super Admin policy gates are ready.",
    ownedInterfaceRule: "Acts as a platform layer that paid workspaces may receive access to later by plan or add-on.",
    superAdminMustControl: ["Verification policy", "Posting rules", "Abuse monitoring", "Plan access", "Billing state", "Support review"],
  },
  {
    key: "Internal Operations",
    accountClass: "Internal workspace",
    subscriptionRule: "No customer subscription. Used by Dispatch Spot team for support, onboarding, incidents, and customer success.",
    planVisibilityRule: "Hidden from public registration and customer plan selection.",
    ownedInterfaceRule: "Supports internal operations without replacing Super Admin.",
    superAdminMustControl: ["Internal access", "Support queues", "Runbooks", "Incident workflows", "Customer success tasks"],
  },
];

const workspaceTypeOptions = [
  { value: "DISPATCHER", label: "Dispatcher" },
  { value: "COMPANY_FLEET", label: "Company / Fleet" },
  { value: "CARRIER_OWNER_OPERATOR", label: "Carrier / Owner-Operator" },
  { value: "FREIGHT_BROKER", label: "Freight Broker" },
  { value: "SHIPPER_CUSTOMER", label: "Shipper / Customer" },
  { value: "DRIVER_INTERFACE", label: "Driver Interface" },
  { value: "INTERNAL_OPERATIONS", label: "Internal Operations" },
  { value: "PLATFORM_MARKETPLACE", label: "Platform Marketplace" },
];

const accountClassOptions = [
  { value: "PAID_WORKSPACE", label: "Paid workspace" },
  { value: "OWNED_INTERFACE", label: "Owned interface" },
  { value: "INVITED_PORTAL", label: "Invited portal" },
  { value: "PLATFORM_LAYER", label: "Platform layer" },
  { value: "INTERNAL_WORKSPACE", label: "Internal workspace" },
];

const recommendedAccountClassByWorkspaceType: Record<string, string> = {
  DISPATCHER: "PAID_WORKSPACE",
  COMPANY_FLEET: "PAID_WORKSPACE",
  CARRIER_OWNER_OPERATOR: "PAID_WORKSPACE",
  FREIGHT_BROKER: "PAID_WORKSPACE",
  SHIPPER_CUSTOMER: "INVITED_PORTAL",
  DRIVER_INTERFACE: "OWNED_INTERFACE",
  INTERNAL_OPERATIONS: "INTERNAL_WORKSPACE",
  PLATFORM_MARKETPLACE: "PLATFORM_LAYER",
};

const recommendedWorkspaceTypeByClass: Partial<Record<WorkspaceClassKey, string>> = {
  Dispatcher: "DISPATCHER",
  "Company / Fleet": "COMPANY_FLEET",
  "Carrier / Owner-Operator": "CARRIER_OWNER_OPERATOR",
  "Freight Broker": "FREIGHT_BROKER",
  "Driver Interface": "DRIVER_INTERFACE",
  "Shipper / Customer Portal": "SHIPPER_CUSTOMER",
  "Platform Marketplace": "PLATFORM_MARKETPLACE",
  "Internal Operations": "INTERNAL_OPERATIONS",
};

const paidWorkspaceTypes = new Set(["DISPATCHER", "COMPANY_FLEET", "CARRIER_OWNER_OPERATOR", "FREIGHT_BROKER"]);
function money(value: number) {
  return new Intl.NumberFormat("en-US", { style: "currency", currency: "USD", maximumFractionDigits: 0 }).format(value);
}

function statusPill(status: StatusTone) {
  const classes = status === "Ready"
    ? "bg-emerald-100 text-emerald-700"
    : status === "Check"
      ? "bg-amber-100 text-amber-700"
      : status === "Planning"
        ? "bg-blue-100 text-blue-700"
        : "bg-rose-100 text-rose-700";
  return <span className={`rounded-full px-2.5 py-1 text-[11px] font-semibold ${classes}`}>{status}</span>;
}

function featurePill(item: SubscriptionFeatureSignal) {
  return (
    <span key={item.key} className={`rounded-full px-2 py-1 text-[10px] font-semibold ${item.included ? "bg-emerald-100 text-emerald-700" : "bg-slate-100 text-slate-500"}`}>
      {item.label}: {item.included ? "On" : "Off"}
    </span>
  );
}

function limitPill(item: SubscriptionLimitSignal) {
  return (
    <span key={item.key} className={`rounded-full px-2 py-1 text-[10px] font-semibold ${item.over > 0 ? "bg-rose-100 text-rose-700" : "bg-emerald-100 text-emerald-700"}`}>
      {item.label}: {item.used}/{item.included}
    </span>
  );
}

function dbLabel(value?: string | null) {
  if (!value) return "Not set";
  return value.toLowerCase().split("_").map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join(" ");
}

function storedWorkspaceTypeToClass(value?: string | null): WorkspaceClassKey | null {
  if (value === "DISPATCHER") return "Dispatcher";
  if (value === "COMPANY_FLEET") return "Company / Fleet";
  if (value === "CARRIER_OWNER_OPERATOR") return "Carrier / Owner-Operator";
  if (value === "FREIGHT_BROKER") return "Freight Broker";
  if (value === "DRIVER_INTERFACE") return "Driver Interface";
  if (value === "SHIPPER_CUSTOMER") return "Shipper / Customer Portal";
  if (value === "PLATFORM_MARKETPLACE") return "Platform Marketplace";
  if (value === "INTERNAL_OPERATIONS") return "Internal Operations";
  return null;
}

function inferWorkspaceClassFromSignals(workspace: WorkspaceRow): WorkspaceClassKey {
  const name = `${workspace.name ?? ""} ${workspace.slug ?? ""}`.toLowerCase();
  const counts = workspace._count ?? {};
  const hasBrokerSignal = (counts.brokers ?? 0) > 0 || name.includes("broker");
  const hasFleetSignal = (counts.companies ?? 0) > 0 || (counts.trucks ?? 0) > 3 || name.includes("fleet");
  const hasOwnerSignal = (counts.ownerOperators ?? 0) > 0 || name.includes("owner") || name.includes("carrier");
  const hasShipperSignal = (counts.shippers ?? 0) > 0 || name.includes("shipper") || name.includes("customer");
  const hasMarketplaceSignal = name.includes("marketplace") || name.includes("load board") || name.includes("load-board");

  if (name.includes("internal") || name.includes("dispatch spot")) return "Internal Operations";
  if (hasMarketplaceSignal) return "Platform Marketplace";
  if (hasBrokerSignal && !hasFleetSignal) return "Freight Broker";
  if (hasFleetSignal) return "Company / Fleet";
  if (hasOwnerSignal) return "Carrier / Owner-Operator";
  if (hasShipperSignal && (counts.loads ?? 0) === 0) return "Shipper / Customer Portal";
  return "Dispatcher";
}

function getDefinition(key: WorkspaceClassKey) {
  return workspaceClassDefinitions.find((item) => item.key === key) ?? {
    key,
    accountClass: "Needs classification" as const,
    subscriptionRule: "This workspace needs an explicit type before registration and billing rules are finalized.",
    planVisibilityRule: "Plan visibility cannot be trusted until workspace type is stored.",
    ownedInterfaceRule: "Owned interface rules need review.",
    superAdminMustControl: ["Workspace type", "Plan", "Trial", "Billing gate"],
  };
}

function buildClassificationState(workspace: WorkspaceRow): ClassificationState {
  const signalClass = inferWorkspaceClassFromSignals(workspace);
  const storedClass = storedWorkspaceTypeToClass(workspace.workspaceType);
  const hasWorkspaceType = Boolean(workspace.workspaceType);
  const hasAccountClass = Boolean(workspace.accountClass);
  const hasStoredPair = Boolean(hasWorkspaceType && hasAccountClass);
  const hasAnyStoredValue = Boolean(hasWorkspaceType || hasAccountClass);
  const pairIncomplete = hasAnyStoredValue && !hasStoredPair;
  const effectiveClass = storedClass ?? signalClass;
  const recommendedAccountClass = workspace.workspaceType ? (recommendedAccountClassByWorkspaceType[workspace.workspaceType] ?? "") : "";
  const recommendationMismatch = Boolean(recommendedAccountClass && workspace.accountClass && workspace.accountClass !== recommendedAccountClass);
  const signalMismatch = Boolean(storedClass && signalClass !== storedClass);
  const warnings: ReadinessWarning[] = [];

  if (pairIncomplete) {
    warnings.push({
      key: "pair-incomplete",
      status: "Blocked",
      title: "Classification pair incomplete",
      message: "Workspace type and account class must be stored together before plan visibility can be trusted.",
    });
  }

  if (!hasStoredPair) {
    warnings.push({
      key: "missing-stored-classification",
      status: "Check",
      title: "Still using inferred classification",
      message: "Save a workspace type and account class before registration or plan-selection work is connected to this surface.",
    });
  }

  if (recommendationMismatch) {
    warnings.push({
      key: "account-class-mismatch",
      status: "Check",
      title: "Account class differs from the usual recommendation",
      message: `${dbLabel(workspace.workspaceType)} usually uses ${dbLabel(recommendedAccountClass)}. Keep the saved value only if this is intentional.`,
    });
  }

  if (signalMismatch) {
    warnings.push({
      key: "signal-mismatch",
      status: "Check",
      title: "Stored classification differs from record signals",
      message: `Stored as ${storedClass}, while current records look closer to ${signalClass}. Review before using this classification in signup or billing rules.`,
    });
  }

  const status: StatusTone = pairIncomplete ? "Blocked" : warnings.length > 0 ? "Check" : "Ready";
  const label = hasStoredPair ? `${dbLabel(workspace.workspaceType)} / ${dbLabel(workspace.accountClass)}` : "Inferred only";
  const note = hasStoredPair
    ? "Stored classification is available for Super Admin review."
    : `Current record signals suggest ${signalClass}.`;

  return { hasStoredPair, hasAnyStoredValue, pairIncomplete, storedClass, signalClass, effectiveClass, recommendedAccountClass, recommendationMismatch, signalMismatch, status, label, note, warnings };
}

function trialSummary(subscription?: WorkspaceSubscriptionPreview | null) {
  if (!subscription) return { status: "Blocked" as const, label: "No subscription record", note: "Assign a plan before this workspace can be treated as subscription-ready." };
  if (subscription.status === "TRIAL") {
    return {
      status: "Check" as const,
      label: "Trial workspace",
      note: subscription.trialEndsAt ? `Trial ends ${new Date(subscription.trialEndsAt).toLocaleDateString()}.` : "Trial status is present, but no trial end date is stored yet.",
    };
  }
  if (subscription.status === "ACTIVE") return { status: "Ready" as const, label: "Active paid workspace", note: "Workspace is marked active for subscription access." };
  if (subscription.status === "PAST_DUE") return { status: "Blocked" as const, label: "Past due", note: "Billing status should gate paid features only after explicit enforcement approval." };
  if (subscription.status === "PAUSED" || subscription.status === "CANCELED") return { status: "Blocked" as const, label: dbLabel(subscription.status), note: "Workspace access should be reviewed before Super Admin activates hard gates." };
  return { status: "Check" as const, label: dbLabel(subscription.status), note: "Review subscription state before launch." };
}

function billingGateSummary(workspace: WorkspaceRow, subscription?: WorkspaceSubscriptionPreview | null) {
  if (!workspace.isActive) return { status: "Blocked" as const, label: "Workspace inactive", note: "Workspace is inactive. Paid feature gating remains a future enforcement step." };
  if (!subscription) return { status: "Blocked" as const, label: "No subscription", note: "No workspace subscription is stored yet." };
  if (subscription.status === "PAST_DUE" || subscription.status === "PAUSED" || subscription.status === "CANCELED") {
    return { status: "Blocked" as const, label: "Billing review needed", note: "Subscription state should be reviewed before future billing gates are activated." };
  }
  if (subscription.billingProvider === "STRIPE" && subscription.providerSyncStatus !== "SYNCED") {
    return { status: "Check" as const, label: "Stripe handoff not synced", note: "Stripe ids or webhook sync still need review before live billing." };
  }
  return { status: "Ready" as const, label: "Access allowed", note: "Workspace is active and subscription state allows access." };
}

function getUsage(workspace: WorkspaceRow) {
  const counts = workspace._count ?? {};
  const activeUsers = (workspace.users ?? []).filter((user) => user.isActive);
  return {
    users: counts.users ?? activeUsers.length,
    trucks: counts.trucks ?? 0,
    phoneNumbers: workspace.isActive ? 1 : 0,
  };
}

function ownedInterfaceSummary(workspace: WorkspaceRow) {
  const activeUsers = (workspace.users ?? []).filter((user) => user.isActive);
  const driverUsers = activeUsers.filter((user) => user.role === "COMPANY_DRIVER").length;
  const ownerOperatorUsers = activeUsers.filter((user) => user.role === "OWNER_OPERATOR").length;
  const accountingUsers = activeUsers.filter((user) => user.role === "ACCOUNTING").length;
  const counts = workspace._count ?? {};

  return [
    { label: "Driver interfaces", value: driverUsers, note: driverUsers > 0 ? "Driver login users already exist." : `${counts.drivers ?? 0} driver records exist; portal access may be invited later.` },
    { label: "Owner-operator users", value: ownerOperatorUsers, note: ownerOperatorUsers > 0 ? "Owner-operator login users already exist." : `${counts.ownerOperators ?? 0} owner-operator records exist.` },
    { label: "Accounting users", value: accountingUsers, note: accountingUsers > 0 ? "Accounting access exists." : "Accounting access can be invited when needed." },
    { label: "Customer/carrier portals", value: 0, note: "Portal ownership is planned but not yet represented as a dedicated schema object." },
  ];
}

function planMatchesWorkspaceClass(plan: SubscriptionPlanDraft, workspaceClass: WorkspaceClassKey) {
  const features = plan.featureAccess;
  if (workspaceClass === "Driver Interface" || workspaceClass === "Shipper / Customer Portal") return "Owned interface / portal, not sold directly by default";
  if (workspaceClass === "Platform Marketplace") return "Platform access should stay plan/policy controlled";
  if (workspaceClass === "Freight Broker") return features.loadBoard ? "Potential broker tier base" : "Needs broker distribution/load-board expansion";
  if (workspaceClass === "Company / Fleet") return features.routePlanning && features.reports ? "Fleet-ready base" : "Starter fleet only";
  if (workspaceClass === "Carrier / Owner-Operator") return features.dispatch && features.billing ? "Carrier-ready base" : "Needs carrier workflow review";
  if (workspaceClass === "Internal Operations") return "Hidden from public sales";
  return features.dispatch ? "Dispatcher-ready base" : "Not dispatcher-ready";
}

function planVisibilityFit(plan: SubscriptionPlanDraft, workspace: WorkspaceRow): PlanVisibilityFit {
  const workspaceType = workspace.workspaceType ?? "";
  const accountClass = workspace.accountClass ?? "";

  if (!workspaceType || !accountClass) {
    return {
      status: "Check",
      label: "Needs stored classification",
      note: "Save workspace type and account class before trusting plan visibility for this workspace.",
    };
  }

  const listed = plan.visibleWorkspaceTypes.includes(workspaceType);

  if (accountClass === "INTERNAL_WORKSPACE") {
    if (plan.planVisibility === "Internal" || listed) {
      return { status: "Ready", label: "Internal fit", note: "This plan is hidden from normal public selection or explicitly listed for this internal workspace type." };
    }
    return { status: "Check", label: "Internal plan review", note: "Internal workspaces should normally use internal or manually assigned plans." };
  }

  if (accountClass === "PLATFORM_LAYER") {
    if (plan.planVisibility === "Internal") {
      return { status: "Ready", label: "Platform hidden", note: "Platform marketplace access remains hidden until policy and plan gates are approved." };
    }
    return { status: "Planning", label: "Platform access not enforced", note: "Marketplace access should stay behind future plan, verification, billing-state, and Super Admin policy controls." };
  }

  if (accountClass === "OWNED_INTERFACE" || accountClass === "INVITED_PORTAL") {
    if (listed || plan.planVisibility === "Public") {
      return { status: "Check", label: "Direct-sale review", note: "Owned interfaces and invited portals should not be sold directly by default. Review this plan visibility before registration is changed." };
    }
    return { status: "Ready", label: "Not sold directly", note: "This interface/portal is not listed for normal paid plan selection." };
  }

  if (paidWorkspaceTypes.has(workspaceType) && listed) {
    return { status: "Ready", label: "Listed for this type", note: "The saved plan visibility includes this workspace type." };
  }

  if (paidWorkspaceTypes.has(workspaceType) && plan.planFamily === "General") {
    return { status: "Check", label: "General fallback", note: "General plan family may fit, but the saved visible workspace type list does not include this workspace type yet." };
  }

  if (plan.planVisibility === "Internal") {
    return { status: "Blocked", label: "Internal plan", note: "This plan should not appear for normal customer workspace selection." };
  }

  return { status: "Check", label: "Not listed for this type", note: "Update plan visibility before using this plan in registration for this workspace type." };
}

function getReadinessWarnings(input: {
  workspace: WorkspaceRow;
  classification: ClassificationState;
  plan: SubscriptionPlanDraft;
  planVisibility: PlanVisibilityFit;
  limits: SubscriptionLimitSignal[];
  trial: ReturnType<typeof trialSummary>;
  billingGate: ReturnType<typeof billingGateSummary>;
}) {
  const warnings: ReadinessWarning[] = [...input.classification.warnings];
  const paidWorkspace = input.workspace.accountClass === "PAID_WORKSPACE" || (!input.workspace.accountClass && getDefinition(input.classification.effectiveClass).accountClass === "Paid workspace");

  if (paidWorkspace && !input.workspace.workspaceSubscription) {
    warnings.push({
      key: "missing-subscription",
      status: "Blocked",
      title: "Paid workspace has no subscription record",
      message: "Assign or review a plan before this workspace is treated as registration-ready.",
    });
  }

  if (input.planVisibility.status !== "Ready") {
    warnings.push({
      key: "plan-visibility-fit",
      status: input.planVisibility.status === "Blocked" ? "Blocked" : "Check",
      title: "Plan visibility needs review",
      message: input.planVisibility.note,
    });
  }

  const overLimit = input.limits.find((item) => item.over > 0);
  if (overLimit) {
    warnings.push({
      key: "usage-over-plan-limit",
      status: "Check",
      title: "Usage is over the current plan limit",
      message: `${overLimit.label} is ${overLimit.over} over the included amount. Review add-ons or plan assignment before enforcing limits.`,
    });
  }

  if (input.billingGate.status === "Blocked") {
    warnings.push({
      key: "billing-state-review",
      status: "Check",
      title: "Billing state needs review",
      message: input.billingGate.note,
    });
  }

  if (input.trial.status === "Check" && input.workspace.workspaceSubscription?.status === "TRIAL" && !input.workspace.workspaceSubscription.trialEndsAt) {
    warnings.push({
      key: "trial-date-missing",
      status: "Check",
      title: "Trial end date missing",
      message: "Trial status exists, but the trial end date is not stored yet.",
    });
  }

  return warnings;
}

function Section({ title, subtitle, children }: { title: string; subtitle: string; children: ReactNode }) {
  return (
    <section className="rounded-2xl border bg-white p-6 shadow-sm">
      <div className="flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between">
        <div>
          <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>
      </div>
      <div className="mt-5">{children}</div>
    </section>
  );
}

export function AdminWorkspaceTypeSubscriptionOverviewClient() {
  const [workspaces, setWorkspaces] = useState<WorkspaceRow[]>([]);
  const [plans, setPlans] = useState<SubscriptionPlanDraft[]>([]);
  const [selectedClass, setSelectedClass] = useState<WorkspaceClassKey | "All">("All");
  const [selectedWorkspaceId, setSelectedWorkspaceId] = useState<string>("");
  const [loaded, setLoaded] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [classificationDraft, setClassificationDraft] = useState({ workspaceType: "", accountClass: "" });
  const [classificationSaving, setClassificationSaving] = useState(false);
  const [classificationNotice, setClassificationNotice] = useState<string | null>(null);
  const [bulkSaving, setBulkSaving] = useState(false);
  const [bulkNotice, setBulkNotice] = useState<string | null>(null);

  async function loadAll() {
    try {
      setError(null);
      const [workspaceData, planData] = await Promise.all([
        apiGet<{ workspaces: WorkspaceRow[] }>("/api/workspaces"),
        apiGet<{ plans: SubscriptionPlanDraft[] }>("/api/subscriptions"),
      ]);
      setWorkspaces(workspaceData.workspaces);
      setPlans(planData.plans);
      setSelectedWorkspaceId((current) => current || workspaceData.workspaces[0]?.id || "");
    } catch (err: any) {
      setError(err?.message ?? "Failed to load Super Admin workspace type overview");
    } finally {
      setLoaded(true);
    }
  }

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

  const enrichedWorkspaces = useMemo(() => workspaces.map((workspace) => {
    const classification = buildClassificationState(workspace);
    const inferredClass = classification.effectiveClass;
    const definition = getDefinition(inferredClass);
    const usage = getUsage(workspace);
    const plan = workspace.workspaceSubscription?.plan ?? getStagedPlanForWorkspace(usage);
    const limits = evaluateSubscriptionLimits(plan, usage);
    const features = evaluateFeatureAccess(plan);
    const trial = trialSummary(workspace.workspaceSubscription);
    const billingGate = billingGateSummary(workspace, workspace.workspaceSubscription);
    const ownedInterfaces = ownedInterfaceSummary(workspace);
    const overLimitCount = limits.filter((item) => item.over > 0).length;
    const planVisibility = planVisibilityFit(plan, workspace);
    const readinessWarnings = getReadinessWarnings({ workspace, classification, plan, planVisibility, limits, trial, billingGate });
    return { workspace, inferredClass, classification, definition, usage, plan, limits, features, trial, billingGate, ownedInterfaces, overLimitCount, planVisibility, readinessWarnings };
  }), [workspaces]);

  const filteredWorkspaces = selectedClass === "All" ? enrichedWorkspaces : enrichedWorkspaces.filter((item) => item.inferredClass === selectedClass);
  const selected = enrichedWorkspaces.find((item) => item.workspace.id === selectedWorkspaceId) ?? enrichedWorkspaces[0] ?? null;

  useEffect(() => {
    if (!selected) return;
    setClassificationDraft({
      workspaceType: selected.workspace.workspaceType ?? "",
      accountClass: selected.workspace.accountClass ?? "",
    });
    setClassificationNotice(null);
  }, [selected?.workspace.id, selected?.workspace.workspaceType, selected?.workspace.accountClass]);

  async function saveClassification() {
    if (!selected || classificationSaving) return;
    try {
      setClassificationSaving(true);
      setClassificationNotice(null);
      await apiPatch(`/api/workspaces/${selected.workspace.id}/classification`, {
        workspaceType: classificationDraft.workspaceType || null,
        accountClass: classificationDraft.accountClass || null,
      });
      await loadAll();
      setClassificationNotice("Classification saved. Registration, billing gates, Stripe, portal ownership, broker distribution, and plan enforcement were not changed.");
    } catch (err: any) {
      setClassificationNotice(err?.message ?? "Failed to save workspace classification.");
    } finally {
      setClassificationSaving(false);
    }
  }



  async function runBulkClassificationCleanup() {
    if (bulkSaving) return;
    const workspaceIds = bulkCandidateRows.map((item) => item.workspace.id).slice(0, 50);
    if (workspaceIds.length === 0) {
      setBulkNotice("No completely unclassified workspaces are ready for the bulk helper in this view.");
      return;
    }

    try {
      setBulkSaving(true);
      setBulkNotice(null);
      const result = await apiPost<BulkClassificationResult>("/api/workspaces/classification/bulk", { workspaceIds });
      await loadAll();
      setBulkNotice(`Bulk helper reviewed ${result.requested} workspace${result.requested === 1 ? '' : 's'}: ${result.updated} saved, ${result.skipped} skipped, ${result.missing} missing. No registration, Stripe, billing gate, portal, broker distribution, or internal load-board access was changed.`);
    } catch (err: any) {
      setBulkNotice(err?.message ?? "Failed to run bulk classification helper.");
    } finally {
      setBulkSaving(false);
    }
  }

  const classStats = workspaceClassDefinitions.map((definition) => {
    const matching = enrichedWorkspaces.filter((item) => item.inferredClass === definition.key);
    return {
      ...definition,
      count: matching.length,
      stored: matching.filter((item) => item.classification.hasStoredPair).length,
      inferred: matching.filter((item) => !item.classification.hasStoredPair).length,
      review: matching.filter((item) => item.readinessWarnings.length > 0).length,
    };
  });

  const summary = {
    total: enrichedWorkspaces.length,
    paid: enrichedWorkspaces.filter((item) => item.definition.accountClass === "Paid workspace").length,
    classified: enrichedWorkspaces.filter((item) => item.classification.hasStoredPair).length,
    stillInferred: enrichedWorkspaces.filter((item) => !item.classification.hasStoredPair).length,
    readinessWarnings: enrichedWorkspaces.filter((item) => item.readinessWarnings.length > 0).length,
    planVisibilityWarnings: enrichedWorkspaces.filter((item) => item.planVisibility.status !== "Ready").length,
    trial: enrichedWorkspaces.filter((item) => item.workspace.workspaceSubscription?.status === "TRIAL").length,
  };

  const readinessWarningRows = enrichedWorkspaces
    .filter((item) => item.readinessWarnings.length > 0)
    .slice(0, 8);

  const bulkEligibleRows = filteredWorkspaces.filter((item) => !item.classification.hasAnyStoredValue && Boolean(recommendedWorkspaceTypeByClass[item.inferredClass]));
  const bulkCandidateRows = bulkEligibleRows.slice(0, 50);
  const manualCleanupAllRows = filteredWorkspaces
    .filter((item) => item.classification.pairIncomplete || item.classification.recommendationMismatch || item.classification.signalMismatch);
  const manualCleanupRows = manualCleanupAllRows.slice(0, 8);
  const alreadyStoredInView = filteredWorkspaces.filter((item) => item.classification.hasStoredPair).length;


  const recommendedWorkspaceType = selected ? (recommendedWorkspaceTypeByClass[selected.inferredClass] ?? "") : "";
  const recommendedAccountClass = classificationDraft.workspaceType ? (recommendedAccountClassByWorkspaceType[classificationDraft.workspaceType] ?? "") : "";
  const classificationPairIncomplete = Boolean((classificationDraft.workspaceType && !classificationDraft.accountClass) || (!classificationDraft.workspaceType && classificationDraft.accountClass));
  const classificationRecommendationMismatch = Boolean(recommendedAccountClass && classificationDraft.accountClass && recommendedAccountClass !== classificationDraft.accountClass);

  if (!loaded) return <div className="rounded-2xl border bg-white p-6 text-sm text-slate-500">Loading workspace type and subscription overview...</div>;
  if (error) return <div className="rounded-2xl border border-rose-100 bg-rose-50 p-6 text-sm text-rose-700">{error}</div>;

  return (
    <div className="space-y-6">
      <Section title="Control surface status" subtitle="This Super Admin surface uses stored workspace type and account class first, keeps inference only as a fallback, and still avoids registration, Stripe, billing-gate, portal, broker-distribution, or internal load-board enforcement changes.">
        <div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-6">
          <div className="rounded-2xl border border-slate-100 bg-slate-50 p-4">
            <div className="text-xs font-semibold uppercase tracking-[0.18em] text-slate-500">Workspaces</div>
            <div className="mt-2 text-3xl font-semibold text-slate-900">{summary.total}</div>
          </div>
          <div className="rounded-2xl border border-slate-100 bg-slate-50 p-4">
            <div className="text-xs font-semibold uppercase tracking-[0.18em] text-slate-500">Paid candidates</div>
            <div className="mt-2 text-3xl font-semibold text-slate-900">{summary.paid}</div>
          </div>
          <div className="rounded-2xl border border-emerald-100 bg-emerald-50 p-4">
            <div className="text-xs font-semibold uppercase tracking-[0.18em] text-emerald-700">Classified</div>
            <div className="mt-2 text-3xl font-semibold text-slate-900">{summary.classified}</div>
            <div className="mt-1 text-xs leading-5 text-emerald-800">Stored type and account class.</div>
          </div>
          <div className="rounded-2xl border border-amber-100 bg-amber-50 p-4">
            <div className="text-xs font-semibold uppercase tracking-[0.18em] text-amber-700">Still inferred</div>
            <div className="mt-2 text-3xl font-semibold text-slate-900">{summary.stillInferred}</div>
            <div className="mt-1 text-xs leading-5 text-amber-800">Needs stored classification.</div>
          </div>
          <div className="rounded-2xl border border-amber-100 bg-amber-50 p-4">
            <div className="text-xs font-semibold uppercase tracking-[0.18em] text-amber-700">Readiness warnings</div>
            <div className="mt-2 text-3xl font-semibold text-slate-900">{summary.readinessWarnings}</div>
            <div className="mt-1 text-xs leading-5 text-amber-800">Review before signup work.</div>
          </div>
          <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">Plan visibility checks</div>
            <div className="mt-2 text-3xl font-semibold text-slate-900">{summary.planVisibilityWarnings}</div>
            <div className="mt-1 text-xs leading-5 text-blue-800">No enforcement active.</div>
          </div>
        </div>
        <div className="mt-4 flex flex-wrap gap-2">
          <Link href="/admin/workspaces/subscriptions" className="rounded-xl border border-slate-200 px-3 py-2 text-sm font-semibold text-slate-700">Open workspace subscriptions</Link>
          <Link href="/admin/subscriptions" className="rounded-xl border border-slate-200 px-3 py-2 text-sm font-semibold text-slate-700">Open plan manager</Link>
          <Link href="/admin/stripe-readiness" className="rounded-xl border border-slate-200 px-3 py-2 text-sm font-semibold text-slate-700">Open Stripe readiness</Link>
          <Link href="/admin/workspaces/create" className="rounded-xl border border-slate-200 px-3 py-2 text-sm font-semibold text-slate-700">Provision workspace</Link>
        </div>
      </Section>

      <Section title="Classification coverage summary" subtitle="This shows which workspace categories are stored, which are still inferred, and where Super Admin should review before plan visibility or registration work continues.">
        <div className="grid gap-3 lg:grid-cols-2 xl:grid-cols-4">
          {classStats.map((definition) => (
            <div key={definition.key} className="rounded-2xl border border-slate-100 bg-white p-4 shadow-sm">
              <div className="flex items-start justify-between gap-3">
                <div>
                  <h3 className="font-semibold text-slate-900">{definition.key}</h3>
                  <div className="mt-1 text-xs font-semibold uppercase tracking-[0.14em] text-slate-500">{definition.accountClass}</div>
                </div>
                <span className="rounded-full bg-slate-100 px-2.5 py-1 text-xs font-semibold text-slate-700">{definition.count} total</span>
              </div>
              <div className="mt-4 grid grid-cols-3 gap-2 text-center text-xs">
                <div className="rounded-xl bg-emerald-50 p-2 text-emerald-800"><div className="text-lg font-semibold text-slate-900">{definition.stored}</div>Stored</div>
                <div className="rounded-xl bg-amber-50 p-2 text-amber-800"><div className="text-lg font-semibold text-slate-900">{definition.inferred}</div>Inferred</div>
                <div className="rounded-xl bg-rose-50 p-2 text-rose-800"><div className="text-lg font-semibold text-slate-900">{definition.review}</div>Review</div>
              </div>
              <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">Plan visibility:</span> {definition.planVisibilityRule}</div>
            </div>
          ))}
        </div>
        <div className="mt-4 rounded-2xl border border-amber-100 bg-amber-50 p-4">
          <div className="flex flex-col gap-2 md:flex-row md:items-start md:justify-between">
            <div>
              <h3 className="font-semibold text-slate-900">Top readiness warnings</h3>
              <p className="mt-1 text-sm leading-6 text-amber-800">Warnings are review notes only. They do not enforce registration, Stripe, billing gates, broker distribution, portal access, or internal load-board access.</p>
            </div>
            {statusPill(summary.readinessWarnings > 0 ? "Check" : "Ready")}
          </div>
          <div className="mt-4 grid gap-2 lg:grid-cols-2">
            {readinessWarningRows.length > 0 ? readinessWarningRows.map((item) => (
              <div key={item.workspace.id} className="rounded-xl bg-white p-3 text-sm">
                <div className="flex items-start justify-between gap-3">
                  <div>
                    <div className="font-semibold text-slate-900">{item.workspace.name}</div>
                    <div className="mt-1 text-xs text-slate-500">{item.classification.label} · {item.plan.name}</div>
                  </div>
                  {statusPill(item.readinessWarnings.some((warning) => warning.status === "Blocked") ? "Blocked" : "Check")}
                </div>
                <div className="mt-2 text-xs leading-5 text-slate-600">{item.readinessWarnings[0]?.title}: {item.readinessWarnings[0]?.message}</div>
              </div>
            )) : <div className="rounded-xl bg-white p-3 text-sm text-slate-600">No readiness warnings found.</div>}
          </div>
        </div>
      </Section>

      <Section title="Bulk classification cleanup helper" subtitle="Use this only to save server-recommended workspace type and account class for completely unclassified workspaces. Existing stored values, partial pairs, and signal mismatches stay manual so the helper does not overwrite intentional Super Admin decisions.">
        <div className="grid gap-3 lg:grid-cols-4">
          <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">Ready for helper</div>
            <div className="mt-2 text-3xl font-semibold text-slate-900">{bulkEligibleRows.length}</div>
            <div className="mt-1 text-xs leading-5 text-blue-800">Completely unclassified in this view. First 50 can be saved at once.</div>
          </div>
          <div className="rounded-2xl border border-amber-100 bg-amber-50 p-4">
            <div className="text-xs font-semibold uppercase tracking-[0.18em] text-amber-700">Manual cleanup</div>
            <div className="mt-2 text-3xl font-semibold text-slate-900">{manualCleanupAllRows.length}</div>
            <div className="mt-1 text-xs leading-5 text-amber-800">Partial, unusual, or signal-mismatch records.</div>
          </div>
          <div className="rounded-2xl border border-emerald-100 bg-emerald-50 p-4">
            <div className="text-xs font-semibold uppercase tracking-[0.18em] text-emerald-700">Already stored</div>
            <div className="mt-2 text-3xl font-semibold text-slate-900">{alreadyStoredInView}</div>
            <div className="mt-1 text-xs leading-5 text-emerald-800">No bulk overwrite.</div>
          </div>
          <div className="rounded-2xl border border-slate-100 bg-slate-50 p-4">
            <div className="text-xs font-semibold uppercase tracking-[0.18em] text-slate-500">Current scope</div>
            <div className="mt-2 text-lg font-semibold text-slate-900">{selectedClass === "All" ? "All classes" : selectedClass}</div>
            <div className="mt-1 text-xs leading-5 text-slate-600">Class filter controls which workspaces are included.</div>
          </div>
        </div>

        <div className="mt-4 rounded-2xl border border-slate-100 bg-white p-4">
          <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
            <div>
              <h3 className="font-semibold text-slate-900">Recommended bulk save</h3>
              <p className="mt-1 text-sm leading-6 text-slate-500">The server rechecks each selected workspace before saving. It only updates workspaces where both stored fields are empty.</p>
            </div>
            <button type="button" onClick={runBulkClassificationCleanup} disabled={bulkSaving || bulkCandidateRows.length === 0} className="rounded-xl bg-slate-900 px-4 py-2 text-sm font-semibold text-white disabled:cursor-not-allowed disabled:bg-slate-300">{bulkSaving ? "Saving recommendations..." : "Save recommended classifications"}</button>
          </div>
          {bulkNotice ? <div className="mt-3 rounded-xl border border-slate-200 bg-slate-50 p-3 text-sm leading-6 text-slate-700">{bulkNotice}</div> : null}
          <div className="mt-4 grid gap-2 lg:grid-cols-2">
            {bulkCandidateRows.length > 0 ? bulkCandidateRows.slice(0, 10).map((item) => {
              const recommendedType = recommendedWorkspaceTypeByClass[item.inferredClass] ?? "";
              const recommendedClass = recommendedType ? (recommendedAccountClassByWorkspaceType[recommendedType] ?? "") : "";
              return (
                <div key={item.workspace.id} className="rounded-xl bg-slate-50 p-3 text-sm">
                  <div className="flex items-start justify-between gap-3">
                    <div>
                      <div className="font-semibold text-slate-900">{item.workspace.name}</div>
                      <div className="mt-1 text-xs text-slate-500">Signal: {item.classification.signalClass}</div>
                    </div>
                    {statusPill("Planning")}
                  </div>
                  <div className="mt-2 text-xs leading-5 text-slate-600">Will save {dbLabel(recommendedType)} / {dbLabel(recommendedClass)} if still unclassified on the server.</div>
                </div>
              );
            }) : <div className="rounded-xl bg-slate-50 p-3 text-sm text-slate-600">No completely unclassified workspaces are ready in this view.</div>}
          </div>
        </div>

        <div className="mt-4 rounded-2xl border border-amber-100 bg-amber-50 p-4">
          <h3 className="font-semibold text-slate-900">Manual cleanup queue</h3>
          <p className="mt-1 text-sm leading-6 text-amber-800">These stay manual because they may reflect intentional exceptions or incomplete prior work.</p>
          <div className="mt-4 grid gap-2 lg:grid-cols-2">
            {manualCleanupRows.length > 0 ? manualCleanupRows.map((item) => (
              <div key={item.workspace.id} className="rounded-xl bg-white p-3 text-sm">
                <div className="flex items-start justify-between gap-3">
                  <div>
                    <div className="font-semibold text-slate-900">{item.workspace.name}</div>
                    <div className="mt-1 text-xs text-slate-500">Stored: {dbLabel(item.workspace.workspaceType)} / {dbLabel(item.workspace.accountClass)}</div>
                  </div>
                  {statusPill(item.classification.pairIncomplete ? "Blocked" : "Check")}
                </div>
                <div className="mt-2 text-xs leading-5 text-slate-600">{item.classification.warnings[0]?.title ?? "Review classification"}: {item.classification.warnings[0]?.message ?? "Open the workspace and confirm the stored values."}</div>
              </div>
            )) : <div className="rounded-xl bg-white p-3 text-sm text-slate-600">No manual cleanup rows in this view.</div>}
          </div>
        </div>

        <div className="mt-4 rounded-xl border border-blue-100 bg-blue-50 p-3 text-xs leading-5 text-blue-800"><span className="font-semibold">Guardrail:</span> bulk cleanup writes classification and audit records only. It does not change public registration, plan sales, Stripe checkout, subscription status, hard billing gates, owned portal rules, broker distribution limits, or internal load-board access.</div>
      </Section>

      <Section title="Workspace type and billing gate review" subtitle="Select a workspace to see stored classification, record-signal fallback, trial/subscription status, plan limits, owned interfaces, invited portal readiness, and billing gate state.">
        <div className="grid gap-4 xl:grid-cols-[360px_1fr]">
          <div className="rounded-2xl border border-slate-100 bg-slate-50 p-3">
            <div className="mb-3 flex flex-wrap gap-2">
              <button onClick={() => setSelectedClass("All")} className={`rounded-full border px-3 py-1.5 text-xs font-semibold ${selectedClass === "All" ? "border-slate-900 bg-slate-900 text-white" : "border-slate-200 bg-white text-slate-700"}`}>All</button>
              {workspaceClassDefinitions.map((definition) => (
                <button key={definition.key} onClick={() => setSelectedClass(definition.key)} className={`rounded-full border px-3 py-1.5 text-xs font-semibold ${selectedClass === definition.key ? "border-slate-900 bg-slate-900 text-white" : "border-slate-200 bg-white text-slate-700"}`}>{definition.key}</button>
              ))}
            </div>
            <div className="max-h-[720px] space-y-2 overflow-y-auto pr-1">
              {filteredWorkspaces.map((item) => (
                <button key={item.workspace.id} type="button" onClick={() => setSelectedWorkspaceId(item.workspace.id)} className={`w-full rounded-xl border p-3 text-left transition ${selected?.workspace.id === item.workspace.id ? "border-blue-200 bg-blue-50" : "border-slate-100 bg-white hover:border-slate-200"}`}>
                  <div className="flex items-start justify-between gap-3">
                    <div>
                      <div className="font-semibold text-slate-900">{item.workspace.name}</div>
                      <div className="mt-1 text-xs text-slate-500">/{item.workspace.slug}</div>
                    </div>
                    {statusPill(item.readinessWarnings.length > 0 ? (item.readinessWarnings.some((warning) => warning.status === "Blocked") ? "Blocked" : "Check") : "Ready")}
                  </div>
                  <div className="mt-3 flex flex-wrap gap-2 text-[11px] font-semibold text-slate-600">
                    <span className="rounded-full bg-slate-100 px-2 py-1">{item.inferredClass}</span>
                    <span className={`rounded-full px-2 py-1 ${item.classification.hasStoredPair ? "bg-emerald-100 text-emerald-700" : "bg-amber-100 text-amber-700"}`}>{item.classification.hasStoredPair ? "Stored" : "Inferred"}</span>
                    <span className="rounded-full bg-slate-100 px-2 py-1">{item.workspace.workspaceSubscription?.status ?? "No subscription"}</span>
                    <span className="rounded-full bg-slate-100 px-2 py-1">{item.plan.name}</span>
                  </div>
                </button>
              ))}
            </div>
          </div>

          {selected ? (
            <div className="space-y-4">
              <div className="rounded-2xl border border-slate-100 bg-white p-5 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-slate-500">Selected workspace</div>
                    <h3 className="mt-1 text-2xl font-semibold text-slate-900">{selected.workspace.name}</h3>
                    <p className="mt-1 text-sm leading-6 text-slate-500">/{selected.workspace.slug} · {selected.classification.label}</p>
                  </div>
                  <div className="flex flex-wrap gap-2">
                    {statusPill(selected.classification.status)}
                    {statusPill(selected.trial.status)}
                    {statusPill(selected.billingGate.status)}
                  </div>
                </div>
                <div className="mt-5 grid gap-3 lg:grid-cols-4">
                  <div className="rounded-xl border border-slate-100 bg-slate-50 p-4">
                    <div className="text-xs font-semibold uppercase tracking-[0.16em] text-slate-500">Stored classification</div>
                    <div className="mt-2 text-lg font-semibold text-slate-900">{selected.classification.hasStoredPair ? selected.inferredClass : "Not stored"}</div>
                    <p className="mt-2 text-xs leading-5 text-slate-600">{selected.classification.note}</p>
                  </div>
                  <div className="rounded-xl border border-slate-100 bg-slate-50 p-4">
                    <div className="text-xs font-semibold uppercase tracking-[0.16em] text-slate-500">Record signal</div>
                    <div className="mt-2 text-lg font-semibold text-slate-900">{selected.classification.signalClass}</div>
                    <p className="mt-2 text-xs leading-5 text-slate-600">Used only as a fallback for unclassified workspaces.</p>
                  </div>
                  <div className="rounded-xl border border-slate-100 bg-slate-50 p-4">
                    <div className="text-xs font-semibold uppercase tracking-[0.16em] text-slate-500">Trial/subscription</div>
                    <div className="mt-2 text-lg font-semibold text-slate-900">{selected.trial.label}</div>
                    <p className="mt-2 text-xs leading-5 text-slate-600">{selected.trial.note}</p>
                  </div>
                  <div className="rounded-xl border border-slate-100 bg-slate-50 p-4">
                    <div className="text-xs font-semibold uppercase tracking-[0.16em] text-slate-500">Plan visibility</div>
                    <div className="mt-2 text-lg font-semibold text-slate-900">{selected.planVisibility.label}</div>
                    <p className="mt-2 text-xs leading-5 text-slate-600">{selected.planVisibility.note}</p>
                  </div>
                </div>
              </div>

              <div className="rounded-2xl border border-blue-100 bg-blue-50 p-5 shadow-sm">
                <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
                  <div>
                    <h3 className="font-semibold text-slate-900">Guarded classification workflow</h3>
                    <p className="mt-1 text-sm leading-6 text-blue-800">Set the stored workspace type and account class for this existing workspace. This is an audited planning/control action only; it does not change registration, billing gates, Stripe status, plan enforcement, portal ownership, broker distribution, or internal load-board access.</p>
                  </div>
                  {statusPill(selected.classification.hasStoredPair ? "Ready" : "Check")}
                </div>
                <div className="mt-4 grid gap-3 lg:grid-cols-3">
                  <div className="rounded-xl bg-white p-3">
                    <div className="text-xs font-semibold uppercase tracking-[0.16em] text-slate-500">Current stored value</div>
                    <div className="mt-2 text-sm font-semibold text-slate-900">{dbLabel(selected.workspace.workspaceType)} / {dbLabel(selected.workspace.accountClass)}</div>
                    <p className="mt-1 text-xs leading-5 text-slate-600">Before value captured in the audit event when saved.</p>
                  </div>
                  <div className="rounded-xl bg-white p-3">
                    <div className="text-xs font-semibold uppercase tracking-[0.16em] text-slate-500">Current signal</div>
                    <div className="mt-2 text-sm font-semibold text-slate-900">{selected.classification.signalClass}</div>
                    <p className="mt-1 text-xs leading-5 text-slate-600">Recommended stored type: {recommendedWorkspaceType ? dbLabel(recommendedWorkspaceType) : "Review manually"}.</p>
                  </div>
                  <div className="rounded-xl bg-white p-3">
                    <div className="text-xs font-semibold uppercase tracking-[0.16em] text-slate-500">After save</div>
                    <div className="mt-2 text-sm font-semibold text-slate-900">{classificationDraft.workspaceType ? dbLabel(classificationDraft.workspaceType) : "Unclassified"} / {classificationDraft.accountClass ? dbLabel(classificationDraft.accountClass) : "Unclassified"}</div>
                    <p className="mt-1 text-xs leading-5 text-slate-600">After value will be stored on the workspace and written to the audit history.</p>
                  </div>
                </div>
                <div className="mt-4 grid gap-3 lg:grid-cols-[1fr_1fr_auto] lg:items-end">
                  <label className="block">
                    <span className="text-xs font-semibold uppercase tracking-[0.14em] text-slate-600">Workspace type</span>
                    <select value={classificationDraft.workspaceType} onChange={(event) => setClassificationDraft((current) => ({ ...current, workspaceType: event.target.value, accountClass: event.target.value ? (current.accountClass || (recommendedAccountClassByWorkspaceType[event.target.value] ?? "")) : "" }))} className="mt-2 w-full rounded-xl border border-slate-200 bg-white px-3 py-2 text-sm font-medium text-slate-800">
                      <option value="">Keep unclassified</option>
                      {workspaceTypeOptions.map((option) => <option key={option.value} value={option.value}>{option.label}</option>)}
                    </select>
                  </label>
                  <label className="block">
                    <span className="text-xs font-semibold uppercase tracking-[0.14em] text-slate-600">Account class</span>
                    <select value={classificationDraft.accountClass} onChange={(event) => setClassificationDraft((current) => ({ ...current, accountClass: event.target.value }))} className="mt-2 w-full rounded-xl border border-slate-200 bg-white px-3 py-2 text-sm font-medium text-slate-800">
                      <option value="">Keep unclassified</option>
                      {accountClassOptions.map((option) => <option key={option.value} value={option.value}>{option.label}</option>)}
                    </select>
                  </label>
                  <button type="button" onClick={saveClassification} disabled={classificationSaving || classificationPairIncomplete} className="rounded-xl bg-slate-900 px-4 py-2 text-sm font-semibold text-white disabled:cursor-not-allowed disabled:bg-slate-300">{classificationSaving ? "Saving..." : "Save classification"}</button>
                </div>
                <div className="mt-3 space-y-2 text-xs leading-5">
                  {classificationPairIncomplete ? <div className="rounded-xl border border-amber-200 bg-amber-50 p-3 text-amber-800">Workspace type and account class must be saved together, or both cleared.</div> : null}
                  {classificationRecommendationMismatch ? <div className="rounded-xl border border-amber-200 bg-amber-50 p-3 text-amber-800">The selected account class does not match the usual recommendation for this workspace type. Save only if this is intentional.</div> : null}
                  {classificationNotice ? <div className="rounded-xl border border-slate-200 bg-white p-3 text-slate-700">{classificationNotice}</div> : null}
                </div>
                <div className="mt-4 rounded-xl border border-blue-100 bg-white p-3 text-xs leading-5 text-blue-800"><span className="font-semibold">Guardrail:</span> this action only stores classification and writes an audit event. It does not sell a plan, start or end a trial, assign portal ownership, send billing to Stripe, change broker distribution, open the internal load board, or change user access.</div>
              </div>

              <div className="rounded-2xl border border-amber-100 bg-amber-50 p-5 shadow-sm">
                <div className="flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between">
                  <div>
                    <h3 className="font-semibold text-slate-900">Selected workspace readiness warnings</h3>
                    <p className="mt-1 text-sm leading-6 text-amber-800">Resolve these before connecting public registration, plan selection, hard billing gates, portals, broker distribution, or internal load-board access.</p>
                  </div>
                  {statusPill(selected.readinessWarnings.length > 0 ? "Check" : "Ready")}
                </div>
                <div className="mt-4 grid gap-2">
                  {selected.readinessWarnings.length > 0 ? selected.readinessWarnings.map((warning) => (
                    <div key={warning.key} className="rounded-xl bg-white p-3 text-sm">
                      <div className="flex items-start justify-between gap-3">
                        <div className="font-semibold text-slate-900">{warning.title}</div>
                        {statusPill(warning.status)}
                      </div>
                      <p className="mt-1 text-xs leading-5 text-slate-600">{warning.message}</p>
                    </div>
                  )) : <div className="rounded-xl bg-white p-3 text-sm text-slate-600">No readiness warnings for this selected workspace.</div>}
                </div>
              </div>

              <div className="rounded-2xl border border-slate-100 bg-white p-5 shadow-sm">
                <h3 className="font-semibold text-slate-900">Recent classification audit</h3>
                <p className="mt-1 text-sm leading-6 text-slate-500">Recent Super Admin classification changes for this workspace.</p>
                <div className="mt-4 space-y-2">
                  {(selected.workspace.superAdminAuditEvents ?? []).length > 0 ? (selected.workspace.superAdminAuditEvents ?? []).map((event) => (
                    <div key={event.id} className="rounded-xl bg-slate-50 p-3 text-sm">
                      <div className="flex flex-col gap-1 sm:flex-row sm:items-center sm:justify-between">
                        <span className="font-semibold text-slate-900">{event.summary}</span>
                        <span className="text-xs text-slate-500">{new Date(event.createdAt).toLocaleString()}</span>
                      </div>
                      <div className="mt-1 text-xs leading-5 text-slate-600">By {event.actorUser?.email ?? "Super Admin"}</div>
                    </div>
                  )) : <div className="rounded-xl bg-slate-50 p-3 text-sm text-slate-600">No classification audit events yet.</div>}
                </div>
              </div>

              <div className="grid gap-4 lg:grid-cols-2">
                <div className="rounded-2xl border border-slate-100 bg-white p-5 shadow-sm">
                  <h3 className="font-semibold text-slate-900">Entitlement summary</h3>
                  <p className="mt-1 text-sm leading-6 text-slate-500">{selected.plan.name}: {planLimitSummary(selected.plan)}. Monthly base {money(selected.plan.monthlyPrice)}.</p>
                  <div className="mt-3 rounded-xl border border-blue-100 bg-blue-50 p-3 text-xs leading-5 text-blue-800"><span className="font-semibold">Visibility fit:</span> {selected.planVisibility.label}. {selected.planVisibility.note}</div>
                  <div className="mt-4 flex flex-wrap gap-2">{selected.limits.map(limitPill)}</div>
                  <div className="mt-4 flex flex-wrap gap-2">{selected.features.map(featurePill)}</div>
                </div>
                <div className="rounded-2xl border border-slate-100 bg-white p-5 shadow-sm">
                  <h3 className="font-semibold text-slate-900">Owned interfaces and portals</h3>
                  <p className="mt-1 text-sm leading-6 text-slate-500">These are interfaces/users owned by the paid workspace, not necessarily separate paid subscriptions.</p>
                  <div className="mt-4 grid gap-2">
                    {selected.ownedInterfaces.map((item) => (
                      <div key={item.label} className="rounded-xl bg-slate-50 p-3 text-sm">
                        <div className="flex items-center justify-between gap-3"><span className="font-semibold text-slate-900">{item.label}</span><span className="rounded-full bg-white px-2 py-1 text-xs font-semibold text-slate-700">{item.value}</span></div>
                        <div className="mt-1 text-xs leading-5 text-slate-600">{item.note}</div>
                      </div>
                    ))}
                  </div>
                </div>
              </div>

              <div className="rounded-2xl border border-slate-100 bg-white p-5 shadow-sm">
                <h3 className="font-semibold text-slate-900">What Super Admin must control for this type</h3>
                <div className="mt-3 grid gap-2 sm:grid-cols-2 xl:grid-cols-3">
                  {selected.definition.superAdminMustControl.map((item) => <div key={item} className="rounded-xl bg-slate-50 px-3 py-2 text-sm font-medium text-slate-700">{item}</div>)}
                </div>
                <div className="mt-4 rounded-xl border border-blue-100 bg-blue-50 p-3 text-sm leading-6 text-blue-800"><span className="font-semibold">Owned interface rule:</span> {selected.definition.ownedInterfaceRule}</div>
              </div>
            </div>
          ) : <div className="rounded-2xl border border-slate-100 bg-white p-6 text-sm text-slate-500">No workspaces found.</div>}
        </div>
      </Section>

      <Section title="Plan visibility preview" subtitle="This preview compares saved plan family and visible workspace type fields against stored workspace classifications. It is review-only and does not enforce registration, Stripe checkout, billing gates, portals, broker distribution, or internal load-board access.">
        <div className="overflow-hidden rounded-2xl border border-slate-100">
          <table className="min-w-full divide-y divide-slate-100 text-sm">
            <thead className="bg-slate-50">
              <tr>
                <th className="px-4 py-3 text-left font-semibold text-slate-600">Plan</th>
                <th className="px-4 py-3 text-left font-semibold text-slate-600">Price</th>
                <th className="px-4 py-3 text-left font-semibold text-slate-600">Family</th>
                <th className="px-4 py-3 text-left font-semibold text-slate-600">Visibility</th>
                <th className="px-4 py-3 text-left font-semibold text-slate-600">Saved visible types</th>
                <th className="px-4 py-3 text-left font-semibold text-slate-600">Classified fit</th>
                <th className="px-4 py-3 text-left font-semibold text-slate-600">Needs review</th>
                <th className="px-4 py-3 text-left font-semibold text-slate-600">Current best for</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-100 bg-white">
              {plans.map((plan) => {
                const classifiedWorkspaces = enrichedWorkspaces.filter((item) => item.classification.hasStoredPair);
                const fitCount = classifiedWorkspaces.filter((item) => planVisibilityFit(plan, item.workspace).status === "Ready").length;
                const reviewCount = classifiedWorkspaces.filter((item) => planVisibilityFit(plan, item.workspace).status !== "Ready").length;
                return (
                  <tr key={plan.id}>
                    <td className="px-4 py-3 font-semibold text-slate-900">{plan.name}<div className="mt-1 text-xs font-normal text-slate-500">{plan.status}</div></td>
                    <td className="px-4 py-3 text-slate-700">{money(plan.monthlyPrice)}/mo</td>
                    <td className="px-4 py-3 text-slate-600">{plan.planFamily}</td>
                    <td className="px-4 py-3 text-slate-600">{plan.planVisibility}</td>
                    <td className="px-4 py-3 text-slate-600">{plan.visibleWorkspaceTypes.length > 0 ? plan.visibleWorkspaceTypes.map(dbLabel).join(", ") : "No saved type list"}</td>
                    <td className="px-4 py-3 text-slate-600">{fitCount} classified workspace{fitCount === 1 ? "" : "s"}</td>
                    <td className="px-4 py-3 text-slate-600">{reviewCount} review item{reviewCount === 1 ? "" : "s"}</td>
                    <td className="px-4 py-3 text-slate-600">{plan.bestFor || planMatchesWorkspaceClass(plan, "Dispatcher")}</td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
        <div className="mt-4 grid gap-3 lg:grid-cols-3">
          {workspaceClassDefinitions.filter((definition) => definition.accountClass === "Paid workspace").map((definition) => (
            <div key={definition.key} className="rounded-2xl border border-slate-100 bg-slate-50 p-4">
              <h3 className="font-semibold text-slate-900">{definition.key}</h3>
              <p className="mt-2 text-xs leading-5 text-slate-600">{definition.planVisibilityRule}</p>
              <div className="mt-3 text-xs font-semibold text-slate-700">Plan review: {plans.map((plan) => `${plan.name}: ${planMatchesWorkspaceClass(plan, definition.key)}`).join(" · ")}</div>
            </div>
          ))}
        </div>
      </Section>

      <Section title="Schema review before final controls" subtitle="This surface proves what can be reviewed now and what still needs explicit representation before sign-up, billing, portals, and Super Admin controls become final.">
        <div className="grid gap-3 lg:grid-cols-2">
          <div className="rounded-2xl border border-emerald-100 bg-emerald-50 p-4">
            <h3 className="font-semibold text-slate-900">Represented now</h3>
            <ul className="mt-3 space-y-2 text-sm leading-6 text-emerald-800">
              <li>Organization records as workspaces.</li>
              <li>User roles including workspace admin, dispatcher, accounting, owner-operator, and company driver.</li>
              <li>Subscription plans, feature flags, included users/trucks/phone numbers, add-on prices, Stripe ids, plan family, plan visibility, and saved visible workspace type lists.</li>
              <li>Workspace subscriptions with status, billing provider, Stripe ids, provider sync status, and trial/current period dates.</li>
              <li>Stored workspace type and account class fields for future registration/billing gates.</li>
              <li>Classification coverage summaries and plan visibility readiness warnings based on stored workspace classifications.</li>
              <li>Driver portal linkage through user-to-driver relationship.</li>
              <li>First Super Admin audit event table for future overrides and sensitive admin actions.</li>
              <li>Guarded Super Admin classification workflow and bulk cleanup helper for storing workspace type/account class on existing workspaces.</li>
            </ul>
          </div>
          <div className="rounded-2xl border border-amber-100 bg-amber-50 p-4">
            <h3 className="font-semibold text-slate-900">Still needs future schema/workflow work</h3>
            <ul className="mt-3 space-y-2 text-sm leading-6 text-amber-800">
              <li>Registration-time classification and plan visibility enforcement after Super Admin cleanup has been reviewed.</li>
              <li>Enforcement rules that use plan visibility by workspace type.</li>
              <li>Global configurable trial policy and registration flow state.</li>
              <li>Owned interface and invited portal records for driver/customer/carrier access.</li>
              <li>Broker load distribution limits, email distribution usage, and internal load-board posting access.</li>
              <li>Super Admin override/audit records for billing gates and entitlement exceptions.</li>
            </ul>
          </div>
        </div>
      </Section>
    </div>
  );
}
