"use client";

import { useEffect, useMemo, useState } from "react";
import { apiDelete, apiGet, apiPost, apiPut } from "@/lib/api";
import {
  defaultSubscriptionPlanBilling,
  enabledFeatureCount,
  planLimitSummary,
  stagedSubscriptionPlans,
  subscriptionFeatureKeys,
  subscriptionFeatureLabels,
  type SubscriptionFeatureKey,
  type SubscriptionPlanDraft,
  type SubscriptionPlanFamily,
  type SubscriptionPlanVisibility,
} from "@/src/modules/subscriptions/subscription-entitlements";

const emptyPlan: SubscriptionPlanDraft = {
  id: "new-plan",
  name: "New Plan",
  status: "Draft",
  planFamily: "General",
  planVisibility: "Private",
  visibleWorkspaceTypes: [],
  monthlyPrice: 0,
  includedUsers: 1,
  includedTrucks: 1,
  includedPhoneNumbers: 1,
  extraUserPrice: 0,
  extraTruckPrice: 0,
  extraPhoneNumberPrice: 0,
  billing: defaultSubscriptionPlanBilling(),
  bestFor: "Describe who this plan is for.",
  featureAccess: {
    dispatch: true,
    documents: true,
    billing: true,
    notifications: true,
    businessPhone: false,
    routePlanning: false,
    loadBoard: false,
    reports: false,
    cori: false,
  },
};

const planFamilyOptions: SubscriptionPlanFamily[] = [
  "General",
  "Dispatcher",
  "Company / Fleet",
  "Carrier / Owner-Operator",
  "Freight Broker",
  "Shipper / Customer",
  "Internal",
];

const planVisibilityOptions: SubscriptionPlanVisibility[] = ["Private", "Public", "Invite only", "Internal"];

const workspaceTypeVisibilityOptions = [
  { 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: "INTERNAL_OPERATIONS", label: "Internal Operations" },
  { value: "PLATFORM_MARKETPLACE", label: "Platform Marketplace" },
];

const publicSignupWorkspaceTypes = ["DISPATCHER", "COMPANY_FLEET", "CARRIER_OWNER_OPERATOR", "FREIGHT_BROKER"] as const;

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

type StripePriceReadinessReview = {
  candidate: boolean;
  status: StripePriceReadinessStatus;
  warnings: string[];
  firstFix: string;
  missingProductId: boolean;
  missingMonthlyPriceId: boolean;
  invalidProductId: boolean;
  invalidMonthlyPriceId: boolean;
  syncNeedsReview: boolean;
};

type StripePriceAuditNote = {
  id: string;
  createdAt: string;
  summary: string;
  planId: string;
  planName: string;
  readinessStatus: string;
  note: string;
  firstFix: string;
  warningCount: number;
};

function isPublicSignupWorkspaceType(value: string) {
  return (publicSignupWorkspaceTypes as readonly string[]).includes(value);
}

function hasInternalOnlyVisibleType(value: string) {
  return ["DRIVER_INTERFACE", "INTERNAL_OPERATIONS", "PLATFORM_MARKETPLACE"].includes(value);
}

function planIsCandidateCheckoutPlan(plan: SubscriptionPlanDraft) {
  if (plan.status === "Retired") return false;
  if (!["Public", "Invite only"].includes(plan.planVisibility)) return false;
  if (plan.planFamily === "Internal") return false;
  if (!plan.visibleWorkspaceTypes.length) return false;
  if (plan.visibleWorkspaceTypes.some(hasInternalOnlyVisibleType)) return false;
  return plan.visibleWorkspaceTypes.some(isPublicSignupWorkspaceType);
}

function stripeIdStartsWith(value: string | undefined, prefix: string) {
  const clean = String(value ?? "").trim();
  return clean.length > 0 && clean.startsWith(prefix);
}

function stripePriceReadiness(plan: SubscriptionPlanDraft): StripePriceReadinessReview {
  const billing = plan.billing ?? defaultSubscriptionPlanBilling();
  const candidate = planIsCandidateCheckoutPlan(plan);
  const productId = String(billing.stripeProductId ?? "").trim();
  const monthlyPriceId = String(billing.stripeMonthlyPriceId ?? "").trim();
  const missingProductId = productId.length === 0;
  const missingMonthlyPriceId = monthlyPriceId.length === 0;
  const invalidProductId = productId.length > 0 && !stripeIdStartsWith(productId, "prod_");
  const invalidMonthlyPriceId = monthlyPriceId.length > 0 && !stripeIdStartsWith(monthlyPriceId, "price_");
  const syncNeedsReview = !["Ready", "Synced"].includes(billing.syncStatus);

  if (!candidate) {
    return {
      candidate,
      status: "Locked",
      warnings: ["This plan is not currently staged as a public or invite-only signup candidate."],
      firstFix: "Set the correct plan family, visibility, and workspace type list before preparing Stripe price IDs.",
      missingProductId,
      missingMonthlyPriceId,
      invalidProductId,
      invalidMonthlyPriceId,
      syncNeedsReview,
    };
  }

  const warnings: string[] = [];
  if (billing.provider !== "Stripe") warnings.push("Billing provider is not set to Stripe.");
  if (billing.mode === "Not connected" || billing.mode === "Manual") warnings.push("Billing mode should be Test for locked checkout preparation.");
  if (billing.mode === "Live") warnings.push("Live mode is saved before checkout activation. Review carefully before any later payment build.");
  if (missingProductId) warnings.push("Stripe product ID is missing.");
  if (invalidProductId) warnings.push("Stripe product ID should start with prod_.");
  if (missingMonthlyPriceId) warnings.push("Monthly Stripe price ID is missing.");
  if (invalidMonthlyPriceId) warnings.push("Monthly Stripe price ID should start with price_.");
  if (Number(plan.monthlyPrice) <= 0) warnings.push("Monthly plan amount is $0. Confirm this is intended before checkout preparation continues.");
  if (billing.syncStatus === "Error") warnings.push("Provider sync status is Error.");
  if (syncNeedsReview && billing.syncStatus !== "Error") warnings.push("Provider sync status should be Ready or Synced after IDs are verified.");

  const firstFix = billing.provider !== "Stripe"
    ? "Set billing provider to Stripe."
    : billing.mode === "Not connected" || billing.mode === "Manual"
      ? "Set billing mode to Test for locked checkout preparation."
      : missingProductId
        ? "Paste the Stripe product ID for this plan."
        : invalidProductId
          ? "Correct the Stripe product ID so it starts with prod_."
          : missingMonthlyPriceId
            ? "Paste the monthly Stripe price ID for this plan."
            : invalidMonthlyPriceId
              ? "Correct the monthly Stripe price ID so it starts with price_."
              : billing.syncStatus === "Error"
                ? "Resolve the provider sync error."
                : syncNeedsReview
                  ? "Mark the provider sync status Ready after the IDs are verified."
                  : Number(plan.monthlyPrice) <= 0
                    ? "Confirm the $0 monthly amount is intentional."
                    : "Stripe price fields are ready for locked checkout-route review. Checkout remains off.";

  return {
    candidate,
    status: billing.syncStatus === "Error" ? "Blocked" : warnings.length ? "Check" : "Ready",
    warnings,
    firstFix,
    missingProductId,
    missingMonthlyPriceId,
    invalidProductId,
    invalidMonthlyPriceId,
    syncNeedsReview,
  };
}

function priceReadinessBadge(status: StripePriceReadinessStatus) {
  if (status === "Ready") return "bg-emerald-100 text-emerald-700";
  if (status === "Blocked") return "bg-rose-100 text-rose-700";
  if (status === "Locked") return "bg-slate-100 text-slate-700";
  return "bg-amber-100 text-amber-700";
}

function priceReadinessSortValue(status: StripePriceReadinessStatus) {
  if (status === "Blocked") return 0;
  if (status === "Check") return 1;
  if (status === "Locked") return 2;
  return 3;
}

function csvCell(value: unknown) {
  const normalized = value instanceof Date ? value.toISOString() : String(value ?? "");
  return '"' + normalized.replace(/"/g, '""') + '"';
}

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

function maskStripeId(value: string | undefined) {
  const clean = String(value ?? "").trim();
  if (!clean) return "";
  if (clean.length <= 12) return clean;
  return `${clean.slice(0, 8)}...${clean.slice(-4)}`;
}

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

const recommendedPlanVisibilityByFamily: Record<SubscriptionPlanFamily, { visibility: SubscriptionPlanVisibility; visibleWorkspaceTypes: string[]; note: string }> = {
  General: {
    visibility: "Private",
    visibleWorkspaceTypes: ["DISPATCHER", "COMPANY_FLEET", "CARRIER_OWNER_OPERATOR"],
    note: "General plans can remain private while Super Admin decides whether they are safe for several paid workspace types.",
  },
  Dispatcher: {
    visibility: "Private",
    visibleWorkspaceTypes: ["DISPATCHER"],
    note: "Dispatcher plans should only be staged for dispatcher workspaces until public registration gates are approved.",
  },
  "Company / Fleet": {
    visibility: "Private",
    visibleWorkspaceTypes: ["COMPANY_FLEET"],
    note: "Fleet plans should stay limited to company/fleet workspaces unless Super Admin intentionally shares the plan.",
  },
  "Carrier / Owner-Operator": {
    visibility: "Private",
    visibleWorkspaceTypes: ["CARRIER_OWNER_OPERATOR"],
    note: "Carrier plans should stay limited to independent carrier or owner-operator workspaces.",
  },
  "Freight Broker": {
    visibility: "Private",
    visibleWorkspaceTypes: ["FREIGHT_BROKER"],
    note: "Broker plans should stay private until load distribution and load-board usage controls are ready.",
  },
  "Shipper / Customer": {
    visibility: "Private",
    visibleWorkspaceTypes: ["SHIPPER_CUSTOMER"],
    note: "Shipper plans should remain private until the large-shipper product is intentionally activated.",
  },
  Internal: {
    visibility: "Internal",
    visibleWorkspaceTypes: ["INTERNAL_OPERATIONS", "PLATFORM_MARKETPLACE"],
    note: "Internal plans should be hidden from public sales and assigned only by Super Admin.",
  },
};

type PlanVisibilityReview = {
  status: "Ready" | "Check";
  warnings: string[];
  recommended: { visibility: SubscriptionPlanVisibility; visibleWorkspaceTypes: string[]; note: string };
};

function sameStringSet(first: string[], second: string[]) {
  if (first.length !== second.length) return false;
  const secondSet = new Set(second);
  return first.every((item) => secondSet.has(item));
}

function visibleTypeLabel(value: string) {
  return workspaceTypeVisibilityOptions.find((item) => item.value === value)?.label ?? value.toLowerCase().split("_").map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join(" ");
}

function visibilityReview(plan: SubscriptionPlanDraft): PlanVisibilityReview {
  const recommended = recommendedPlanVisibilityByFamily[plan.planFamily] ?? recommendedPlanVisibilityByFamily.General;
  const warnings: string[] = [];

  if (plan.visibleWorkspaceTypes.length === 0) warnings.push("No visible workspace type list is saved yet.");
  if (!sameStringSet(plan.visibleWorkspaceTypes, recommended.visibleWorkspaceTypes)) warnings.push(`Saved visible workspace types differ from the ${plan.planFamily} recommendation.`);
  if (plan.planFamily === "Internal" && plan.planVisibility !== "Internal") warnings.push("Internal plans should normally use Internal visibility.");
  if (plan.planFamily !== "Internal" && plan.planVisibility === "Internal") warnings.push("Customer plan family is marked Internal. Review before plan selection uses it.");
  if (plan.planVisibility === "Public") warnings.push("Public visibility is staged only. Registration and Stripe checkout are not connected to this value yet.");
  if (plan.visibleWorkspaceTypes.includes("PLATFORM_MARKETPLACE") && plan.planFamily !== "Internal") warnings.push("Platform Marketplace should stay behind internal policy and future access gates.");
  if (plan.planFamily === "Freight Broker" && plan.featureAccess.loadBoard) warnings.push("Broker load-board access still needs usage limits, audit, and Super Admin policy before enforcement.");

  return { status: warnings.length > 0 ? "Check" : "Ready", warnings, recommended };
}


const recommendedEntitlementDefaultsByFamily: Record<SubscriptionPlanFamily, {
  bundle: string;
  includedUsers: number;
  includedTrucks: number;
  includedPhoneNumbers: number;
  extraUserPrice: number;
  extraTruckPrice: number;
  extraPhoneNumberPrice: number;
  enabledFeatures: SubscriptionFeatureKey[];
  note: string;
}> = {
  General: {
    bundle: "Balanced operations",
    includedUsers: 5,
    includedTrucks: 15,
    includedPhoneNumbers: 2,
    extraUserPrice: 15,
    extraTruckPrice: 24,
    extraPhoneNumberPrice: 12,
    enabledFeatures: ["dispatch", "documents", "billing", "notifications", "businessPhone", "routePlanning", "reports", "cori"],
    note: "Balanced plan for mixed customer workspace types while registration and billing gates stay review-only.",
  },
  Dispatcher: {
    bundle: "Dispatcher operations",
    includedUsers: 2,
    includedTrucks: 3,
    includedPhoneNumbers: 1,
    extraUserPrice: 19,
    extraTruckPrice: 29,
    extraPhoneNumberPrice: 15,
    enabledFeatures: ["dispatch", "documents", "billing", "notifications", "businessPhone", "cori"],
    note: "Good starting bundle for small dispatch teams.",
  },
  "Company / Fleet": {
    bundle: "Fleet command center",
    includedUsers: 12,
    includedTrucks: 50,
    includedPhoneNumbers: 4,
    extraUserPrice: 12,
    extraTruckPrice: 19,
    extraPhoneNumberPrice: 10,
    enabledFeatures: ["dispatch", "documents", "billing", "notifications", "businessPhone", "routePlanning", "reports", "cori"],
    note: "Larger fleet bundle with route planning, reporting, phone, and CORI coverage.",
  },
  "Carrier / Owner-Operator": {
    bundle: "Small carrier operations",
    includedUsers: 1,
    includedTrucks: 1,
    includedPhoneNumbers: 1,
    extraUserPrice: 15,
    extraTruckPrice: 20,
    extraPhoneNumberPrice: 10,
    enabledFeatures: ["dispatch", "documents", "billing", "notifications", "routePlanning", "cori"],
    note: "Simple carrier bundle for one-truck or small-carrier workspaces.",
  },
  "Freight Broker": {
    bundle: "Broker/customer desk",
    includedUsers: 3,
    includedTrucks: 0,
    includedPhoneNumbers: 1,
    extraUserPrice: 20,
    extraTruckPrice: 0,
    extraPhoneNumberPrice: 12,
    enabledFeatures: ["documents", "billing", "notifications", "businessPhone", "reports", "cori"],
    note: "Broker desk bundle. Broker distribution and load-board access remain locked behind future Super Admin policy.",
  },
  "Shipper / Customer": {
    bundle: "Customer portal preparation",
    includedUsers: 2,
    includedTrucks: 0,
    includedPhoneNumbers: 0,
    extraUserPrice: 10,
    extraTruckPrice: 0,
    extraPhoneNumberPrice: 0,
    enabledFeatures: ["documents", "notifications", "reports"],
    note: "Portal-oriented bundle that stays private until owned portal rules are ready.",
  },
  Internal: {
    bundle: "Internal platform layer",
    includedUsers: 0,
    includedTrucks: 0,
    includedPhoneNumbers: 0,
    extraUserPrice: 0,
    extraTruckPrice: 0,
    extraPhoneNumberPrice: 0,
    enabledFeatures: ["reports", "cori"],
    note: "Internal plans stay hidden from customer signup and billing enforcement.",
  },
};

type EntitlementLimitReview = { status: "Ready" | "Check"; warnings: string[]; firstFix: string };

function entitlementLimitReview(plan: SubscriptionPlanDraft): EntitlementLimitReview {
  const recommended = recommendedEntitlementDefaultsByFamily[plan.planFamily] ?? recommendedEntitlementDefaultsByFamily.General;
  const warnings: string[] = [];
  if (plan.planFamily !== "Internal" && Number(plan.includedUsers) < 1) warnings.push("Customer-facing plans should include at least one user/seat.");
  if (!["Freight Broker", "Shipper / Customer", "Internal"].includes(plan.planFamily) && Number(plan.includedTrucks) < 1) warnings.push("This plan family usually needs at least one included truck.");
  if (plan.featureAccess.businessPhone && Number(plan.includedPhoneNumbers) < 1) warnings.push("Business phone is included but no business phone number is included.");
  if (plan.featureAccess.routePlanning && Number(plan.includedTrucks) < 1) warnings.push("Route planning is included but no truck is included.");
  if (Number(plan.extraUserPrice) <= 0 && Number(plan.includedUsers) > recommended.includedUsers && plan.planFamily !== "Internal") warnings.push("Extra user price is $0 even though this plan includes more users than the family default.");
  if (Number(plan.extraTruckPrice) <= 0 && Number(plan.includedTrucks) > recommended.includedTrucks && !["Freight Broker", "Shipper / Customer", "Internal"].includes(plan.planFamily)) warnings.push("Extra truck price is $0 even though this plan includes more trucks than the family default.");
  if (Number(plan.extraPhoneNumberPrice) <= 0 && Number(plan.includedPhoneNumbers) > recommended.includedPhoneNumbers && plan.planFamily !== "Internal") warnings.push("Extra phone number price is $0 even though this plan includes more phone numbers than the family default.");
  if (plan.featureAccess.loadBoard && plan.planFamily === "Freight Broker") warnings.push("Broker load-board access still needs Super Admin policy before enforcement.");
  const firstFix = warnings[0] ?? `${plan.name} limits and add-on prices are ready for the current ${recommended.bundle} review.`;
  return { status: warnings.length ? "Check" : "Ready", warnings, firstFix };
}

function featureAccessFromRecommendation(plan: SubscriptionPlanDraft) {
  const recommended = recommendedEntitlementDefaultsByFamily[plan.planFamily] ?? recommendedEntitlementDefaultsByFamily.General;
  return subscriptionFeatureKeys.reduce((next, key) => {
    next[key] = recommended.enabledFeatures.includes(key);
    return next;
  }, {} as Record<SubscriptionFeatureKey, boolean>);
}

function reviewBadge(status: "Ready" | "Check") {
  return status === "Ready" ? "bg-emerald-100 text-emerald-700" : "bg-amber-100 text-amber-700";
}

function statusClasses(status: SubscriptionPlanDraft["status"]) {
  if (status === "Live") return "bg-emerald-100 text-emerald-700";
  if (status === "Retired") return "bg-slate-100 text-slate-600";
  return "bg-amber-100 text-amber-700";
}

function toPlanId(name: string) {
  return name.toLowerCase().trim().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "") || `plan-${Date.now()}`;
}

export function AdminSubscriptionPlansClient() {
  const [plans, setPlans] = useState<SubscriptionPlanDraft[]>(stagedSubscriptionPlans);
  const [selectedPlanId, setSelectedPlanId] = useState(stagedSubscriptionPlans[0]?.id ?? emptyPlan.id);
  const [draft, setDraft] = useState<SubscriptionPlanDraft>(stagedSubscriptionPlans[0] ?? emptyPlan);
  const [message, setMessage] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);
  const [priceAuditNotes, setPriceAuditNotes] = useState<StripePriceAuditNote[]>([]);
  const [priceAuditNoteDraft, setPriceAuditNoteDraft] = useState("");
  const [priceAuditSaving, setPriceAuditSaving] = useState(false);

  const selectedPlan = useMemo(() => plans.find((plan) => plan.id === selectedPlanId) ?? plans[0] ?? draft, [plans, selectedPlanId, draft]);
  const livePlans = plans.filter((plan) => plan.status === "Live").length;
  const draftPlans = plans.filter((plan) => plan.status === "Draft").length;
  const planVisibilityReviews = useMemo(() => plans.map((plan) => ({ plan, review: visibilityReview(plan) })), [plans]);
  const planVisibilityChecks = planVisibilityReviews.filter((item) => item.review.status === "Check").length;
  const missingVisibleTypes = planVisibilityReviews.filter((item) => item.plan.visibleWorkspaceTypes.length === 0).length;
  const publicStagedPlans = plans.filter((plan) => plan.planVisibility === "Public").length;
  const draftVisibilityReview = useMemo(() => visibilityReview(draft), [draft]);
  const planEntitlementLimitReviews = useMemo(() => plans.map((plan) => ({ plan, review: entitlementLimitReview(plan) })), [plans]);
  const planEntitlementLimitChecks = planEntitlementLimitReviews.filter((item) => item.review.status === "Check").length;
  const planEntitlementAddOnReady = planEntitlementLimitReviews.filter((item) => Number(item.plan.extraUserPrice) > 0 && (Number(item.plan.extraTruckPrice) > 0 || ["Freight Broker", "Shipper / Customer", "Internal"].includes(item.plan.planFamily)) && (Number(item.plan.extraPhoneNumberPrice) > 0 || Number(item.plan.includedPhoneNumbers) === 0)).length;
  const draftEntitlementLimitReview = useMemo(() => entitlementLimitReview(draft), [draft]);
  const draftEntitlementRecommendation = recommendedEntitlementDefaultsByFamily[draft.planFamily] ?? recommendedEntitlementDefaultsByFamily.General;
  const candidatePriceReadinessReviews = useMemo(() => plans
    .filter(planIsCandidateCheckoutPlan)
    .map((plan) => ({ plan, review: stripePriceReadiness(plan) })), [plans]);
  const candidatePriceReadinessChecks = candidatePriceReadinessReviews.filter((item) => item.review.status === "Check").length;
  const candidatePriceReadinessBlocked = candidatePriceReadinessReviews.filter((item) => item.review.status === "Blocked").length;
  const candidatePriceReadinessReady = candidatePriceReadinessReviews.filter((item) => item.review.status === "Ready").length;
  const candidateMissingProductIds = candidatePriceReadinessReviews.filter((item) => item.review.missingProductId).length;
  const candidateMissingMonthlyPriceIds = candidatePriceReadinessReviews.filter((item) => item.review.missingMonthlyPriceId).length;
  const candidateInvalidStripeIds = candidatePriceReadinessReviews.filter((item) => item.review.invalidProductId || item.review.invalidMonthlyPriceId).length;
  const draftStripePriceReview = useMemo(() => stripePriceReadiness(draft), [draft]);
  const selectedPlanPriceAuditNotes = useMemo(() => priceAuditNotes.filter((note) => note.planId === draft.id).slice(0, 3), [priceAuditNotes, draft.id]);

  async function loadPlans() {
    try {
      setLoading(true);
      setMessage(null);
      const data = await apiGet<{ plans: SubscriptionPlanDraft[] }>("/api/subscriptions");
      const nextPlans = data.plans.length ? data.plans : stagedSubscriptionPlans;
      setPlans(nextPlans);
      const nextSelected = nextPlans.find((plan) => plan.id === selectedPlanId) ?? nextPlans[0] ?? emptyPlan;
      setSelectedPlanId(nextSelected.id);
      setDraft(nextSelected);
    } catch (error: any) {
      setMessage(error?.message ?? "Failed to load subscription plans");
    } finally {
      setLoading(false);
    }
  }

  async function loadPriceAuditNotes() {
    try {
      const data = await apiGet<{ auditNotes: StripePriceAuditNote[] }>("/api/admin/stripe-price-readiness/audit-note");
      setPriceAuditNotes(data.auditNotes ?? []);
    } catch {
      setPriceAuditNotes([]);
    }
  }

  useEffect(() => { void loadPlans(); void loadPriceAuditNotes(); }, []);

  function selectPlan(plan: SubscriptionPlanDraft) {
    setSelectedPlanId(plan.id);
    setDraft(plan);
  }

  function updateNumber(field: keyof Pick<SubscriptionPlanDraft, "monthlyPrice" | "includedUsers" | "includedTrucks" | "includedPhoneNumbers" | "extraUserPrice" | "extraTruckPrice" | "extraPhoneNumberPrice">, value: string) {
    setDraft((current) => ({ ...current, [field]: Number(value) || 0 }));
  }

  function updateBilling(field: keyof SubscriptionPlanDraft["billing"], value: string) {
    setDraft((current) => ({ ...current, billing: { ...(current.billing ?? defaultSubscriptionPlanBilling()), [field]: value } as SubscriptionPlanDraft["billing"] }));
  }

  function toggleVisibleWorkspaceType(value: string) {
    setDraft((current) => {
      const exists = current.visibleWorkspaceTypes.includes(value);
      const nextTypes = exists
        ? current.visibleWorkspaceTypes.filter((item) => item !== value)
        : [...current.visibleWorkspaceTypes, value];
      return { ...current, visibleWorkspaceTypes: nextTypes };
    });
  }

  function applyRecommendedVisibility() {
    const recommended = recommendedPlanVisibilityByFamily[draft.planFamily] ?? recommendedPlanVisibilityByFamily.General;
    setDraft((current) => ({
      ...current,
      planVisibility: recommended.visibility,
      visibleWorkspaceTypes: recommended.visibleWorkspaceTypes,
    }));
    setMessage("Recommended plan visibility applied to the draft. Save the plan to keep it.");
  }

  function applyRecommendedEntitlementDefaults() {
    const recommended = recommendedEntitlementDefaultsByFamily[draft.planFamily] ?? recommendedEntitlementDefaultsByFamily.General;
    setDraft((current) => ({
      ...current,
      includedUsers: recommended.includedUsers,
      includedTrucks: recommended.includedTrucks,
      includedPhoneNumbers: recommended.includedPhoneNumbers,
      extraUserPrice: recommended.extraUserPrice,
      extraTruckPrice: recommended.extraTruckPrice,
      extraPhoneNumberPrice: recommended.extraPhoneNumberPrice,
      featureAccess: featureAccessFromRecommendation(current),
    }));
    setMessage(`Recommended entitlement defaults applied for the ${recommended.bundle} bundle. Save the plan to keep it.`);
  }

  function applyStripeTestReadinessDefaults() {
    setDraft((current) => ({
      ...current,
      billing: {
        ...(current.billing ?? defaultSubscriptionPlanBilling()),
        provider: "Stripe",
        mode: "Test",
        syncStatus: "Needs review",
        notes: (current.billing?.notes ?? "").trim() || "Prepared for locked Stripe checkout review. No checkout activation.",
      },
    }));
    setMessage("Stripe test readiness defaults applied to the draft. Add the real Stripe IDs, then save the plan.");
  }

  function markStripeIdsVerifiedForReview() {
    const productIdReady = stripeIdStartsWith(draft.billing?.stripeProductId, "prod_");
    const monthlyPriceReady = stripeIdStartsWith(draft.billing?.stripeMonthlyPriceId, "price_");
    if (!draftStripePriceReview.candidate) {
      setMessage("This plan is not staged as a public or invite-only signup candidate yet. Set visibility and workspace types first.");
      return;
    }
    if (!productIdReady || !monthlyPriceReady) {
      setMessage("Add a product ID starting with prod_ and a monthly price ID starting with price_ before marking the plan ready.");
      return;
    }
    setDraft((current) => ({
      ...current,
      billing: {
        ...(current.billing ?? defaultSubscriptionPlanBilling()),
        provider: "Stripe",
        mode: current.billing?.mode === "Live" ? "Live" : "Test",
        syncStatus: "Ready",
      },
    }));
    setMessage("Stripe IDs marked Ready in the draft. Save the plan to keep the review state.");
  }

  function suggestedStripePriceAuditNote() {
    const warningText = draftStripePriceReview.warnings.length ? ` Warnings: ${draftStripePriceReview.warnings.join(" ")}` : " No warnings are currently listed.";
    return `${draft.name}: ${draftStripePriceReview.status}. ${draftStripePriceReview.firstFix}${warningText}`;
  }

  function fillSuggestedStripePriceAuditNote() {
    setPriceAuditNoteDraft(suggestedStripePriceAuditNote());
  }

  async function saveStripePriceAuditNote() {
    try {
      setPriceAuditSaving(true);
      setMessage(null);
      const note = priceAuditNoteDraft.trim() || suggestedStripePriceAuditNote();
      const data = await apiPost<{ auditNote: StripePriceAuditNote }>("/api/admin/stripe-price-readiness/audit-note", { planId: draft.id, note });
      setPriceAuditNotes((current) => [data.auditNote, ...current.filter((item) => item.id !== data.auditNote.id)].slice(0, 10));
      setPriceAuditNoteDraft("");
      setMessage("Stripe price readiness audit note saved. Checkout is still locked.");
    } catch (error: any) {
      setMessage(error?.message ?? "Failed to save Stripe price readiness audit note");
    } finally {
      setPriceAuditSaving(false);
    }
  }

  function exportStripePriceReadinessCsv() {
    downloadCsv(
      "dispatchspot-stripe-price-readiness-" + new Date().toISOString().slice(0, 10) + ".csv",
      ["Plan", "Family", "Visibility", "Workspace types", "Monthly price", "Readiness", "Candidate", "Billing provider", "Billing mode", "Sync status", "Product ID", "Monthly price ID", "Warnings", "First fix"],
      candidatePriceReadinessReviews.map(({ plan, review }) => [
        plan.name,
        plan.planFamily,
        plan.planVisibility,
        plan.visibleWorkspaceTypes.map(visibleTypeLabel).join(", "),
        `$${plan.monthlyPrice}/month`,
        review.status,
        review.candidate ? "Yes" : "No",
        plan.billing?.provider ?? "None",
        plan.billing?.mode ?? "Not connected",
        plan.billing?.syncStatus ?? "Not ready",
        review.missingProductId ? "Missing" : review.invalidProductId ? "Review format" : maskStripeId(plan.billing?.stripeProductId),
        review.missingMonthlyPriceId ? "Missing" : review.invalidMonthlyPriceId ? "Review format" : maskStripeId(plan.billing?.stripeMonthlyPriceId),
        review.warnings.join(" "),
        review.firstFix,
      ]),
    );
  }

  function exportStripePriceIssuesCsv() {
    const rows = candidatePriceReadinessReviews.filter(({ review }) => review.status !== "Ready");
    downloadCsv(
      "dispatchspot-stripe-price-readiness-issues-" + new Date().toISOString().slice(0, 10) + ".csv",
      ["Plan", "Readiness", "Issue count", "First fix", "Warnings"],
      rows.map(({ plan, review }) => [plan.name, review.status, review.warnings.length, review.firstFix, review.warnings.join(" ")]),
    );
  }

  function toggleFeature(feature: SubscriptionFeatureKey) {
    setDraft((current) => ({
      ...current,
      featureAccess: { ...current.featureAccess, [feature]: !current.featureAccess[feature] },
    }));
  }

  async function saveDraft() {
    try {
      setMessage(null);
      const isNew = draft.id.startsWith("new-plan");
      const payload = { plan: { ...draft, id: isNew ? toPlanId(draft.name) : draft.id } };
      const data = isNew
        ? await apiPost<{ plan: SubscriptionPlanDraft }>("/api/subscriptions", payload)
        : await apiPut<{ plan: SubscriptionPlanDraft }>(`/api/subscriptions/${draft.id}`, payload);
      setPlans((current) => {
        const exists = current.some((plan) => plan.id === data.plan.id);
        return exists ? current.map((plan) => (plan.id === data.plan.id ? data.plan : plan)) : [...current, data.plan];
      });
      setSelectedPlanId(data.plan.id);
      setDraft(data.plan);
      setMessage("Plan saved to database.");
    } catch (error: any) {
      setMessage(error?.message ?? "Failed to save plan");
    }
  }

  function createNewPlan() {
    const next = { ...emptyPlan, id: `new-plan-${Date.now()}`, name: "New Plan" };
    setSelectedPlanId(next.id);
    setDraft(next);
  }

  function duplicatePlan() {
    const next = { ...selectedPlan, id: `${selectedPlan.id}-copy-${Date.now()}`, name: `${selectedPlan.name} Copy`, status: "Draft" as const };
    setPlans((current) => [...current, next]);
    setSelectedPlanId(next.id);
    setDraft(next);
  }

  async function deletePlan(planId: string) {
    try {
      setMessage(null);
      if (!planId.startsWith("new-plan")) await apiDelete(`/api/subscriptions/${planId}`);
      const nextPlans = plans.filter((plan) => plan.id !== planId);
      setPlans(nextPlans);
      const next = nextPlans[0] ?? emptyPlan;
      setSelectedPlanId(next.id);
      setDraft(next);
      setMessage("Plan removed.");
    } catch (error: any) {
      setMessage(error?.message ?? "Failed to delete plan");
    }
  }

  return (
    <div className="space-y-6">
      <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 plan control</div>
            <h2 className="mt-1 text-lg font-semibold text-slate-900">Subscription plan foundation</h2>
            <p className="mt-1 max-w-3xl text-sm leading-6 text-slate-600">
              Create and maintain the saved plans, limits, and feature access rules that will govern every workspace. Live billing can connect to this persisted model later.
            </p>
          </div>
          <div className="grid gap-2 text-sm sm:grid-cols-3 lg:min-w-[360px]">
            <div className="rounded-xl border border-blue-100 bg-white p-3">
              <div className="text-xs text-slate-500">Plans</div>
              <div className="mt-1 text-xl font-semibold text-slate-900">{plans.length}</div>
            </div>
            <div className="rounded-xl border border-blue-100 bg-white p-3">
              <div className="text-xs text-slate-500">Live</div>
              <div className="mt-1 text-xl font-semibold text-slate-900">{livePlans}</div>
            </div>
            <div className="rounded-xl border border-blue-100 bg-white p-3">
              <div className="text-xs text-slate-500">Draft</div>
              <div className="mt-1 text-xl font-semibold text-slate-900">{draftPlans}</div>
            </div>
          </div>
        </div>
      </section>

      <section className="rounded-2xl border border-amber-100 bg-amber-50 p-6 shadow-sm">
        <div className="flex flex-col gap-4 xl:flex-row xl:items-start xl:justify-between">
          <div>
            <div className="text-xs font-semibold uppercase tracking-[0.18em] text-amber-700">Plan-family visibility cleanup</div>
            <h2 className="mt-1 text-lg font-semibold text-slate-900">Review plan family, sales visibility, and allowed workspace types</h2>
            <p className="mt-1 max-w-4xl text-sm leading-6 text-amber-800">
              These controls prepare registration plan selection by cleaning up saved plan metadata first. They do not change signup, Stripe checkout, billing gates, broker load distribution, owned portal rules, or internal load-board access.
            </p>
          </div>
          <div className="grid gap-2 text-sm sm:grid-cols-4 xl:min-w-[520px]">
            <div className="rounded-xl border border-amber-100 bg-white p-3"><div className="text-xs text-slate-500">Visibility checks</div><div className="mt-1 text-xl font-semibold text-slate-900">{planVisibilityChecks}</div></div>
            <div className="rounded-xl border border-amber-100 bg-white p-3"><div className="text-xs text-slate-500">Missing type list</div><div className="mt-1 text-xl font-semibold text-slate-900">{missingVisibleTypes}</div></div>
            <div className="rounded-xl border border-amber-100 bg-white p-3"><div className="text-xs text-slate-500">Public staged</div><div className="mt-1 text-xl font-semibold text-slate-900">{publicStagedPlans}</div></div>
            <div className="rounded-xl border border-amber-100 bg-white p-3"><div className="text-xs text-slate-500">Ready</div><div className="mt-1 text-xl font-semibold text-slate-900">{Math.max(plans.length - planVisibilityChecks, 0)}</div></div>
          </div>
        </div>
        <div className="mt-5 grid gap-3 lg:grid-cols-2 xl:grid-cols-3">
          {planVisibilityReviews.slice().sort((a, b) => Number(b.review.status === "Check") - Number(a.review.status === "Check")).slice(0, 6).map(({ plan, review }) => (
            <button type="button" key={plan.id} onClick={() => selectPlan(plan)} className="rounded-2xl border border-amber-100 bg-white p-4 text-left shadow-sm transition hover:bg-amber-50/50">
              <div className="flex items-start justify-between gap-3">
                <div>
                  <div className="font-semibold text-slate-900">{plan.name}</div>
                  <div className="mt-1 text-xs text-slate-500">{plan.planFamily} · {plan.planVisibility}</div>
                </div>
                <span className={`rounded-full px-2 py-0.5 text-[10px] font-semibold ${reviewBadge(review.status)}`}>{review.status}</span>
              </div>
              <div className="mt-3 text-xs leading-5 text-slate-600">Visible to: {plan.visibleWorkspaceTypes.length ? plan.visibleWorkspaceTypes.map(visibleTypeLabel).join(", ") : "No saved type list"}</div>
              {review.warnings[0] ? <div className="mt-2 text-xs leading-5 text-amber-800">{review.warnings[0]}</div> : <div className="mt-2 text-xs leading-5 text-emerald-700">Family visibility is aligned with the current recommendation.</div>}
            </button>
          ))}
        </div>
      </section>

      <section className="rounded-2xl border border-cyan-100 bg-cyan-50 p-6 shadow-sm">
        <div className="flex flex-col gap-4 xl:flex-row xl:items-start xl:justify-between">
          <div>
            <div className="text-xs font-semibold uppercase tracking-[0.18em] text-cyan-700">Candidate-plan Stripe price readiness</div>
            <h2 className="mt-1 text-lg font-semibold text-slate-900">Clean up Stripe product and price IDs before checkout can be activated</h2>
            <p className="mt-1 max-w-4xl text-sm leading-6 text-cyan-900">
              These Super Admin controls review only the plans already staged for public or invite-only signup. They help prepare Stripe product and monthly price IDs while checkout sessions, card collection, billing gates, broker distribution, portal rules, and internal load-board access remain off.
            </p>
          </div>
          <div className="grid gap-2 text-sm sm:grid-cols-3 xl:min-w-[640px]">
            <div className="rounded-xl border border-cyan-100 bg-white p-3"><div className="text-xs text-slate-500">Candidate plans</div><div className="mt-1 text-xl font-semibold text-slate-900">{candidatePriceReadinessReviews.length}</div></div>
            <div className="rounded-xl border border-cyan-100 bg-white p-3"><div className="text-xs text-slate-500">Stripe-ready</div><div className="mt-1 text-xl font-semibold text-slate-900">{candidatePriceReadinessReady}</div></div>
            <div className="rounded-xl border border-cyan-100 bg-white p-3"><div className="text-xs text-slate-500">Need review</div><div className="mt-1 text-xl font-semibold text-slate-900">{candidatePriceReadinessChecks}</div></div>
            <div className="rounded-xl border border-cyan-100 bg-white p-3"><div className="text-xs text-slate-500">Blocked</div><div className="mt-1 text-xl font-semibold text-slate-900">{candidatePriceReadinessBlocked}</div></div>
            <div className="rounded-xl border border-cyan-100 bg-white p-3"><div className="text-xs text-slate-500">Missing product IDs</div><div className="mt-1 text-xl font-semibold text-slate-900">{candidateMissingProductIds}</div></div>
            <div className="rounded-xl border border-cyan-100 bg-white p-3"><div className="text-xs text-slate-500">Missing price IDs</div><div className="mt-1 text-xl font-semibold text-slate-900">{candidateMissingMonthlyPriceIds}</div></div>
          </div>
        </div>

        <div className="mt-5 grid gap-3 lg:grid-cols-2 xl:grid-cols-3">
          {candidatePriceReadinessReviews.length ? candidatePriceReadinessReviews
            .slice()
            .sort((a, b) => priceReadinessSortValue(a.review.status) - priceReadinessSortValue(b.review.status))
            .slice(0, 6)
            .map(({ plan, review }) => (
              <button type="button" key={plan.id} onClick={() => selectPlan(plan)} className="rounded-2xl border border-cyan-100 bg-white p-4 text-left shadow-sm transition hover:bg-cyan-50/60">
                <div className="flex items-start justify-between gap-3">
                  <div>
                    <div className="font-semibold text-slate-900">{plan.name}</div>
                    <div className="mt-1 text-xs text-slate-500">{plan.planFamily} · {plan.planVisibility} · ${plan.monthlyPrice}/month</div>
                  </div>
                  <span className={`rounded-full px-2 py-0.5 text-[10px] font-semibold ${priceReadinessBadge(review.status)}`}>{review.status}</span>
                </div>
                <div className="mt-3 grid gap-2 text-xs sm:grid-cols-2">
                  <div className="rounded-lg border bg-slate-50 px-2 py-1 text-slate-600">Product: {review.missingProductId ? "Missing" : review.invalidProductId ? "Review format" : "Set"}</div>
                  <div className="rounded-lg border bg-slate-50 px-2 py-1 text-slate-600">Monthly price: {review.missingMonthlyPriceId ? "Missing" : review.invalidMonthlyPriceId ? "Review format" : "Set"}</div>
                </div>
                <div className="mt-3 text-xs leading-5 text-cyan-900">{review.firstFix}</div>
              </button>
            )) : (
              <div className="rounded-2xl border border-cyan-100 bg-white p-4 text-sm leading-6 text-slate-600 xl:col-span-3">
                No public or invite-only signup candidate plans are staged yet. Use the plan-family visibility cleanup controls first, then return here to prepare Stripe product and price IDs.
              </div>
            )}
        </div>
        {candidateInvalidStripeIds ? <div className="mt-4 rounded-xl border border-amber-100 bg-white p-3 text-sm leading-6 text-amber-800">{candidateInvalidStripeIds} candidate plan{candidateInvalidStripeIds === 1 ? "" : "s"} contain Stripe IDs that need format review before future checkout activation.</div> : null}
        <div className="mt-4 rounded-xl border border-cyan-100 bg-white p-3 text-xs leading-5 text-cyan-900"><span className="font-semibold">Guardrail:</span> these controls only save plan metadata for Super Admin review. They do not call Stripe, create products, create prices, create checkout sessions, collect payment, or enforce billing access.</div>

        <div className="mt-4 rounded-2xl border border-cyan-100 bg-white p-4">
          <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
            <div>
              <h3 className="text-sm font-semibold text-slate-900">Stripe price readiness export and audit notes</h3>
              <p className="mt-1 text-sm leading-6 text-slate-600">Export the current candidate-plan readiness list or review the latest Super Admin audit notes before checkout work continues.</p>
            </div>
            <div className="flex flex-wrap gap-2">
              <button type="button" onClick={exportStripePriceReadinessCsv} className="rounded-lg border border-cyan-200 bg-cyan-50 px-3 py-2 text-sm font-semibold text-cyan-800">Export readiness CSV</button>
              <button type="button" onClick={exportStripePriceIssuesCsv} className="rounded-lg border border-amber-200 bg-amber-50 px-3 py-2 text-sm font-semibold text-amber-800">Export issues CSV</button>
            </div>
          </div>
          <div className="mt-3 grid gap-2 lg:grid-cols-2">
            {priceAuditNotes.length ? priceAuditNotes.slice(0, 4).map((note) => (
              <div key={note.id} className="rounded-xl border border-slate-100 bg-slate-50 p-3 text-xs leading-5 text-slate-600">
                <div className="flex flex-col gap-1 sm:flex-row sm:items-start sm:justify-between">
                  <div className="font-semibold text-slate-900">{note.planName || "Subscription plan"}</div>
                  <span>{dateTime(note.createdAt)}</span>
                </div>
                <div className="mt-1">{note.readinessStatus || "Review"} · {note.warningCount} warning{note.warningCount === 1 ? "" : "s"}</div>
                <div className="mt-1 text-slate-700">{note.note}</div>
              </div>
            )) : <div className="rounded-xl border border-slate-100 bg-slate-50 p-3 text-sm text-slate-600 lg:col-span-2">No Stripe price readiness audit notes have been saved yet.</div>}
          </div>
        </div>
      </section>

      {message ? <div className="rounded-xl border border-slate-200 bg-white px-4 py-3 text-sm text-slate-700">{message}</div> : null}
      {loading ? <div className="rounded-xl border bg-white px-4 py-3 text-sm text-slate-600">Loading saved subscription plans...</div> : null}

      <div className="grid gap-6 xl:grid-cols-[380px_1fr]">
        <section className="rounded-2xl border bg-white p-5 shadow-sm">
          <div className="flex items-center justify-between gap-3">
            <div>
              <h2 className="text-lg font-semibold text-slate-900">Plan list</h2>
              <p className="mt-1 text-sm text-slate-500">Select a plan to review or edit its saved limits.</p>
            </div>
            <button type="button" onClick={createNewPlan} className="rounded-lg bg-slate-950 px-3 py-2 text-sm font-semibold text-white">
              New plan
            </button>
          </div>
          <div className="mt-5 space-y-3">
            {plans.map((plan) => (
              <button
                type="button"
                key={plan.id}
                onClick={() => selectPlan(plan)}
                className={`w-full rounded-2xl border p-4 text-left transition ${selectedPlanId === plan.id ? "border-blue-200 bg-blue-50" : "border-slate-100 bg-white hover:bg-slate-50"}`}
              >
                <div className="flex items-start justify-between gap-3">
                  <div>
                    <div className="font-semibold text-slate-900">{plan.name}</div>
                    <div className="mt-1 text-xs text-slate-500">${plan.monthlyPrice}/month · {planLimitSummary(plan)}</div>
                  </div>
                  <span className={`rounded-full px-2 py-0.5 text-[10px] font-semibold ${statusClasses(plan.status)}`}>{plan.status}</span>
                </div>
                <div className="mt-3 text-xs leading-5 text-slate-600">{plan.bestFor}</div>
                <div className="mt-3 text-xs font-semibold text-slate-700">{enabledFeatureCount(plan)} of {subscriptionFeatureKeys.length} features included</div>
                <div className="mt-1 text-xs text-slate-500">Family: {plan.planFamily} · Visibility: {plan.planVisibility}</div>
                <div className="mt-1 text-xs text-slate-500">Types: {plan.visibleWorkspaceTypes.length ? plan.visibleWorkspaceTypes.map(visibleTypeLabel).join(", ") : "No saved type list"}</div>
                <div className="mt-1 text-xs text-slate-500">Billing: {plan.billing?.provider ?? "None"} · {plan.billing?.syncStatus ?? "Not ready"}</div>
              </button>
            ))}
          </div>
        </section>

        <section className="rounded-2xl border bg-white p-6 shadow-sm">
          <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
            <div>
              <div className="text-xs font-semibold uppercase tracking-[0.18em] text-slate-500">Plan editor</div>
              <h2 className="mt-1 text-lg font-semibold text-slate-900">{draft.name}</h2>
              <p className="mt-1 text-sm text-slate-500">Set what is included for workspaces assigned to this plan.</p>
            </div>
            <div className="flex flex-wrap gap-2">
              <button type="button" onClick={saveDraft} className="rounded-lg bg-blue-700 px-3 py-2 text-sm font-semibold text-white">Save plan</button>
              <button type="button" onClick={duplicatePlan} className="rounded-lg border px-3 py-2 text-sm font-semibold text-slate-700">Duplicate</button>
              <button type="button" onClick={() => deletePlan(draft.id)} className="rounded-lg border border-rose-200 px-3 py-2 text-sm font-semibold text-rose-700">Delete</button>
            </div>
          </div>

          <div className="mt-6 grid gap-4 md:grid-cols-2">
            <label className="block text-sm">
              <div className="mb-1 font-medium text-slate-700">Plan name</div>
              <input value={draft.name} onChange={(event) => setDraft((current) => ({ ...current, name: event.target.value }))} className="w-full rounded-xl border px-3 py-2" />
            </label>
            <label className="block text-sm">
              <div className="mb-1 font-medium text-slate-700">Plan status</div>
              <select value={draft.status} onChange={(event) => setDraft((current) => ({ ...current, status: event.target.value as SubscriptionPlanDraft["status"] }))} className="w-full rounded-xl border px-3 py-2">
                <option>Draft</option>
                <option>Live</option>
                <option>Retired</option>
              </select>
            </label>
            <label className="block text-sm md:col-span-2">
              <div className="mb-1 font-medium text-slate-700">Best for</div>
              <input value={draft.bestFor} onChange={(event) => setDraft((current) => ({ ...current, bestFor: event.target.value }))} className="w-full rounded-xl border px-3 py-2" />
            </label>
          </div>

          <div className="mt-6 rounded-2xl border border-amber-100 bg-amber-50 p-4">
            <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
              <div>
                <div className="text-xs font-semibold uppercase tracking-[0.18em] text-amber-700">Registration visibility staging</div>
                <h3 className="mt-1 text-sm font-semibold text-slate-900">Plan family and workspace visibility</h3>
                <p className="mt-1 text-sm leading-6 text-slate-600">Clean up which workspace types this plan should be visible to before registration starts using plan selection.</p>
              </div>
              <button type="button" onClick={applyRecommendedVisibility} className="rounded-lg border border-amber-200 bg-white px-3 py-2 text-sm font-semibold text-amber-800">Use recommended visibility</button>
            </div>
            <div className="mt-4 grid gap-4 md:grid-cols-2">
              <label className="block text-sm">
                <div className="mb-1 font-medium text-slate-700">Plan family</div>
                <select value={draft.planFamily} onChange={(event) => setDraft((current) => ({ ...current, planFamily: event.target.value as SubscriptionPlanFamily }))} className="w-full rounded-xl border px-3 py-2">
                  {planFamilyOptions.map((family) => <option key={family}>{family}</option>)}
                </select>
              </label>
              <label className="block text-sm">
                <div className="mb-1 font-medium text-slate-700">Plan visibility</div>
                <select value={draft.planVisibility} onChange={(event) => setDraft((current) => ({ ...current, planVisibility: event.target.value as SubscriptionPlanVisibility }))} className="w-full rounded-xl border px-3 py-2">
                  {planVisibilityOptions.map((visibility) => <option key={visibility}>{visibility}</option>)}
                </select>
              </label>
            </div>
            <div className="mt-4">
              <div className="mb-2 text-sm font-medium text-slate-700">Visible workspace types</div>
              <div className="grid gap-2 sm:grid-cols-2 xl:grid-cols-3">
                {workspaceTypeVisibilityOptions.map((option) => (
                  <button
                    type="button"
                    key={option.value}
                    onClick={() => toggleVisibleWorkspaceType(option.value)}
                    className={`rounded-xl border p-3 text-left text-sm ${draft.visibleWorkspaceTypes.includes(option.value) ? "border-emerald-200 bg-emerald-50 text-emerald-800" : "border-slate-200 bg-white text-slate-600"}`}
                  >
                    <div className="font-semibold">{option.label}</div>
                    <div className="mt-1 text-xs">{draft.visibleWorkspaceTypes.includes(option.value) ? "Included in staged plan selection" : "Hidden from this plan"}</div>
                  </button>
                ))}
              </div>
            </div>
            <div className="mt-4 grid gap-3 lg:grid-cols-2">
              <div className="rounded-xl border border-amber-100 bg-white p-3 text-sm leading-6 text-slate-600">
                <span className="font-semibold text-slate-900">Recommended:</span> {draftVisibilityReview.recommended.visibility} visibility for {draftVisibilityReview.recommended.visibleWorkspaceTypes.map(visibleTypeLabel).join(", ")}. {draftVisibilityReview.recommended.note}
              </div>
              <div className="rounded-xl border border-amber-100 bg-white p-3 text-sm leading-6 text-slate-600">
                <span className="font-semibold text-slate-900">Current review:</span> {draftVisibilityReview.status === "Ready" ? "Ready for staging review." : draftVisibilityReview.warnings.join(" ")}
              </div>
            </div>
            <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">Guardrail:</span> saving these fields only updates the plan record. It does not activate registration plan selection, Stripe checkout, hard billing gates, broker distribution limits, owned portal rules, or internal load-board access.</div>
          </div>

          <div className="mt-6 rounded-2xl border border-violet-100 bg-violet-50 p-4">
            <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
              <div>
                <div className="text-xs font-semibold uppercase tracking-[0.18em] text-violet-700">Plan limits and entitlement bundle</div>
                <h3 className="mt-1 text-sm font-semibold text-slate-900">Included usage, paid add-ons, and recommended feature defaults</h3>
                <p className="mt-1 text-sm leading-6 text-slate-600">
                  These fields define the saved entitlement model for this plan. They prepare users/seats, trucks, business phone numbers, and add-on prices without activating hard billing gates.
                </p>
              </div>
              <button type="button" onClick={applyRecommendedEntitlementDefaults} className="rounded-lg border border-violet-200 bg-white px-3 py-2 text-sm font-semibold text-violet-800">Use entitlement defaults</button>
            </div>
            <div className="mt-4 grid gap-3 lg:grid-cols-3">
              <div className="rounded-xl border border-violet-100 bg-white p-3 text-sm leading-6 text-slate-600">
                <div className="text-xs font-semibold uppercase tracking-[0.12em] text-violet-700">Recommended bundle</div>
                <div className="mt-1 font-semibold text-slate-900">{draftEntitlementRecommendation.bundle}</div>
                <div className="mt-1 text-xs leading-5 text-slate-600">{draftEntitlementRecommendation.note}</div>
              </div>
              <div className="rounded-xl border border-violet-100 bg-white p-3 text-sm leading-6 text-slate-600">
                <div className="text-xs font-semibold uppercase tracking-[0.12em] text-violet-700">Current review</div>
                <div className="mt-1 font-semibold text-slate-900">{draftEntitlementLimitReview.status}</div>
                <div className="mt-1 text-xs leading-5 text-slate-600">{draftEntitlementLimitReview.firstFix}</div>
              </div>
              <div className="rounded-xl border border-violet-100 bg-white p-3 text-sm leading-6 text-slate-600">
                <div className="text-xs font-semibold uppercase tracking-[0.12em] text-violet-700">Plan list readiness</div>
                <div className="mt-1 font-semibold text-slate-900">{planEntitlementLimitChecks} need review · {planEntitlementAddOnReady} add-on ready</div>
                <div className="mt-1 text-xs leading-5 text-slate-600">Saved plan limits remain review-only until billing gates and add-on billing are separately approved.</div>
              </div>
            </div>
            <div className="mt-4 grid gap-4 md:grid-cols-3">
              <label className="block text-sm"><div className="mb-1 font-medium text-slate-700">Monthly price</div><input type="number" value={draft.monthlyPrice} onChange={(event) => updateNumber("monthlyPrice", event.target.value)} className="w-full rounded-xl border px-3 py-2" /></label>
              <label className="block text-sm"><div className="mb-1 font-medium text-slate-700">Included users / seats</div><input type="number" value={draft.includedUsers} onChange={(event) => updateNumber("includedUsers", event.target.value)} className="w-full rounded-xl border px-3 py-2" /><div className="mt-1 text-xs text-slate-500">Recommended: {draftEntitlementRecommendation.includedUsers}</div></label>
              <label className="block text-sm"><div className="mb-1 font-medium text-slate-700">Included trucks</div><input type="number" value={draft.includedTrucks} onChange={(event) => updateNumber("includedTrucks", event.target.value)} className="w-full rounded-xl border px-3 py-2" /><div className="mt-1 text-xs text-slate-500">Recommended: {draftEntitlementRecommendation.includedTrucks}</div></label>
              <label className="block text-sm"><div className="mb-1 font-medium text-slate-700">Included phone numbers</div><input type="number" value={draft.includedPhoneNumbers} onChange={(event) => updateNumber("includedPhoneNumbers", event.target.value)} className="w-full rounded-xl border px-3 py-2" /><div className="mt-1 text-xs text-slate-500">Recommended: {draftEntitlementRecommendation.includedPhoneNumbers}</div></label>
              <label className="block text-sm"><div className="mb-1 font-medium text-slate-700">Extra user price</div><input type="number" value={draft.extraUserPrice} onChange={(event) => updateNumber("extraUserPrice", event.target.value)} className="w-full rounded-xl border px-3 py-2" /><div className="mt-1 text-xs text-slate-500">Recommended: ${draftEntitlementRecommendation.extraUserPrice}</div></label>
              <label className="block text-sm"><div className="mb-1 font-medium text-slate-700">Extra truck price</div><input type="number" value={draft.extraTruckPrice} onChange={(event) => updateNumber("extraTruckPrice", event.target.value)} className="w-full rounded-xl border px-3 py-2" /><div className="mt-1 text-xs text-slate-500">Recommended: ${draftEntitlementRecommendation.extraTruckPrice}</div></label>
              <label className="block text-sm"><div className="mb-1 font-medium text-slate-700">Extra phone number price</div><input type="number" value={draft.extraPhoneNumberPrice} onChange={(event) => updateNumber("extraPhoneNumberPrice", event.target.value)} className="w-full rounded-xl border px-3 py-2" /><div className="mt-1 text-xs text-slate-500">Recommended: ${draftEntitlementRecommendation.extraPhoneNumberPrice}</div></label>
            </div>
            {draftEntitlementLimitReview.warnings.length ? <div className="mt-4 rounded-xl border border-amber-100 bg-white p-3 text-xs leading-5 text-amber-800">{draftEntitlementLimitReview.warnings.join(" ")}</div> : <div className="mt-4 rounded-xl border border-emerald-100 bg-white p-3 text-xs leading-5 text-emerald-700">This plan's saved limits and add-on prices fit the current entitlement review.</div>}
            <div className="mt-3 rounded-xl border border-violet-100 bg-white p-3 text-xs leading-5 text-violet-900"><span className="font-semibold">Guardrail:</span> saving these limits only changes plan metadata. It does not restrict users, charge add-ons, collect payment, or change workspace access.</div>
          </div>

          <div className="mt-6 rounded-2xl border border-blue-100 bg-blue-50 p-4">
            <div className="text-xs font-semibold uppercase tracking-[0.18em] text-blue-700">Stripe-ready billing fields</div>
            <h3 className="mt-1 text-sm font-semibold text-slate-900">Platform subscription billing</h3>
            <p className="mt-1 text-sm leading-6 text-slate-600">These fields prepare Super Admin platform subscriptions for Stripe later. They do not charge anyone yet.</p>
            <div className="mt-4 rounded-xl border border-blue-100 bg-white p-3">
              <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
                <div>
                  <div className="text-sm font-semibold text-slate-900">Selected plan checkout-price review</div>
                  <p className="mt-1 text-sm leading-6 text-slate-600">{draftStripePriceReview.candidate ? draftStripePriceReview.firstFix : "This selected plan is not a signup checkout candidate yet."}</p>
                </div>
                <span className={`w-fit rounded-full px-3 py-1 text-xs font-semibold ${priceReadinessBadge(draftStripePriceReview.status)}`}>{draftStripePriceReview.status}</span>
              </div>
              <div className="mt-3 grid gap-2 text-xs md:grid-cols-4">
                <div className="rounded-lg border bg-slate-50 px-2 py-1 text-slate-600">Candidate: {draftStripePriceReview.candidate ? "Yes" : "No"}</div>
                <div className="rounded-lg border bg-slate-50 px-2 py-1 text-slate-600">Product ID: {draftStripePriceReview.missingProductId ? "Missing" : draftStripePriceReview.invalidProductId ? "Review" : "Set"}</div>
                <div className="rounded-lg border bg-slate-50 px-2 py-1 text-slate-600">Monthly price ID: {draftStripePriceReview.missingMonthlyPriceId ? "Missing" : draftStripePriceReview.invalidMonthlyPriceId ? "Review" : "Set"}</div>
                <div className="rounded-lg border bg-slate-50 px-2 py-1 text-slate-600">Sync: {draft.billing?.syncStatus ?? "Not ready"}</div>
              </div>
              {draftStripePriceReview.warnings.length ? <div className="mt-3 rounded-lg border border-amber-100 bg-amber-50 p-3 text-xs leading-5 text-amber-800">{draftStripePriceReview.warnings.join(" ")}</div> : null}
              <div className="mt-3 flex flex-wrap gap-2">
                <button type="button" onClick={applyStripeTestReadinessDefaults} className="rounded-lg border border-blue-200 bg-blue-50 px-3 py-2 text-sm font-semibold text-blue-800">Use Stripe test defaults</button>
                <button type="button" onClick={markStripeIdsVerifiedForReview} className="rounded-lg border border-emerald-200 bg-emerald-50 px-3 py-2 text-sm font-semibold text-emerald-800">Mark IDs verified</button>
              </div>
              <div className="mt-4 rounded-xl border border-slate-100 bg-slate-50 p-3">
                <div className="text-sm font-semibold text-slate-900">Selected-plan audit note</div>
                <p className="mt-1 text-xs leading-5 text-slate-600">Save a Super Admin audit note after checking this plan's Stripe product and monthly price readiness. This does not call Stripe or unlock checkout.</p>
                <textarea
                  value={priceAuditNoteDraft}
                  onChange={(event) => setPriceAuditNoteDraft(event.target.value)}
                  placeholder={suggestedStripePriceAuditNote()}
                  className="mt-3 min-h-[84px] w-full rounded-xl border border-slate-200 bg-white px-3 py-2 text-sm text-slate-700"
                />
                <div className="mt-3 flex flex-wrap gap-2">
                  <button type="button" onClick={fillSuggestedStripePriceAuditNote} className="rounded-lg border border-slate-200 bg-white px-3 py-2 text-sm font-semibold text-slate-700">Use suggested note</button>
                  <button type="button" onClick={saveStripePriceAuditNote} disabled={priceAuditSaving} className="rounded-lg border border-slate-900 bg-slate-900 px-3 py-2 text-sm font-semibold text-white disabled:opacity-60">{priceAuditSaving ? "Saving note..." : "Save audit note"}</button>
                </div>
                {selectedPlanPriceAuditNotes.length ? <div className="mt-3 space-y-2">
                  {selectedPlanPriceAuditNotes.map((note) => (
                    <div key={note.id} className="rounded-lg border border-slate-200 bg-white p-2 text-xs leading-5 text-slate-600">
                      <div className="font-semibold text-slate-800">{dateTime(note.createdAt)} · {note.readinessStatus || "Review"}</div>
                      <div>{note.note}</div>
                    </div>
                  ))}
                </div> : null}
              </div>
            </div>
            <div className="mt-4 grid gap-4 md:grid-cols-3">
              <label className="block text-sm"><div className="mb-1 font-medium text-slate-700">Billing provider</div><select value={draft.billing?.provider ?? "None"} onChange={(event) => updateBilling("provider", event.target.value)} className="w-full rounded-xl border px-3 py-2"><option>None</option><option>Stripe</option><option>Manual</option></select></label>
              <label className="block text-sm"><div className="mb-1 font-medium text-slate-700">Billing mode</div><select value={draft.billing?.mode ?? "Not connected"} onChange={(event) => updateBilling("mode", event.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-medium text-slate-700">Sync status</div><select value={draft.billing?.syncStatus ?? "Not ready"} onChange={(event) => updateBilling("syncStatus", event.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-medium text-slate-700">Stripe product ID</div><input value={draft.billing?.stripeProductId ?? ""} onChange={(event) => updateBilling("stripeProductId", event.target.value)} placeholder="prod_..." className="w-full rounded-xl border px-3 py-2" /></label>
              <label className="block text-sm"><div className="mb-1 font-medium text-slate-700">Monthly price ID</div><input value={draft.billing?.stripeMonthlyPriceId ?? ""} onChange={(event) => updateBilling("stripeMonthlyPriceId", event.target.value)} placeholder="price_..." className="w-full rounded-xl border px-3 py-2" /></label>
              <label className="block text-sm"><div className="mb-1 font-medium text-slate-700">Extra user price ID</div><input value={draft.billing?.stripeExtraUserPriceId ?? ""} onChange={(event) => updateBilling("stripeExtraUserPriceId", event.target.value)} placeholder="price_..." className="w-full rounded-xl border px-3 py-2" /></label>
              <label className="block text-sm"><div className="mb-1 font-medium text-slate-700">Extra truck price ID</div><input value={draft.billing?.stripeExtraTruckPriceId ?? ""} onChange={(event) => updateBilling("stripeExtraTruckPriceId", event.target.value)} placeholder="price_..." className="w-full rounded-xl border px-3 py-2" /></label>
              <label className="block text-sm"><div className="mb-1 font-medium text-slate-700">Extra phone price ID</div><input value={draft.billing?.stripeExtraPhonePriceId ?? ""} onChange={(event) => updateBilling("stripeExtraPhonePriceId", event.target.value)} placeholder="price_..." className="w-full rounded-xl border px-3 py-2" /></label>
              <label className="block text-sm"><div className="mb-1 font-medium text-slate-700">Billing notes</div><input value={draft.billing?.notes ?? ""} onChange={(event) => updateBilling("notes", event.target.value)} placeholder="Internal setup note" className="w-full rounded-xl border px-3 py-2" /></label>
            </div>
          </div>

          <div className="mt-6">
            <h3 className="text-sm font-semibold text-slate-900">Feature access</h3>
            <p className="mt-1 text-sm text-slate-500">These switches now save the entitlement model. Workspace pages will later read from this shared source instead of scattered page logic.</p>
            <div className="mt-4 grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
              {subscriptionFeatureKeys.map((feature) => (
                <button
                  type="button"
                  key={feature}
                  onClick={() => toggleFeature(feature)}
                  className={`rounded-xl border p-3 text-left text-sm ${draft.featureAccess[feature] ? "border-emerald-200 bg-emerald-50 text-emerald-800" : "border-slate-200 bg-slate-50 text-slate-600"}`}
                >
                  <div className="font-semibold">{subscriptionFeatureLabels[feature]}</div>
                  <div className="mt-1 text-xs">{draft.featureAccess[feature] ? "Included in this plan" : "Not included"}</div>
                </button>
              ))}
            </div>
          </div>
        </section>
      </div>

      <section className="rounded-2xl border border-slate-200 bg-white p-6 shadow-sm">
        <div className="text-xs font-semibold uppercase tracking-[0.18em] text-slate-500">Entitlement wiring preview</div>
        <h2 className="mt-1 text-lg font-semibold text-slate-900">How Workspace Admin will be governed</h2>
        <div className="mt-4 grid gap-3 md:grid-cols-3">
          <div className="rounded-xl border bg-slate-50 p-4 text-sm leading-6 text-slate-600"><span className="font-semibold text-slate-900">Pages:</span> Workspace Admin pages will ask the plan whether a module is included before showing full functionality.</div>
          <div className="rounded-xl border bg-slate-50 p-4 text-sm leading-6 text-slate-600"><span className="font-semibold text-slate-900">Limits:</span> users, trucks, and business phone numbers will check included limits before allowing more free usage.</div>
          <div className="rounded-xl border bg-slate-50 p-4 text-sm leading-6 text-slate-600"><span className="font-semibold text-slate-900">Add-ons:</span> extra seats, trucks, and phone numbers are prepared as paid overages instead of hidden system surprises.</div>
        </div>
      </section>
    </div>
  );
}
