"use client";

import * as React from "react";
import Image from "next/image";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import Link from "next/link";
import {
  Building2,
  Phone,
  Mail,
  MapPin,
  Users,
  Globe,
  Layout,
  Pencil,
  DollarSign,
  FileText,
  Calendar,
  ArrowLeft,
  Contact,
  UserCircle2,
  ExternalLink,
  Briefcase,
  FolderKanban,
  Plus,
  Trash2,
  TrendingUp,
  Eye,
  MessageSquare,
  History,
  User,
  CheckCircle2,
} from "lucide-react";
import { Loading } from "@/components/ui/loading";
import {
  customersApi,
  useGetCustomerQuery,
  useGetCustomerLinkedLeadsQuery,
  useGetCustomerBusinessDealsQuery,
  useGetCustomerBusinessDealPaymentStructureQuery,
  useSyncCustomerPaymentStructureMutation,
} from "@/api/rtk/customers-api";
import { useQueryState, parseAsString } from "nuqs";
import { getFileUrl } from "@/api/client";
import {
  useGetCustomerProjectsQuery,
  useDeleteCustomerProjectMutation,
  type CustomerProjectRecord,
  type CustomerProjectStatus,
} from "@/api/rtk/customer-projects-api";
import {
  useGetCustomerContactsQuery,
  useDeleteCustomerContactMutation,
  type CustomerAccountContactRecord,
} from "@/api/rtk/customer-contacts-api";
import { CustomerContactDialog } from "./customer-contact-dialog";
import { UserAvatar } from "@/components/ui/user-avatar";
import type { CustomerBackend } from "@/api/rtk/customers-api";
import { ExpansionSignalsSection } from "./expansion-signals-section";
import { CustomerExpansionEditor } from "./customer-expansion-editor";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { ReactSelect } from "@/components/ui/react-select";
import { DealPaymentManager } from "../deals/deal-payment-manager";
import { type Deal } from "@/api/rtk/deals-api";
import {
  toViewPaymentStructure,
  parsePositiveMoneyString,
  emptyPaymentStructureForLead,
  type DealPaymentStructureRaw,
} from "@/lib/to-view-payment-structure";
import type { PaymentStructure } from "@/components/deals/types";
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import {
  setCustomerLinkedLeads,
  selectCustomerLinkedLeads,
} from "@/store";
import { useAuthToken } from "@/hooks/use-auth-token";
import { useSession } from "next-auth/react";
import { useGetProfileQuery } from "@/api/rtk/auth-api";
import {
  hasPermission,
  type PermissionActorLike,
  type PermissionSource,
} from "@/lib/permissions";
import { format, formatDistanceToNow } from "date-fns";
import { toast } from "sonner";
import { useRouter } from "next/navigation";
import type { BusinessDealRecord } from "@/api/rtk/business-deals-api";
import { CustomerProjectDialog } from "./customer-project-dialog";
import { CustomerProjectsList } from "./customer-projects-list";
import { CustomerLinkedLeadsList } from "./customer-linked-leads-list";
import { CustomerBusinessDealsList } from "./customer-business-deals-list";
import { CustomerContactDeleteDialog } from "./customer-contact-delete-dialog";
import { CustomerContactViewDialog } from "./customer-contact-view-dialog";
import { CustomerProjectDeleteDialog } from "./customer-project-delete-dialog";
import {
  AlertDialog,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";

import { DetailItem, SectionHeading } from "./customer-details-shared";

export interface CustomerDetailViewProps {
  customerId: string;
  /** When false, skips loading customer (e.g. modal closed). */
  fetchEnabled: boolean;
  variant: "page" | "modal";
  onBack?: () => void;
  onEdit?: (customer: CustomerBackend) => void;
}

function stageLabel(d: Deal): string {
  const nested = d.stageDetail?.stageName?.name;
  if (nested) return nested;
  if (typeof d.stage === "string" && d.stage.length < 24) return d.stage;
  return "—";
}

function leadTitle(d: Deal): string {
  return (
    d.customerName?.trim() ||
    d.email?.trim() ||
    d.leadId?.trim() ||
    d.id.slice(0, 8) + "…"
  );
}

function businessDealStageLabel(b: BusinessDealRecord): string {
  const sub = b.pipelineSubStage?.name?.trim();
  const ps = b.PipelineStage;
  const main =
    ps?.stageName?.name?.trim() ||
    ps?.name?.trim() ||
    b.stageDetail?.name?.trim() ||
    "";
  if (sub && main) return `${main} › ${sub}`;
  return sub || main || "—";
}

function businessDealTitle(b: BusinessDealRecord): string {
  const t = b.title?.trim();
  if (t) return t;
  return b.id.slice(0, 8) + "…";
}

const PROJECT_STATUS_LABELS: Record<CustomerProjectStatus, string> = {
  PLANNING: "Planning",
  ACTIVE: "Active",
  ON_HOLD: "On hold",
  COMPLETED: "Completed",
  CANCELLED: "Cancelled",
};

export function CustomerDetailView({
  customerId,
  fetchEnabled,
  variant,
  onBack,
  onEdit,
}: CustomerDetailViewProps) {
  const {
    data: customer,
    isLoading,
    isError,
  } = useGetCustomerQuery(customerId, { skip: !fetchEnabled || !customerId });

  const [mainTab, setMainTab] = useQueryState(
    "tabs",
    parseAsString.withDefault("details").withOptions({ shallow: true }),
  );

  const [selectedSalesDealId, setSelectedSalesDealId] = React.useState<
    string | null
  >(null);
  React.useEffect(() => {
    setSelectedSalesDealId(null);
  }, [customerId]);

  const [syncCustomerPaymentStructure, { isLoading: isUpdatingPayment }] =
    useSyncCustomerPaymentStructureMutation();

  const { token: accessToken } = useAuthToken();
  const { data: session } = useSession();
  const { data: userProfile } = useGetProfileQuery(undefined, {
    skip: !accessToken,
  });

  /**
   * JWT `session.backendUser` is sometimes minimal (roleId only). `/auth/profile` returns full
   * role + permissions. Prefer whichever actor actually carries permissions or role name.
   */
  const permissionSource = React.useMemo((): PermissionSource => {
    const bu = (session as { backendUser?: PermissionActorLike | null } | null)
      ?.backendUser;
    const prof = userProfile as PermissionActorLike | undefined;

    const actorUsable = (a: PermissionActorLike | null | undefined) =>
      Boolean(
        a &&
        (a.role?.name?.trim() ||
          (a.role?.permissions && a.role.permissions.length > 0)),
      );

    if (actorUsable(bu)) return bu;
    if (actorUsable(prof)) return prof;
    return bu ?? prof ?? null;
  }, [session, userProfile]);

  const router = useRouter();

  const linkedQueriesReady =
    fetchEnabled && !!customerId && !!customer && !isError;

  const dispatch = useAppDispatch();
  const cachedLinkedLeads = useAppSelector(selectCustomerLinkedLeads(customerId));

  const { data: fetchedLinkedLeads = [], isLoading: linkedLeadsLoading } =
    useGetCustomerLinkedLeadsQuery(customerId, {
      skip: !linkedQueriesReady,
    });

  React.useEffect(() => {
    if (!linkedLeadsLoading && fetchedLinkedLeads.length > 0) {
      dispatch(setCustomerLinkedLeads({ customerId, leads: fetchedLinkedLeads }));
    }
  }, [dispatch, customerId, fetchedLinkedLeads, linkedLeadsLoading]);

  const linkedLeads = linkedLeadsLoading && cachedLinkedLeads.length > 0
    ? cachedLinkedLeads
    : fetchedLinkedLeads.length > 0
      ? fetchedLinkedLeads
      : cachedLinkedLeads;

  const { data: customerBusinessDeals = [], isLoading: businessDealsLoading } =
    useGetCustomerBusinessDealsQuery(customerId, {
      skip: !linkedQueriesReady,
    });

  const { data: apiCustomerProjects = [], isLoading: projectsLoading } =
    useGetCustomerProjectsQuery(customerId, {
      skip: !linkedQueriesReady,
    });

  const { data: customerAccountContacts = [], isLoading: contactsLoading } =
    useGetCustomerContactsQuery(customerId, {
      skip: !linkedQueriesReady,
    });

  const [deleteCustomerProject, { isLoading: deletingProject }] =
    useDeleteCustomerProjectMutation();

  const [deleteCustomerContact, { isLoading: deletingContact }] =
    useDeleteCustomerContactMutation();

  const [projectDialogOpen, setProjectDialogOpen] = React.useState(false);
  const [projectEditing, setProjectEditing] =
    React.useState<CustomerProjectRecord | null>(null);
  const [projectDeleteTarget, setProjectDeleteTarget] =
    React.useState<CustomerProjectRecord | null>(null);

  const [contactDialogOpen, setContactDialogOpen] = React.useState(false);
  const [contactEditing, setContactEditing] =
    React.useState<CustomerAccountContactRecord | null>(null);
  const [contactDeleteTarget, setContactDeleteTarget] =
    React.useState<CustomerAccountContactRecord | null>(null);
  const [contactViewTarget, setContactViewTarget] =
    React.useState<CustomerAccountContactRecord | null>(null);

  /** When customer has pipeline deals, payment UI is driven by sales deal (same idea as business-deal detail). */
  const payViaSalesDeals = customerBusinessDeals.length > 0;

  const activeSalesDeal = React.useMemo(() => {
    if (!payViaSalesDeals) return undefined;
    if (selectedSalesDealId) {
      return (
        customerBusinessDeals.find((b) => b.id === selectedSalesDealId) ??
        customerBusinessDeals[0]
      );
    }
    return customerBusinessDeals[0];
  }, [payViaSalesDeals, customerBusinessDeals, selectedSalesDealId]);

  const queryBusinessDealId = activeSalesDeal?.id ?? "";

  const paymentTabActive = mainTab === "payment";

  const skipPaymentDealQuery =
    !fetchEnabled ||
    !linkedQueriesReady ||
    !queryBusinessDealId ||
    !paymentTabActive ||
    !payViaSalesDeals;

  const {
    data: paymentDealBundle,
    isLoading: paymentDealBundleLoading,
    isFetching: paymentDealBundleFetching,
  } = useGetCustomerBusinessDealPaymentStructureQuery(
    { customerId, businessDealId: queryBusinessDealId },
    {
      skip: skipPaymentDealQuery || !customerId,
      refetchOnMountOrArgChange: true,
    },
  );

  const paymentDealBundleRemoteBusy = Boolean(
    paymentTabActive &&
      queryBusinessDealId &&
      !skipPaymentDealQuery &&
      (paymentDealBundleLoading ||
        (paymentDealBundleFetching && paymentDealBundle == null)),
  );

  const paymentDataLoading = Boolean(
    paymentTabActive &&
      linkedQueriesReady &&
      payViaSalesDeals &&
      (businessDealsLoading || paymentDealBundleRemoteBusy),
  );

  const customerPaymentForm = React.useMemo((): PaymentStructure => {
    if (!payViaSalesDeals || !activeSalesDeal) {
      return emptyPaymentStructureForLead();
    }
    const budget =
      paymentDealBundle?.budget ??
      (activeSalesDeal.dealValue != null
        ? parsePositiveMoneyString(activeSalesDeal.dealValue)
        : null);
    return (
      toViewPaymentStructure(
        paymentDealBundle?.paymentStructure,
        budget,
      ) ?? emptyPaymentStructureForLead()
    );
  }, [
    payViaSalesDeals,
    activeSalesDeal,
    paymentDealBundle,
  ]);

  const canManageCustomerProjects = hasPermission(
    permissionSource,
    ["UPDATE"],
    "CUSTOMER",
  );

  const canViewPayment = hasPermission(
    permissionSource,
    ["READ", "CREATE", "UPDATE"],
    "PAYMENT_STRUCTURE",
  );
  const canManagePayment = hasPermission(
    permissionSource,
    ["CREATE", "UPDATE"],
    "PAYMENT_STRUCTURE",
  );
  /** Align with deal / business-deal payment edits (backend uses deal row-level rules). */
  const canManageCustomerPayment =
    canManagePayment ||
    hasPermission(permissionSource, "UPDATE", "DEAL") ||
    hasPermission(permissionSource, "UPDATE", "CUSTOMER");

  const resolvedPaymentSaveBusinessDealId = activeSalesDeal?.id?.trim() ?? null;

  const customerPaymentReadOnly =
    !canManageCustomerPayment || !resolvedPaymentSaveBusinessDealId;

  const salesDealOptions = React.useMemo(
    () =>
      customerBusinessDeals.map((bd) => ({
        value: bd.id,
        label: businessDealTitle(bd),
      })),
    [customerBusinessDeals],
  );

  const salesDealPicker = payViaSalesDeals ? (
    <div className="flex flex-col gap-1.5 sm:flex-row sm:items-center sm:gap-3">
      <span className="text-[12px] font-medium text-gray-700 shrink-0">
        Sales deal
      </span>
      <ReactSelect
        value={activeSalesDeal?.id ?? ""}
        onValueChange={(v) => setSelectedSalesDealId(v)}
        options={salesDealOptions}
        placeholder="Select deal"
        triggerClassName="w-full sm:max-w-[320px] min-h-10 rounded-xl"
        contentClassName="rounded-xl"
      />
    </div>
  ) : null;

  React.useEffect(() => {
    if (!selectedSalesDealId) return;
    if (!customerBusinessDeals.some((b) => b.id === selectedSalesDealId)) {
      setSelectedSalesDealId(null);
    }
  }, [selectedSalesDealId, customerBusinessDeals]);

  const displayName =
    customer?.fullName ?? customer?.customerName ?? customer?.companyName ?? "";

  const fmtDate = (d: string | Date | null | undefined) => {
    if (!d) return "—";
    return format(new Date(d), "MMM d, yyyy");
  };

  const fmtFromNow = (d: string | Date | null | undefined) => {
    if (!d) return "—";
    return formatDistanceToNow(new Date(d), { addSuffix: true });
  };
  const fmtCurrency = (v: string | number | null | undefined) => {
    if (v === null || v === undefined || v === "") return "—";
    const n = typeof v === "string" ? parseFloat(v) : v;
    if (isNaN(n)) return "—";
    return new Intl.NumberFormat("en-US", {
      style: "currency",
      currency: "USD",
      minimumFractionDigits: 0,
      maximumFractionDigits: 0,
    }).format(n);
  };

  const loadingBlock = (
    <Loading
      layout="panel"
      className="min-h-[320px]"
      size="lg"
      spinnerClassName="text-[#6C63FF]"
    />
  );

  const errorBlock = (
    <div className="flex flex-col items-center justify-center min-h-[240px] gap-4 p-8">
      <p className="text-gray-600 font-medium">
        Could not load customer details.
      </p>
      {variant === "page" && onBack && (
        <Button variant="outline" onClick={onBack}>
          Back to customers
        </Button>
      )}
    </div>
  );

  const body = (() => {
    if (isLoading) return loadingBlock;
    if (isError || !customer) return errorBlock;

    return (
      <>
        <div className="relative overflow-hidden pt-8 pb-10 px-8">
          <div className="absolute inset-0 bg-[#6C63FF] opacity-[0.03]" />
          <div className="absolute top-0 right-0 h-96 w-96 bg-[#6C63FF] opacity-[0.05] blur-[120px] -translate-y-1/2 translate-x-1/4" />

          <div className="relative flex items-center justify-between">
            <div className="flex items-center gap-6">
              <div className="relative h-16 w-16 rounded-2xl bg-[#6C63FF]/10 border border-[#6C63FF]/20 flex items-center justify-center shadow-inner overflow-hidden">
                {customer.avatar?.url ? (
                  <Image
                    src={getFileUrl(customer.avatar.url) ?? ""}
                    alt={displayName}
                    fill
                    sizes="64px"
                    className="object-cover"
                  />
                ) : (
                  <Building2 size={32} className="text-[#6C63FF]" />
                )}
              </div>
              <div>
                <h2 className="text-[28px] font-semibold text-gray-900 font-['Lexend'] leading-tight tracking-tight">
                  {displayName || "Unnamed Customer"}
                </h2>
                {customer.customerId && (
                  <p className="text-[12px] font-medium text-gray-400 font-['Lexend_Deca'] mt-0.5">
                    Customer ID: {customer.customerId}
                  </p>
                )}
                <div className="flex items-center gap-3 mt-1.5 flex-wrap">
                  {customer.customerStatus && (
                    <span className="text-[14px] font-medium text-gray-500">
                      {customer.customerStatus}
                    </span>
                  )}
                  {customer.companyName && (
                    <>
                      <span className="text-gray-300">/</span>
                      <span className="text-[14px] font-medium text-gray-600">
                        {customer.companyName}
                      </span>
                    </>
                  )}
                </div>
              </div>
            </div>

            <div className="flex items-center gap-2">
              {onEdit && (
                <Button
                  variant="outline"
                  size="sm"
                  className="gap-2"
                  onClick={() => onEdit(customer)}
                >
                  <Pencil size={14} /> Edit
                </Button>
              )}
            </div>
          </div>
        </div>

        <div className="px-8 pb-8 mt-2">
          <Tabs value={mainTab} onValueChange={setMainTab} className="w-full">
            <TabsList className="mb-6 min-h-11 h-auto flex-wrap gap-1 py-1 bg-gray-100/50 p-1 border border-gray-100 rounded-xl">
              <TabsTrigger
                value="details"
                className="gap-2 px-6 font-semibold text-[13px] rounded-lg data-[state=active]:bg-white data-[state=active]:text-[#6C63FF] data-[state=active]:shadow-sm"
              >
                <Layout size={14} /> Details
              </TabsTrigger>
              <TabsTrigger
                value="contacts"
                className="gap-2 px-6 font-semibold text-[13px] rounded-lg data-[state=active]:bg-white data-[state=active]:text-[#6C63FF] data-[state=active]:shadow-sm"
              >
                <UserCircle2 size={14} />
                Contacts
                {customerAccountContacts.length > 0 ? (
                  <span className="ml-1 rounded-full bg-[#6C63FF]/15 px-2 py-0.5 text-[11px] font-bold text-[#6C63FF] tabular-nums">
                    {customerAccountContacts.length}
                  </span>
                ) : null}
              </TabsTrigger>
              <TabsTrigger
                value="leads"
                className="gap-2 px-6 font-semibold text-[13px] rounded-lg data-[state=active]:bg-white data-[state=active]:text-[#6C63FF] data-[state=active]:shadow-sm"
              >
                <Contact size={14} />
                Linked leads
                {linkedLeads.length > 0 ? (
                  <span className="ml-1 rounded-full bg-[#6C63FF]/15 px-2 py-0.5 text-[11px] font-bold text-[#6C63FF] tabular-nums">
                    {linkedLeads.length}
                  </span>
                ) : null}
              </TabsTrigger>
              <TabsTrigger
                value="all-deals"
                className="gap-2 px-6 font-semibold text-[13px] rounded-lg data-[state=active]:bg-white data-[state=active]:text-[#6C63FF] data-[state=active]:shadow-sm"
              >
                <Briefcase size={14} />
                All deals
                {customerBusinessDeals.length > 0 ? (
                  <span className="ml-1 rounded-full bg-[#6C63FF]/15 px-2 py-0.5 text-[11px] font-bold text-[#6C63FF] tabular-nums">
                    {customerBusinessDeals.length}
                  </span>
                ) : null}
              </TabsTrigger>
              <TabsTrigger
                value="projects"
                className="gap-2 px-6 font-semibold text-[13px] rounded-lg data-[state=active]:bg-white data-[state=active]:text-[#6C63FF] data-[state=active]:shadow-sm"
              >
                <FolderKanban size={14} />
                Projects
                {apiCustomerProjects.length > 0 ? (
                  <span className="ml-1 rounded-full bg-[#6C63FF]/15 px-2 py-0.5 text-[11px] font-bold text-[#6C63FF] tabular-nums">
                    {apiCustomerProjects.length}
                  </span>
                ) : null}
              </TabsTrigger>
              <TabsTrigger
                value="expansion"
                className="gap-2 px-6 font-semibold text-[13px] rounded-lg data-[state=active]:bg-white data-[state=active]:text-[#6C63FF] data-[state=active]:shadow-sm"
              >
                <TrendingUp size={14} />
                Expansion
              </TabsTrigger>
              {canViewPayment && (
                <TabsTrigger
                  value="payment"
                  className="gap-2 px-6 font-semibold text-[13px] rounded-lg data-[state=active]:bg-white data-[state=active]:text-[#6C63FF] data-[state=active]:shadow-sm"
                >
                  <DollarSign size={14} /> Payment Structure
                </TabsTrigger>
              )}
            </TabsList>

            <TabsContent
              value="details"
              className="animate-in fade-in slide-in-from-bottom-2 duration-300 outline-none"
            >
              <SectionHeading icon={<Layout size={14} />}>
                Contact & company
              </SectionHeading>
              <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4 mt-4">
                <DetailItem
                  label="Email"
                  value={customer.email ?? undefined}
                  icon={<Mail size={14} />}
                />
                <DetailItem
                  label="Phone"
                  value={customer.phone ?? undefined}
                  icon={<Phone size={14} />}
                />
                <DetailItem
                  label="Address (USA)"
                  value={customer.addressUsa ?? undefined}
                  icon={<MapPin size={14} />}
                />
                <DetailItem
                  label="Address (Intl)"
                  value={customer.addressIntl ?? undefined}
                  icon={<MapPin size={14} />}
                />
                <DetailItem
                  label="Postal Code"
                  value={customer.postalCode ?? undefined}
                />
                <DetailItem
                  label="Website"
                  value={customer.website ?? undefined}
                  icon={<Globe size={14} />}
                />
                <DetailItem
                  label="Country"
                  value={customer.country ?? undefined}
                />
                <DetailItem
                  label="Company"
                  value={customer.companyName ?? customer.company ?? undefined}
                  icon={<Building2 size={14} />}
                />
                <DetailItem label="Brand" value={customer.brand ?? undefined} />
              </div>

              <SectionHeading icon={<DollarSign size={14} />} className="mt-8">
                Metrics & status
              </SectionHeading>
              <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 mt-4">
                <DetailItem
                  label="Total Lifetime Value"
                  value={fmtCurrency(customer.totalLifetimeValue)}
                />
                <DetailItem
                  label="Total Pipeline Value"
                  value={fmtCurrency(customer.totalDealsValue)}
                />
                <DetailItem
                  label="Account Tier"
                  value={customer.accountTier ?? undefined}
                />
                <DetailItem
                  label="Total Projects"
                  value={customer.totalProjects ?? undefined}
                />
                <DetailItem
                  label="Active Projects"
                  value={customer.activeProjects ?? undefined}
                />
                <DetailItem
                  label="Contract Expiry"
                  value={fmtDate(customer.contractExpiryDate)}
                  icon={<Calendar size={14} />}
                />
                <DetailItem
                  label="NPS Score"
                  value={customer.npsScore ?? undefined}
                />
                <DetailItem
                  label="NPS Date"
                  value={fmtDate(customer.npsDate)}
                />
                <DetailItem label="AHS" value={customer.ahs ?? undefined} />
              </div>

              {canViewPayment && payViaSalesDeals ? (
                <p className="mt-8 text-[12px] text-gray-500 max-w-xl">
                  Payment terms for each linked sales deal are edited on the{" "}
                  <span className="font-semibold text-gray-700">Payment</span>{" "}
                  tab (same as the sales deal page; saved on the linked lead).
                </p>
              ) : null}

              <SectionHeading icon={<Users size={14} />} className="mt-8">
                Assignment
              </SectionHeading>
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 mt-4">
                <DetailItem
                  label="Assigned AM"
                  value={customer.assignedAm?.name ?? undefined}
                />
                <DetailItem
                  label="Owner"
                  value={customer.owner?.name ?? undefined}
                />
              </div>

              {customer.notes && (
                <div className="mt-8">
                  <SectionHeading icon={<FileText size={14} />}>
                    Notes
                  </SectionHeading>
                  <div className="mt-4 p-6 rounded-3xl bg-[#6C63FF]/5 border border-[#6C63FF]/10">
                    <p className="text-[13px] text-gray-600 leading-relaxed whitespace-pre-wrap">
                      {customer.notes}
                    </p>
                  </div>
                </div>
              )}

              <div className="mt-6 flex items-center gap-4 text-[11px] text-gray-400 font-['Lexend_Deca']">
                <span>Created: {fmtDate(customer.createdAt)}</span>
                <span>Updated: {fmtDate(customer.updatedAt)}</span>
              </div>
            </TabsContent>

            <TabsContent
              value="contacts"
              className="animate-in fade-in slide-in-from-bottom-2 duration-300 outline-none"
            >
              <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between mb-4">
                <SectionHeading
                  icon={<UserCircle2 size={14} />}
                  className="mb-0 flex-1"
                >
                  People at this account
                </SectionHeading>
                {canManageCustomerProjects ? (
                  <Button
                    type="button"
                    size="sm"
                    className="gap-2 rounded-xl bg-[#6C63FF] hover:bg-[#5a52e6] shrink-0"
                    onClick={() => {
                      setContactEditing(null);
                      setContactDialogOpen(true);
                    }}
                  >
                    <Plus size={14} /> New contact
                  </Button>
                ) : null}
              </div>
              {contactsLoading && customerAccountContacts.length === 0 ? (
                <Loading
                  layout="section"
                  message="Loading contacts…"
                  spinnerClassName="text-[#6C63FF]"
                />
              ) : customerAccountContacts.length === 0 ? (
                <div className="flex flex-col items-center justify-center py-24 text-center bg-gray-50/50 border border-dashed border-gray-200 rounded-3xl">
                  <div className="p-4 rounded-full bg-gray-100 mb-4">
                    <UserCircle2 className="w-8 h-8 text-gray-400" />
                  </div>
                  <h4 className="text-gray-900 font-semibold mb-1">
                    No contacts yet
                  </h4>
                  <p className="text-[13px] text-gray-500 max-w-[340px]">
                    Add people you work with at this customer (separate from CRM
                    lead contacts).
                  </p>
                  {canManageCustomerProjects ? (
                    <Button
                      type="button"
                      variant="outline"
                      size="sm"
                      className="mt-4 gap-2 rounded-xl"
                      onClick={() => {
                        setContactEditing(null);
                        setContactDialogOpen(true);
                      }}
                    >
                      <Plus size={14} /> Add first contact
                    </Button>
                  ) : null}
                </div>
              ) : (
                <ul className="flex flex-col gap-3 mt-2">
                  {customerAccountContacts.map((c) => (
                    <li
                      key={c.id}
                      className="flex flex-col gap-3 rounded-2xl border border-gray-100 bg-white/80 p-4 shadow-sm sm:flex-row sm:items-start sm:justify-between"
                    >
                      <div className="flex gap-3 min-w-0">
                        <UserAvatar
                          avatar={c.avatar}
                          name={c.name}
                          size="md"
                          className="rounded-xl"
                        />
                        <div className="min-w-0 space-y-1">
                          <div className="flex items-center gap-2 flex-wrap">
                            <p className="text-[15px] font-semibold text-gray-900 font-['Lexend']">
                              {c.name}
                            </p>
                            {c.isPrimary ? (
                              <span className="text-[10px] font-bold uppercase tracking-wide px-2 py-0.5 rounded-full bg-[#6C63FF]/15 text-[#6C63FF]">
                                Primary
                              </span>
                            ) : null}
                          </div>
                          {c.title || c.department ? (
                            <p className="text-[12px] text-gray-600">
                              {[c.title, c.department]
                                .filter(Boolean)
                                .join(" · ")}
                            </p>
                          ) : null}
                          <div className="flex flex-col gap-0.5 text-[12px] text-gray-500 font-['Lexend_Deca']">
                            {c.email ? (
                              <a
                                href={`mailto:${c.email}`}
                                className="text-[#6C63FF] hover:underline w-fit"
                              >
                                {c.email}
                              </a>
                            ) : null}
                            {c.phone ? <span>{c.phone}</span> : null}
                          </div>
                          {c.notes ? (
                            <p className="text-[12px] text-gray-600 line-clamp-3 whitespace-pre-wrap pt-1">
                              {c.notes}
                            </p>
                          ) : null}
                          <div className="flex flex-wrap items-center gap-x-2 gap-y-1 text-[11px] text-gray-400 pt-1">
                            {c.createdBy?.name && (
                              <span>Added by {c.createdBy.name}</span>
                            )}
                            <span className="hidden sm:inline text-gray-200">·</span>
                            <span>Created {fmtDate(c.createdAt)}</span>
                            <span className="hidden sm:inline text-gray-200">·</span>
                            <span>Updated {fmtFromNow(c.updatedAt)}</span>
                          </div>
                        </div>
                      </div>
                      <div className="flex shrink-0 flex-wrap gap-2">
                        <Button
                          type="button"
                          variant="outline"
                          size="sm"
                          className="gap-1.5 rounded-xl"
                          onClick={() => setContactViewTarget(c)}
                        >
                          <Eye size={14} /> View
                        </Button>
                        {canManageCustomerProjects ? (
                          <>
                            <Button
                              type="button"
                              variant="outline"
                              size="sm"
                              className="gap-1.5 rounded-xl"
                              onClick={() => {
                                setContactEditing(c);
                                setContactDialogOpen(true);
                              }}
                            >
                              <Pencil size={14} /> Edit
                            </Button>
                            <Button
                              type="button"
                              variant="outline"
                              size="sm"
                              className="gap-1.5 rounded-xl text-red-600 border-red-200 hover:bg-red-50"
                              onClick={() => setContactDeleteTarget(c)}
                            >
                              <Trash2 size={14} /> Remove
                            </Button>
                          </>
                        ) : null}
                      </div>
                    </li>
                  ))}
                </ul>
              )}
            </TabsContent>

            <TabsContent
              value="leads"
              className="animate-in fade-in slide-in-from-bottom-2 duration-300 outline-none"
            >
              <CustomerLinkedLeadsList
                leads={linkedLeads}
                isLoading={linkedLeadsLoading}
                leadTitle={leadTitle}
                stageLabel={stageLabel}
                fmtCurrency={fmtCurrency}
              />
            </TabsContent>

            <TabsContent
              value="all-deals"
              className="animate-in fade-in slide-in-from-bottom-2 duration-300 outline-none"
            >
              <CustomerBusinessDealsList
                deals={customerBusinessDeals}
                isLoading={businessDealsLoading}
                totalValue={customer.totalDealsValue}
                dealTitle={businessDealTitle}
                stageLabel={businessDealStageLabel}
                fmtCurrency={fmtCurrency}
                onOpenDeal={(id) => router.push(`/sales-deals/${id}`)}
              />
            </TabsContent>

            <TabsContent
              value="projects"
              className="animate-in fade-in slide-in-from-bottom-2 duration-300 outline-none"
            >
              <CustomerProjectsList
                projects={apiCustomerProjects}
                isLoading={projectsLoading}
                canManage={canManageCustomerProjects}
                onNew={() => {
                  setProjectEditing(null);
                  setProjectDialogOpen(true);
                }}
                onEdit={(p) => {
                  setProjectEditing(p);
                  setProjectDialogOpen(true);
                }}
                onDelete={(p) => setProjectDeleteTarget(p)}
                fmtDate={fmtDate}
                fmtCurrency={fmtCurrency}
              />
            </TabsContent>

            <TabsContent
              value="expansion"
              className="animate-in fade-in slide-in-from-bottom-2 duration-300 outline-none"
            >
              <CustomerExpansionEditor
                customerId={customerId}
                customer={customer}
                canEdit={canManageCustomerProjects}
              />
              <ExpansionSignalsSection customerId={customer.id} />
            </TabsContent>

            <TabsContent
              value="payment"
              className="animate-in fade-in slide-in-from-bottom-2 duration-300 outline-none"
            >
              {!payViaSalesDeals ? (
                <div className="rounded-xl border border-dashed border-gray-200 px-4 py-10 text-center">
                  <p className="text-sm text-gray-600">
                    Create a sales deal for this customer to manage payment structure.
                  </p>
                </div>
              ) : paymentDataLoading ? (
                <Loading
                  layout="section"
                  message="Loading payment structure…"
                  spinnerClassName="text-[#6C63FF]"
                />
              ) : (
                <div className="space-y-4">
                  <DealPaymentManager
                    showAddCustomPaymentForm
                    title="Payment by sales deal"
                    description={
                      <>
                        Each sales deal has its own payment ledger. Choose a deal, then
                        edit terms — saves never affect other deals on this customer.
                      </>
                    }
                    payment={customerPaymentForm}
                    readOnly={customerPaymentReadOnly}
                    isSaving={isUpdatingPayment}
                    headerActions={
                      activeSalesDeal?.id ? (
                        <Button
                          variant="outline"
                          size="sm"
                          className="shrink-0 gap-1.5 rounded-xl bg-white"
                          asChild
                        >
                          <Link
                            href={`/sales-deals/${activeSalesDeal.id}`}
                            target="_blank"
                            rel="noopener noreferrer"
                          >
                            <ExternalLink size={14} />
                            Open sales deal
                          </Link>
                        </Button>
                      ) : null
                    }
                    selectors={
                      <div className="space-y-3">{salesDealPicker}</div>
                    }
                    upfrontStatusReadOnly={!canManageCustomerPayment}
                    autoPersistUpfrontStatus={false}
                    onUpdate={async (payment) => {
                      if (
                        !resolvedPaymentSaveBusinessDealId ||
                        !customer?.id
                      ) {
                        throw new Error("NO_PAYMENT_SAVE_TARGET");
                      }
                      await syncCustomerPaymentStructure({
                        customerId: customer.id,
                        businessDealId: resolvedPaymentSaveBusinessDealId,
                        body: payment,
                      }).unwrap();
                      dispatch(
                        customersApi.util.invalidateTags([
                          {
                            type: "CustomerBusinessDealPaymentStructure",
                            id: customer.id,
                          },
                        ]),
                      );
                      toast.success("Payment saved");
                    }}
                  />
                </div>
              )}
            </TabsContent>
          </Tabs>

          <CustomerProjectDialog
            open={projectDialogOpen}
            onOpenChange={(open) => {
              setProjectDialogOpen(open);
              if (!open) setProjectEditing(null);
            }}
            customerId={customerId}
            linkedLeads={linkedLeads}
            project={projectEditing}
          />

          <CustomerContactDialog
            open={contactDialogOpen}
            onOpenChange={(open) => {
              setContactDialogOpen(open);
              if (!open) setContactEditing(null);
            }}
            customerId={customerId}
            contact={contactEditing}
          />

          <CustomerProjectDeleteDialog
            open={projectDeleteTarget != null}
            onOpenChange={(open) => {
              if (!open && deletingProject) return;
              if (!open) setProjectDeleteTarget(null);
            }}
            projectName={projectDeleteTarget?.name ?? null}
            isLoading={deletingProject}
            onConfirm={async () => {
              if (!projectDeleteTarget) return;
              try {
                await deleteCustomerProject({
                  customerId,
                  projectId: projectDeleteTarget.id,
                }).unwrap();
                toast.success("Project deleted");
                setProjectDeleteTarget(null);
              } catch {
                toast.error("Could not delete project");
              }
            }}
          />

          <CustomerContactDeleteDialog
            open={contactDeleteTarget != null}
            onOpenChange={(open) => {
              if (!open && deletingContact) return;
              if (!open) setContactDeleteTarget(null);
            }}
            contactName={contactDeleteTarget?.name ?? null}
            isLoading={deletingContact}
            onConfirm={async () => {
              if (!contactDeleteTarget) return;
              try {
                await deleteCustomerContact({
                  customerId,
                  contactId: contactDeleteTarget.id,
                }).unwrap();
                toast.success("Contact removed");
                setContactDeleteTarget(null);
              } catch {
                toast.error("Could not remove contact");
              }
            }}
          />

          <CustomerContactViewDialog
            open={contactViewTarget != null}
            onOpenChange={(open) => {
              if (!open) setContactViewTarget(null);
            }}
            contact={contactViewTarget}
          />
        </div>
      </>
    );
  })();

  if (variant === "page") {
    return (
      <div className="flex flex-col h-full min-h-0 overflow-hidden">
        <header className="shrink-0 border-b border-gray-200/80 bg-white/60 backdrop-blur-sm px-4 sm:px-6 py-3 flex items-center gap-3 z-10">
          <Button
            type="button"
            variant="ghost"
            size="icon"
            onClick={onBack}
            className="h-9 w-9 rounded-xl hover:bg-gray-100"
            aria-label="Back to customers"
          >
            <ArrowLeft size={18} />
          </Button>
          <div className="h-6 w-px bg-gray-200" />
          <div className="min-w-0">
            <p className="text-[10px] font-bold text-gray-400 uppercase tracking-widest font-['Lexend']">
              Customer
            </p>
            <p className="text-sm font-semibold text-gray-900 truncate font-['Lexend']">
              {displayName || "…"}
            </p>
          </div>
        </header>
        <div className="flex-1 min-h-0 overflow-y-auto overflow-x-hidden scrollbar-themed rounded-2xl border border-white/40 bg-white/40">
          {body}
        </div>
      </div>
    );
  }

  return (
    <div className="max-h-[95vh] overflow-y-auto overflow-x-hidden scrollbar-themed">
      {body}
    </div>
  );
}
