import { useClientStatus, StatCard, EmptyState, useCreateClient, CustomModal, useUpdateClient, useDeleteClient, usePaginationState, useClients, SubshellContentContainer, PageContainer, PageTitleCaption, FilterBar, CenteredErrorState, useClient, showApiErrorNotification } from '../../chunk-CPIQ5GXG.js';
import '../../chunk-NZ2F5RQ4.js';
import '../../chunk-OJJK27GC.js';
import '../../chunk-ZTWA5H77.js';
import '../../chunk-AUDNF2Q7.js';
import '../../chunk-6M6OLGQY.js';
import '../../chunk-MKH2KOAO.js';
import '../../chunk-7Q5THR43.js';
import '../../chunk-SJHM4WDG.js';
import '../../chunk-GMXGDO3I.js';
import { CardHeader } from '../../chunk-S3XR4II4.js';
import '../../chunk-6DO4PE3O.js';
import '../../chunk-DD3CCMCZ.js';
import '../../chunk-M7WWRZ5Z.js';
import '../../chunk-E6NSKXYN.js';
import '../../chunk-2IFYDILW.js';
import '../../chunk-Q7DJKLEN.js';
import '../../chunk-HENXLGVD.js';
import '../../chunk-I3CFGE3N.js';
import '../../chunk-RNP5R5I3.js';
import '../../chunk-W2SFTXMT.js';
import { PAGE_SIZE_DEFAULT, formatTimeAgo } from '../../chunk-XOPLS4S6.js';
import '../../chunk-FVOMKZ7S.js';
import '../../chunk-KRWALB24.js';
import '../../chunk-2FTX4WO2.js';
import '../../chunk-MQZE7SUI.js';
import { UuidSchema } from '../../chunk-TVTSASST.js';
import '../../chunk-BRJ3QZ4E.js';
import '../../chunk-I2KLQ2HA.js';
import { Badge, SimpleGrid, Paper, Stack, Table, Title, TextInput, Select, Group, Button, Text, Alert, Center, Loader, Pagination } from '@mantine/core';
import { jsx, jsxs } from 'react/jsx-runtime';
import { IconUsers, IconCircleCheck, IconRocket, IconBriefcase, IconAlertTriangle, IconPlus, IconSearch, IconInbox, IconCash, IconUser, IconBuilding, IconArrowLeft, IconEdit, IconRefresh, IconTrash } from '@tabler/icons-react';
import { z } from 'zod';
import { useForm } from '@mantine/form';
import { zod4Resolver } from 'mantine-form-zod-resolver';
import { useEffect, useState } from 'react';
import { useDisclosure, useDebouncedValue } from '@mantine/hooks';
import { useNavigate } from '@tanstack/react-router';

// src/features/clients/_shared.ts
var CLIENT_STATUS_COLORS = {
  active: "green",
  onboarding: "blue",
  paused: "yellow",
  completed: "gray",
  churned: "red"
};
function formatClientStatusLabel(status) {
  return status.charAt(0).toUpperCase() + status.slice(1);
}
var CLIENT_SOURCE_OPTIONS = [
  { value: "word_of_mouth", label: "Word of mouth" },
  { value: "acquisition", label: "Acquisition" },
  { value: "referral", label: "Referral" },
  { value: "partner", label: "Partner" },
  { value: "manual", label: "Manual" }
];
function formatClientSourceLabel(source) {
  return source.split("_").filter(Boolean).map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join(" ");
}
function ClientStatusBadge({ status }) {
  return /* @__PURE__ */ jsx(Badge, { variant: "light", color: CLIENT_STATUS_COLORS[status] ?? "gray", size: "sm", children: formatClientStatusLabel(status) });
}
var ClientStatusSchema = z.enum(["active", "onboarding", "paused", "completed", "churned"]);
var ClientSourceSchema = z.string().trim().min(1).max(64).regex(/^[a-z][a-z0-9_]*$/, "Source must use lowercase letters, numbers, and underscores");
z.object({
  clientId: UuidSchema
}).strict();
z.object({
  status: ClientStatusSchema.optional(),
  source: ClientSourceSchema.optional(),
  search: z.string().trim().min(1).max(255).optional(),
  limit: z.coerce.number().int().min(1).max(100).default(50),
  offset: z.coerce.number().int().min(0).default(0)
}).strict();
z.object({
  id: z.string(),
  name: z.string(),
  status: ClientStatusSchema
});
var ClientResponseSchema = z.object({
  id: z.string(),
  organizationId: z.string(),
  name: z.string(),
  status: ClientStatusSchema,
  source: ClientSourceSchema,
  sourceDealId: z.string().nullable(),
  primaryCompanyId: z.string().nullable(),
  primaryContactId: z.string().nullable(),
  convertedAt: z.string().nullable(),
  metadata: z.record(z.string(), z.unknown()),
  createdAt: z.string(),
  updatedAt: z.string()
});
var ClientDealRefSchema = z.object({
  id: z.string(),
  contactEmail: z.string(),
  stageKey: z.string().nullable(),
  stateKey: z.string().nullable(),
  updatedAt: z.string()
});
var ClientProjectRefSchema = z.object({
  id: z.string(),
  name: z.string(),
  kind: z.string(),
  status: z.string(),
  updatedAt: z.string()
});
var ClientCompanyRefSchema = z.object({
  id: z.string(),
  name: z.string(),
  domain: z.string().nullable(),
  status: z.string()
});
var ClientContactRefSchema = z.object({
  id: z.string(),
  email: z.string(),
  firstName: z.string().nullable(),
  lastName: z.string().nullable(),
  title: z.string().nullable(),
  companyId: z.string().nullable(),
  status: z.string()
});
var ClientLineageSchema = z.object({
  deals: z.array(ClientDealRefSchema),
  projects: z.array(ClientProjectRefSchema),
  companies: z.array(ClientCompanyRefSchema),
  contacts: z.array(ClientContactRefSchema)
});
ClientResponseSchema.extend({
  lineage: ClientLineageSchema
});
z.object({
  data: z.array(ClientResponseSchema),
  total: z.number().int().min(0),
  limit: z.number().int().min(1),
  offset: z.number().int().min(0)
});
z.object({
  totalClients: z.number().int().min(0),
  byStatus: z.record(ClientStatusSchema, z.number().int().min(0)),
  linkedDeals: z.number().int().min(0),
  linkedProjects: z.number().int().min(0),
  linkedCompanies: z.number().int().min(0),
  linkedContacts: z.number().int().min(0)
});
var CreateClientRequestSchema = z.object({
  name: z.string().trim().min(1).max(255),
  status: ClientStatusSchema.optional(),
  source: ClientSourceSchema.optional(),
  sourceDealId: UuidSchema.nullable().optional(),
  primaryCompanyId: UuidSchema.nullable().optional(),
  primaryContactId: UuidSchema.nullable().optional(),
  metadata: z.record(z.string(), z.unknown()).nullable().optional()
}).strict();
z.object({
  name: z.string().trim().min(1).max(255).optional(),
  status: ClientStatusSchema.optional(),
  source: ClientSourceSchema.optional(),
  sourceDealId: UuidSchema.nullable().optional(),
  primaryCompanyId: UuidSchema.nullable().optional(),
  primaryContactId: UuidSchema.nullable().optional(),
  metadata: z.record(z.string(), z.unknown()).nullable().optional()
}).strict().refine((data) => Object.keys(data).length > 0, {
  message: "At least one field must be provided"
});
function ClientsMetricsStrip() {
  const { data, isLoading } = useClientStatus();
  return /* @__PURE__ */ jsxs(SimpleGrid, { cols: { base: 2, sm: 4 }, children: [
    /* @__PURE__ */ jsx(
      StatCard,
      {
        variant: "hero",
        icon: IconUsers,
        value: String(data?.totalClients ?? 0),
        label: "Total Clients",
        isLoading
      }
    ),
    /* @__PURE__ */ jsx(
      StatCard,
      {
        variant: "hero",
        icon: IconCircleCheck,
        value: String(data?.byStatus?.active ?? 0),
        label: "Active",
        isLoading
      }
    ),
    /* @__PURE__ */ jsx(
      StatCard,
      {
        variant: "hero",
        icon: IconRocket,
        value: String(data?.byStatus?.onboarding ?? 0),
        label: "Onboarding",
        isLoading
      }
    ),
    /* @__PURE__ */ jsx(
      StatCard,
      {
        variant: "hero",
        icon: IconBriefcase,
        value: String(data?.linkedProjects ?? 0),
        label: "Linked Projects",
        isLoading
      }
    )
  ] });
}
function ClientLineageSection({
  title,
  icon,
  rows,
  columns,
  emptyText,
  emptyIcon,
  rowKey,
  onRowClick
}) {
  return /* @__PURE__ */ jsx(Paper, { withBorder: true, children: /* @__PURE__ */ jsxs(Stack, { gap: "md", children: [
    /* @__PURE__ */ jsx(CardHeader, { icon, title, mb: 0 }),
    rows.length === 0 ? /* @__PURE__ */ jsx(EmptyState, { icon: emptyIcon, title: emptyText }) : /* @__PURE__ */ jsxs(Table, { children: [
      /* @__PURE__ */ jsx(Table.Thead, { children: /* @__PURE__ */ jsx(Table.Tr, { children: columns.map((c) => /* @__PURE__ */ jsx(Table.Th, { children: c.header }, c.header)) }) }),
      /* @__PURE__ */ jsx(Table.Tbody, { children: rows.map((row) => /* @__PURE__ */ jsx(
        Table.Tr,
        {
          style: onRowClick ? { cursor: "pointer" } : void 0,
          onClick: onRowClick ? () => onRowClick(row) : void 0,
          children: columns.map((c) => /* @__PURE__ */ jsx(Table.Td, { children: c.render(row) }, c.header))
        },
        rowKey(row)
      )) })
    ] })
  ] }) });
}
var STATUS_OPTIONS = [
  { value: "active", label: "Active" },
  { value: "onboarding", label: "Onboarding" },
  { value: "paused", label: "Paused" },
  { value: "completed", label: "Completed" },
  { value: "churned", label: "Churned" }
];
function CreateClientModal({ opened, onClose }) {
  const createClient = useCreateClient();
  const form = useForm({
    initialValues: {
      name: "",
      status: "onboarding",
      source: "word_of_mouth"
    },
    validate: zod4Resolver(CreateClientRequestSchema)
  });
  const handleSubmit = async (values) => {
    try {
      await createClient.mutateAsync(values);
      form.reset();
      onClose();
    } catch (error) {
      showApiErrorNotification(error);
    }
  };
  const handleClose = () => {
    if (!createClient.isPending) {
      form.reset();
      onClose();
    }
  };
  return /* @__PURE__ */ jsx(CustomModal, { opened, onClose: handleClose, size: "md", loading: createClient.isPending, children: /* @__PURE__ */ jsx("form", { onSubmit: form.onSubmit(handleSubmit), children: /* @__PURE__ */ jsxs(Stack, { p: "md", children: [
    /* @__PURE__ */ jsx(Title, { order: 3, children: "New Client" }),
    /* @__PURE__ */ jsx(
      TextInput,
      {
        label: "Name",
        placeholder: "Enter client name",
        required: true,
        ...form.getInputProps("name"),
        disabled: createClient.isPending
      }
    ),
    /* @__PURE__ */ jsx(
      Select,
      {
        label: "Status",
        placeholder: "Select status",
        data: STATUS_OPTIONS,
        ...form.getInputProps("status"),
        disabled: createClient.isPending
      }
    ),
    /* @__PURE__ */ jsx(
      Select,
      {
        label: "Source",
        placeholder: "Select source",
        data: CLIENT_SOURCE_OPTIONS,
        required: true,
        value: form.values.source ?? null,
        onChange: (value) => form.setFieldValue("source", value ?? "word_of_mouth"),
        error: form.errors.source,
        disabled: createClient.isPending
      }
    ),
    /* @__PURE__ */ jsxs(Group, { justify: "space-between", mt: "xs", children: [
      /* @__PURE__ */ jsx(Button, { variant: "light", onClick: handleClose, disabled: createClient.isPending, children: "Cancel" }),
      /* @__PURE__ */ jsx(Button, { type: "submit", loading: createClient.isPending, children: "Create Client" })
    ] })
  ] }) }) });
}
var EditClientSchema = z.object({
  name: z.string().trim().min(1).max(255),
  source: ClientSourceSchema
});
function EditClientNameModal({ opened, onClose, clientId, currentName, currentSource }) {
  const updateClient = useUpdateClient();
  const form = useForm({
    initialValues: { name: currentName, source: currentSource },
    validate: zod4Resolver(EditClientSchema)
  });
  useEffect(() => {
    if (opened) {
      form.setValues({ name: currentName, source: currentSource });
    }
  }, [opened, currentName, currentSource]);
  const handleSubmit = async (values) => {
    try {
      await updateClient.mutateAsync({ clientId, updates: { name: values.name, source: values.source } });
      onClose();
    } catch (error) {
      showApiErrorNotification(error);
    }
  };
  const handleClose = () => {
    if (!updateClient.isPending) {
      form.reset();
      onClose();
    }
  };
  return /* @__PURE__ */ jsx(CustomModal, { opened, onClose: handleClose, size: "sm", loading: updateClient.isPending, children: /* @__PURE__ */ jsx("form", { onSubmit: form.onSubmit(handleSubmit), children: /* @__PURE__ */ jsxs(Stack, { p: "md", children: [
    /* @__PURE__ */ jsx(Title, { order: 4, children: "Edit Client" }),
    /* @__PURE__ */ jsx(
      TextInput,
      {
        label: "Name",
        placeholder: "Enter client name",
        required: true,
        ...form.getInputProps("name"),
        disabled: updateClient.isPending
      }
    ),
    /* @__PURE__ */ jsx(
      Select,
      {
        label: "Source",
        data: CLIENT_SOURCE_OPTIONS,
        required: true,
        value: form.values.source,
        onChange: (value) => form.setFieldValue("source", value ?? currentSource),
        error: form.errors.source,
        disabled: updateClient.isPending
      }
    ),
    /* @__PURE__ */ jsxs(Group, { justify: "space-between", mt: "xs", children: [
      /* @__PURE__ */ jsx(Button, { variant: "light", onClick: handleClose, disabled: updateClient.isPending, children: "Cancel" }),
      /* @__PURE__ */ jsx(Button, { type: "submit", loading: updateClient.isPending, children: "Save" })
    ] })
  ] }) }) });
}
var STATUS_OPTIONS2 = [
  { value: "active", label: "Active" },
  { value: "onboarding", label: "Onboarding" },
  { value: "paused", label: "Paused" },
  { value: "completed", label: "Completed" },
  { value: "churned", label: "Churned" }
];
function UpdateClientStatusModal({ opened, onClose, clientId, currentStatus }) {
  const updateClient = useUpdateClient();
  const form = useForm({
    initialValues: { status: currentStatus }
  });
  useEffect(() => {
    if (opened) {
      form.setValues({ status: currentStatus });
    }
  }, [opened, currentStatus]);
  const handleSubmit = async (values) => {
    try {
      await updateClient.mutateAsync({ clientId, updates: { status: values.status } });
      onClose();
    } catch (error) {
      showApiErrorNotification(error);
    }
  };
  const handleClose = () => {
    if (!updateClient.isPending) {
      onClose();
    }
  };
  return /* @__PURE__ */ jsx(CustomModal, { opened, onClose: handleClose, size: "sm", loading: updateClient.isPending, children: /* @__PURE__ */ jsx("form", { onSubmit: form.onSubmit(handleSubmit), children: /* @__PURE__ */ jsxs(Stack, { p: "md", children: [
    /* @__PURE__ */ jsx(Title, { order: 4, children: "Change Status" }),
    /* @__PURE__ */ jsxs(Text, { size: "sm", c: "dimmed", children: [
      "Current status: ",
      formatClientStatusLabel(currentStatus)
    ] }),
    /* @__PURE__ */ jsx(
      Select,
      {
        label: "New Status",
        data: STATUS_OPTIONS2,
        ...form.getInputProps("status"),
        disabled: updateClient.isPending
      }
    ),
    /* @__PURE__ */ jsxs(Group, { justify: "space-between", mt: "xs", children: [
      /* @__PURE__ */ jsx(Button, { variant: "light", onClick: handleClose, disabled: updateClient.isPending, children: "Cancel" }),
      /* @__PURE__ */ jsx(Button, { type: "submit", loading: updateClient.isPending, children: "Update Status" })
    ] })
  ] }) }) });
}
function DeleteClientConfirm({ opened, onClose, clientId, clientName, onDeleted }) {
  const deleteClient = useDeleteClient();
  const [inlineError, setInlineError] = useState(null);
  const handleConfirm = async () => {
    setInlineError(null);
    try {
      await deleteClient.mutateAsync(clientId);
      onClose();
      onDeleted?.();
    } catch (error) {
      const message = error instanceof Error ? error.message : "Failed to delete client";
      setInlineError(message);
    }
  };
  const handleClose = () => {
    if (!deleteClient.isPending) {
      setInlineError(null);
      onClose();
    }
  };
  return /* @__PURE__ */ jsx(CustomModal, { opened, onClose: handleClose, size: "sm", loading: deleteClient.isPending, children: /* @__PURE__ */ jsxs(Stack, { p: "md", children: [
    /* @__PURE__ */ jsx(Title, { order: 4, children: "Delete Client" }),
    /* @__PURE__ */ jsxs(Text, { size: "sm", children: [
      "Are you sure you want to delete ",
      /* @__PURE__ */ jsx("strong", { children: clientName }),
      "? This action cannot be undone."
    ] }),
    inlineError && /* @__PURE__ */ jsx(Alert, { icon: /* @__PURE__ */ jsx(IconAlertTriangle, { size: 16 }), color: "red", title: "Cannot delete client", children: inlineError }),
    /* @__PURE__ */ jsxs(Group, { justify: "space-between", mt: "xs", children: [
      /* @__PURE__ */ jsx(Button, { variant: "light", onClick: handleClose, disabled: deleteClient.isPending, children: "Cancel" }),
      /* @__PURE__ */ jsx(Button, { color: "red", onClick: handleConfirm, loading: deleteClient.isPending, children: "Delete" })
    ] })
  ] }) });
}
var STATUS_OPTIONS3 = [
  { value: "active", label: "Active" },
  { value: "onboarding", label: "Onboarding" },
  { value: "paused", label: "Paused" },
  { value: "completed", label: "Completed" },
  { value: "churned", label: "Churned" }
];
function ClientsListPage({ onClientClick } = {}) {
  const [statusFilter, setStatusFilter] = useState(null);
  const [sourceFilter, setSourceFilter] = useState(null);
  const [searchQuery, setSearchQuery] = useState("");
  const [createOpened, { open: openCreate, close: closeCreate }] = useDisclosure(false);
  const [debouncedSearch] = useDebouncedValue(searchQuery, 300);
  const pagination = usePaginationState(PAGE_SIZE_DEFAULT, [statusFilter, sourceFilter, debouncedSearch]);
  const { data, isLoading, error } = useClients({
    status: statusFilter ?? void 0,
    source: sourceFilter ?? void 0,
    search: debouncedSearch.trim() || void 0,
    limit: PAGE_SIZE_DEFAULT,
    offset: pagination.offset
  });
  const rows = data?.data ?? [];
  const total = data?.total ?? 0;
  return /* @__PURE__ */ jsxs(SubshellContentContainer, { children: [
    /* @__PURE__ */ jsx(PageContainer, { children: /* @__PURE__ */ jsxs(Stack, { children: [
      /* @__PURE__ */ jsx(
        PageTitleCaption,
        {
          title: "Clients",
          caption: "Direct clients, converted deals, and ongoing engagements",
          rightSection: /* @__PURE__ */ jsx(Button, { variant: "filled", size: "sm", leftSection: /* @__PURE__ */ jsx(IconPlus, { size: 16 }), onClick: openCreate, children: "New Client" })
        }
      ),
      /* @__PURE__ */ jsx(ClientsMetricsStrip, {}),
      /* @__PURE__ */ jsx(Paper, { withBorder: true, children: /* @__PURE__ */ jsxs(Stack, { children: [
        /* @__PURE__ */ jsxs(FilterBar, { children: [
          /* @__PURE__ */ jsx(
            Select,
            {
              placeholder: "All Statuses",
              data: STATUS_OPTIONS3,
              value: statusFilter,
              onChange: (v) => setStatusFilter(v),
              clearable: true,
              size: "sm",
              style: { minWidth: 180 }
            }
          ),
          /* @__PURE__ */ jsx(
            Select,
            {
              placeholder: "All Sources",
              data: CLIENT_SOURCE_OPTIONS,
              value: sourceFilter,
              onChange: (v) => setSourceFilter(v),
              clearable: true,
              size: "sm",
              style: { minWidth: 180 }
            }
          ),
          /* @__PURE__ */ jsx(
            TextInput,
            {
              placeholder: "Search clients...",
              leftSection: /* @__PURE__ */ jsx(IconSearch, { size: 16 }),
              value: searchQuery,
              onChange: (e) => setSearchQuery(e.currentTarget.value),
              size: "sm",
              style: { minWidth: 250 }
            }
          )
        ] }),
        isLoading ? /* @__PURE__ */ jsx(Center, { p: "xl", children: /* @__PURE__ */ jsx(Loader, {}) }) : error ? /* @__PURE__ */ jsx(CenteredErrorState, { error, title: "Failed to load clients" }) : !rows.length ? /* @__PURE__ */ jsx(
          EmptyState,
          {
            icon: IconUsers,
            title: "No clients found",
            description: "Create a direct client or convert a closed-won deal."
          }
        ) : /* @__PURE__ */ jsxs(Table, { children: [
          /* @__PURE__ */ jsx(Table.Thead, { children: /* @__PURE__ */ jsxs(Table.Tr, { children: [
            /* @__PURE__ */ jsx(Table.Th, { children: "Name" }),
            /* @__PURE__ */ jsx(Table.Th, { children: "Status" }),
            /* @__PURE__ */ jsx(Table.Th, { children: "Source" }),
            /* @__PURE__ */ jsx(Table.Th, { children: "Converted" }),
            /* @__PURE__ */ jsx(Table.Th, { children: "Updated" })
          ] }) }),
          /* @__PURE__ */ jsx(Table.Tbody, { children: rows.map((client) => {
            const rowProps = onClientClick ? {
              style: { cursor: "pointer" },
              onClick: () => onClientClick(client.id)
            } : void 0;
            return /* @__PURE__ */ jsxs(Table.Tr, { ...rowProps, children: [
              /* @__PURE__ */ jsx(Table.Td, { children: /* @__PURE__ */ jsx(Text, { fw: 500, children: client.name }) }),
              /* @__PURE__ */ jsx(Table.Td, { children: /* @__PURE__ */ jsx(ClientStatusBadge, { status: client.status }) }),
              /* @__PURE__ */ jsx(Table.Td, { children: /* @__PURE__ */ jsx(Text, { size: "sm", c: "dimmed", children: formatClientSourceLabel(client.source) }) }),
              /* @__PURE__ */ jsx(Table.Td, { children: /* @__PURE__ */ jsx(Text, { size: "sm", c: "dimmed", children: formatTimeAgo(client.convertedAt) }) }),
              /* @__PURE__ */ jsx(Table.Td, { children: /* @__PURE__ */ jsx(Text, { size: "sm", c: "dimmed", children: formatTimeAgo(client.updatedAt) }) })
            ] }, client.id);
          }) })
        ] }),
        total > PAGE_SIZE_DEFAULT && /* @__PURE__ */ jsx(Group, { justify: "center", children: /* @__PURE__ */ jsx(
          Pagination,
          {
            value: pagination.page,
            onChange: pagination.setPage,
            total: pagination.totalPages(total),
            size: "sm"
          }
        ) })
      ] }) })
    ] }) }),
    /* @__PURE__ */ jsx(CreateClientModal, { opened: createOpened, onClose: closeCreate })
  ] });
}
function DetailRow({ label, value }) {
  return /* @__PURE__ */ jsxs(Group, { gap: "xs", align: "flex-start", wrap: "nowrap", children: [
    /* @__PURE__ */ jsx(Text, { size: "sm", fw: 500, style: { width: 140, flexShrink: 0 }, children: label }),
    /* @__PURE__ */ jsx(Text, { size: "sm", style: { minWidth: 0, wordBreak: "break-word", color: "var(--color-text-subtle)" }, children: value ?? "N/A" })
  ] });
}
function ClientDetailPage({ clientId }) {
  const navigate = useNavigate();
  const { data: client, isLoading, error } = useClient(clientId);
  const [editNameOpened, { open: openEditName, close: closeEditName }] = useDisclosure(false);
  const [updateStatusOpened, { open: openUpdateStatus, close: closeUpdateStatus }] = useDisclosure(false);
  const [deleteOpened, { open: openDelete, close: closeDelete }] = useDisclosure(false);
  const backButton = /* @__PURE__ */ jsx(
    Button,
    {
      variant: "light",
      size: "sm",
      leftSection: /* @__PURE__ */ jsx(IconArrowLeft, { size: 16 }),
      onClick: () => navigate({ to: "/clients" }),
      children: "Clients"
    }
  );
  const headerActions = /* @__PURE__ */ jsxs(Group, { gap: "xs", children: [
    /* @__PURE__ */ jsx(Button, { variant: "light", size: "sm", leftSection: /* @__PURE__ */ jsx(IconEdit, { size: 16 }), onClick: openEditName, children: "Edit name" }),
    /* @__PURE__ */ jsx(Button, { variant: "light", size: "sm", leftSection: /* @__PURE__ */ jsx(IconRefresh, { size: 16 }), onClick: openUpdateStatus, children: "Change status" }),
    /* @__PURE__ */ jsx(Button, { variant: "light", size: "sm", color: "red", leftSection: /* @__PURE__ */ jsx(IconTrash, { size: 16 }), onClick: openDelete, children: "Delete" }),
    backButton
  ] });
  if (isLoading) {
    return /* @__PURE__ */ jsx(SubshellContentContainer, { children: /* @__PURE__ */ jsx(PageContainer, { children: /* @__PURE__ */ jsxs(Stack, { gap: "md", children: [
      /* @__PURE__ */ jsx(PageTitleCaption, { title: "Client Detail", caption: "Loading client details...", rightSection: backButton }),
      /* @__PURE__ */ jsx(Paper, { withBorder: true, children: /* @__PURE__ */ jsx(Center, { p: "xl", children: /* @__PURE__ */ jsx(Loader, {}) }) })
    ] }) }) });
  }
  if (error) {
    return /* @__PURE__ */ jsx(SubshellContentContainer, { children: /* @__PURE__ */ jsx(PageContainer, { children: /* @__PURE__ */ jsxs(Stack, { gap: "md", children: [
      /* @__PURE__ */ jsx(PageTitleCaption, { title: "Client Detail", caption: "Unable to load client details", rightSection: backButton }),
      /* @__PURE__ */ jsx(Paper, { withBorder: true, children: /* @__PURE__ */ jsx(CenteredErrorState, { error, title: "Failed to load client" }) })
    ] }) }) });
  }
  if (!client) {
    return /* @__PURE__ */ jsx(SubshellContentContainer, { children: /* @__PURE__ */ jsx(PageContainer, { children: /* @__PURE__ */ jsxs(Stack, { gap: "md", children: [
      /* @__PURE__ */ jsx(PageTitleCaption, { title: "Client Detail", caption: "Client not found", rightSection: backButton }),
      /* @__PURE__ */ jsx(Paper, { withBorder: true, children: /* @__PURE__ */ jsx(
        EmptyState,
        {
          icon: IconInbox,
          title: "Client not found",
          description: "The selected client no longer exists."
        }
      ) })
    ] }) }) });
  }
  const caption = client.convertedAt ? `Converted ${formatTimeAgo(client.convertedAt)}` : `${formatClientSourceLabel(client.source)} client`;
  return /* @__PURE__ */ jsxs(SubshellContentContainer, { children: [
    /* @__PURE__ */ jsx(PageContainer, { children: /* @__PURE__ */ jsxs(Stack, { gap: "md", children: [
      /* @__PURE__ */ jsx(PageTitleCaption, { title: client.name, caption, rightSection: headerActions }),
      /* @__PURE__ */ jsx(Paper, { withBorder: true, children: /* @__PURE__ */ jsxs(Stack, { gap: "md", children: [
        /* @__PURE__ */ jsx(CardHeader, { icon: /* @__PURE__ */ jsx(IconUsers, { size: 18 }), title: "Client", mb: 0 }),
        /* @__PURE__ */ jsxs(SimpleGrid, { cols: { base: 1, sm: 2 }, spacing: "sm", children: [
          /* @__PURE__ */ jsx(DetailRow, { label: "Status", value: /* @__PURE__ */ jsx(ClientStatusBadge, { status: client.status }) }),
          /* @__PURE__ */ jsx(DetailRow, { label: "Source", value: formatClientSourceLabel(client.source) }),
          /* @__PURE__ */ jsx(
            DetailRow,
            {
              label: "Converted",
              value: client.convertedAt ? new Date(client.convertedAt).toLocaleDateString() : "N/A"
            }
          ),
          /* @__PURE__ */ jsx(
            DetailRow,
            {
              label: "Source Deal",
              value: client.sourceDealId ? /* @__PURE__ */ jsx(
                Text,
                {
                  size: "sm",
                  style: { cursor: "pointer", color: "var(--color-primary)" },
                  onClick: () => navigate({ to: "/crm/deals/$dealId", params: { dealId: client.sourceDealId } }),
                  children: client.sourceDealId
                }
              ) : "N/A"
            }
          ),
          /* @__PURE__ */ jsx(DetailRow, { label: "Primary Company", value: client.primaryCompanyId ?? "N/A" }),
          /* @__PURE__ */ jsx(DetailRow, { label: "Primary Contact", value: client.primaryContactId ?? "N/A" }),
          /* @__PURE__ */ jsx(DetailRow, { label: "Created", value: new Date(client.createdAt).toLocaleDateString() }),
          /* @__PURE__ */ jsx(DetailRow, { label: "Updated", value: formatTimeAgo(client.updatedAt) })
        ] })
      ] }) }),
      /* @__PURE__ */ jsx(
        ClientLineageSection,
        {
          title: "Projects",
          icon: /* @__PURE__ */ jsx(IconBriefcase, { size: 18 }),
          rows: client.lineage.projects,
          emptyText: "No projects yet",
          emptyIcon: IconBriefcase,
          rowKey: (row) => row.id,
          onRowClick: (row) => navigate({ to: "/projects/$projectId", params: { projectId: row.id } }),
          columns: [
            { header: "Name", render: (row) => row.name },
            { header: "Kind", render: (row) => row.kind },
            { header: "Status", render: (row) => row.status },
            { header: "Updated", render: (row) => formatTimeAgo(row.updatedAt) }
          ]
        }
      ),
      /* @__PURE__ */ jsx(
        ClientLineageSection,
        {
          title: "Deals",
          icon: /* @__PURE__ */ jsx(IconCash, { size: 18 }),
          rows: client.lineage.deals,
          emptyText: "No linked deals",
          emptyIcon: IconCash,
          rowKey: (row) => row.id,
          onRowClick: (row) => navigate({ to: "/crm/deals/$dealId", params: { dealId: row.id } }),
          columns: [
            { header: "Contact Email", render: (row) => row.contactEmail },
            { header: "Stage", render: (row) => row.stageKey ?? "\u2014" },
            { header: "State", render: (row) => row.stateKey ?? "\u2014" },
            { header: "Updated", render: (row) => formatTimeAgo(row.updatedAt) }
          ]
        }
      ),
      /* @__PURE__ */ jsx(
        ClientLineageSection,
        {
          title: "Contacts",
          icon: /* @__PURE__ */ jsx(IconUser, { size: 18 }),
          rows: client.lineage.contacts,
          emptyText: "No contacts",
          emptyIcon: IconUser,
          rowKey: (row) => row.id,
          onRowClick: (row) => navigate({ to: "/crm/contacts/$contactId", params: { contactId: row.id } }),
          columns: [
            {
              header: "Name",
              render: (row) => [row.firstName, row.lastName].filter(Boolean).join(" ") || "\u2014"
            },
            { header: "Email", render: (row) => row.email },
            { header: "Title", render: (row) => row.title ?? "\u2014" },
            { header: "Status", render: (row) => row.status }
          ]
        }
      ),
      /* @__PURE__ */ jsx(
        ClientLineageSection,
        {
          title: "Companies",
          icon: /* @__PURE__ */ jsx(IconBuilding, { size: 18 }),
          rows: client.lineage.companies,
          emptyText: "No companies",
          emptyIcon: IconBuilding,
          rowKey: (row) => row.id,
          onRowClick: (row) => navigate({ to: "/crm/companies/$companyId", params: { companyId: row.id } }),
          columns: [
            { header: "Name", render: (row) => row.name },
            { header: "Domain", render: (row) => row.domain ?? "\u2014" },
            { header: "Status", render: (row) => row.status }
          ]
        }
      )
    ] }) }),
    /* @__PURE__ */ jsx(
      EditClientNameModal,
      {
        opened: editNameOpened,
        onClose: closeEditName,
        clientId,
        currentName: client.name,
        currentSource: client.source
      }
    ),
    /* @__PURE__ */ jsx(
      UpdateClientStatusModal,
      {
        opened: updateStatusOpened,
        onClose: closeUpdateStatus,
        clientId,
        currentStatus: client.status
      }
    ),
    /* @__PURE__ */ jsx(
      DeleteClientConfirm,
      {
        opened: deleteOpened,
        onClose: closeDelete,
        clientId,
        clientName: client.name,
        onDeleted: () => navigate({ to: "/clients" })
      }
    )
  ] });
}

export { CLIENT_STATUS_COLORS, ClientDetailPage, ClientLineageSection, ClientStatusBadge, ClientsListPage, ClientsMetricsStrip, CreateClientModal, DeleteClientConfirm, EditClientNameModal, UpdateClientStatusModal, formatClientStatusLabel };
