"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { Phone, Mail, Trash2, Building2, Globe, Pencil, MapPin } from "lucide-react";
import { useQueryClient } from "@tanstack/react-query";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { Avatar } from "@open-mercato/ui/primitives/avatar";
import { Button } from "@open-mercato/ui/primitives/button";
import { IconButton } from "@open-mercato/ui/primitives/icon-button";
import { Badge } from "@open-mercato/ui/primitives/badge";
import { SendObjectMessageDialog } from "@open-mercato/ui/backend/messages";
import { CompanyTagsDialog } from "./CompanyTagsDialog.js";
import { ObjectHistoryButton } from "./ObjectHistoryButton.js";
import { invalidateCustomerDictionary, useCustomerDictionary } from "./hooks/useCustomerDictionary.js";
import { renderDictionaryIcon } from "../../../dictionaries/components/dictionaryAppearance.js";
import { formatFallbackLabel } from "./utils.js";
const HEADER_ICON_BUTTON_CLASS = "size-8 rounded-md";
function CompanyDictionaryBadge({ value, map }) {
  const entry = map?.[value];
  const color = entry?.color ?? null;
  const icon = entry?.icon ?? null;
  const label = entry?.label ?? formatFallbackLabel(value);
  const colorStyle = color ? { color, borderColor: color, backgroundColor: `${color}1A` } : void 0;
  return /* @__PURE__ */ jsxs(Badge, { variant: "outline", className: "rounded-sm gap-1.5 text-xs font-medium", style: colorStyle, children: [
    icon ? renderDictionaryIcon(icon, "size-2.5") : null,
    label
  ] });
}
function CompanyDetailHeader({
  data,
  onTagsChange,
  tagsSectionControllerRef,
  onSave,
  onDelete,
  isDirty,
  isSaving,
  onFocusField,
  onDataReload
}) {
  const t = useT();
  const queryClient = useQueryClient();
  const [manageTagsOpen, setManageTagsOpen] = React.useState(false);
  const company = data.company;
  const profile = data.profile;
  const displayName = company.displayName || t("customers.companies.detail.untitled", "Untitled");
  const visibleCustomTags = React.useMemo(
    () => data.tags?.filter((tag) => !["status", "lifecycle_stage", "source"].includes(tag.id)).slice(0, 6) ?? [],
    [data.tags]
  );
  const hiddenCustomTagsCount = Math.max(
    0,
    (data.tags?.filter((tag) => !["status", "lifecycle_stage", "source"].includes(tag.id)).length ?? 0) - visibleCustomTags.length
  );
  const industryLabel = profile?.industry ?? null;
  const sizeLabel = profile?.sizeBucket ?? null;
  const subtitle = [industryLabel, sizeLabel ? t("customers.companies.detail.header.employees", "{count} employees", { count: sizeLabel }) : null].filter(Boolean).join(" \xB7 ");
  const primaryAddress = React.useMemo(() => {
    const addresses = data.addresses;
    if (!addresses || !Array.isArray(addresses)) return null;
    return addresses.find((a) => a.isPrimary) ?? addresses[0] ?? null;
  }, [data]);
  const locationText = React.useMemo(() => {
    if (!primaryAddress) return null;
    return [primaryAddress.city, primaryAddress.region, primaryAddress.postalCode].filter(Boolean).join(", ");
  }, [primaryAddress]);
  const companyOrgId = company.organizationId ?? null;
  const { data: statusDict } = useCustomerDictionary("statuses", 0, companyOrgId);
  const { data: lifecycleDict } = useCustomerDictionary("lifecycle-stages", 0, companyOrgId);
  const { data: sourceDict } = useCustomerDictionary("sources", 0, companyOrgId);
  const { data: temperatureDict } = useCustomerDictionary("temperature", 0, companyOrgId);
  const { data: renewalQuarterDict } = useCustomerDictionary("renewal-quarters", 0, companyOrgId);
  return /* @__PURE__ */ jsxs("div", { className: "rounded-lg border bg-card", children: [
    /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-4 px-6 pt-6 pb-3 sm:flex-row sm:items-start sm:gap-5", children: [
      /* @__PURE__ */ jsx(
        Avatar,
        {
          label: "",
          icon: /* @__PURE__ */ jsx(Building2, {}),
          size: "xl",
          variant: "monochrome"
        }
      ),
      /* @__PURE__ */ jsxs("div", { className: "min-w-0 flex-1", children: [
        /* @__PURE__ */ jsx("h1", { className: "truncate text-2xl font-bold text-foreground", children: displayName }),
        subtitle && /* @__PURE__ */ jsx("p", { className: "mt-0.5 text-sm text-muted-foreground", children: subtitle }),
        /* @__PURE__ */ jsxs("div", { className: "mt-1.5 flex flex-wrap items-center gap-x-5 gap-y-1 text-sm text-muted-foreground", children: [
          company.primaryPhone && /* @__PURE__ */ jsxs("span", { className: "inline-flex items-center gap-1.5", children: [
            /* @__PURE__ */ jsx(Phone, { className: "size-3.5" }),
            /* @__PURE__ */ jsx("a", { href: `tel:${company.primaryPhone}`, className: "hover:text-foreground", children: company.primaryPhone })
          ] }),
          company.primaryEmail && /* @__PURE__ */ jsxs("span", { className: "inline-flex items-center gap-1.5", children: [
            /* @__PURE__ */ jsx(Mail, { className: "size-3.5" }),
            /* @__PURE__ */ jsx("a", { href: `mailto:${company.primaryEmail}`, className: "hover:text-foreground", children: company.primaryEmail })
          ] }),
          profile?.websiteUrl && /* @__PURE__ */ jsxs("a", { href: profile.websiteUrl.startsWith("http") ? profile.websiteUrl : `https://${profile.websiteUrl}`, target: "_blank", rel: "noreferrer", className: "inline-flex items-center gap-1.5 hover:text-foreground", children: [
            /* @__PURE__ */ jsx(Globe, { className: "size-3.5" }),
            profile.websiteUrl
          ] }),
          locationText && /* @__PURE__ */ jsxs("span", { className: "inline-flex items-center gap-1.5", children: [
            /* @__PURE__ */ jsx(MapPin, { className: "size-3.5" }),
            locationText
          ] })
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "mt-2.5 flex flex-wrap items-center gap-1.5", children: [
          company.status && /* @__PURE__ */ jsx(CompanyDictionaryBadge, { value: company.status, map: statusDict?.map }),
          company.lifecycleStage && /* @__PURE__ */ jsx(CompanyDictionaryBadge, { value: company.lifecycleStage, map: lifecycleDict?.map }),
          company.source && /* @__PURE__ */ jsx(CompanyDictionaryBadge, { value: company.source, map: sourceDict?.map }),
          company.temperature && /* @__PURE__ */ jsx(CompanyDictionaryBadge, { value: company.temperature, map: temperatureDict?.map }),
          company.renewalQuarter && /* @__PURE__ */ jsx(CompanyDictionaryBadge, { value: company.renewalQuarter, map: renewalQuarterDict?.map }),
          visibleCustomTags.map((tag) => {
            const colorStyle = tag.color ? { color: tag.color, borderColor: tag.color, backgroundColor: `${tag.color}1A` } : void 0;
            return /* @__PURE__ */ jsx(
              Badge,
              {
                variant: "outline",
                className: "rounded-sm gap-1.5 text-xs font-medium",
                style: colorStyle,
                children: tag.label
              },
              tag.id
            );
          }),
          hiddenCustomTagsCount > 0 ? /* @__PURE__ */ jsxs(Badge, { variant: "outline", className: "rounded-sm gap-1.5 text-xs font-medium", children: [
            "+",
            hiddenCustomTagsCount,
            " ",
            t("customers.companies.detail.header.more", "more")
          ] }) : null,
          /* @__PURE__ */ jsxs(
            Button,
            {
              type: "button",
              variant: "outline",
              size: "sm",
              className: "h-auto rounded-sm px-2 py-1 text-xs font-medium text-muted-foreground hover:text-foreground",
              onClick: () => setManageTagsOpen(true),
              children: [
                /* @__PURE__ */ jsx(Pencil, { className: "mr-1 size-3" }),
                t("customers.companies.detail.actions.manageTags", "Edit tags")
              ]
            }
          )
        ] })
      ] }),
      /* @__PURE__ */ jsx("div", { className: "flex w-full shrink-0 flex-col items-start gap-3 sm:w-auto sm:items-end", children: /* @__PURE__ */ jsxs("div", { className: "flex w-full flex-wrap items-center justify-start gap-2 sm:w-auto sm:justify-end", children: [
        /* @__PURE__ */ jsx(
          SendObjectMessageDialog,
          {
            object: {
              entityModule: "customers",
              entityType: "company",
              entityId: company.id,
              previewData: {
                title: displayName,
                subtitle: company.primaryEmail ?? profile?.websiteUrl ?? void 0
              }
            },
            viewHref: `/backend/customers/companies-v2/${company.id}`,
            buttonVariant: "outline",
            buttonSize: "icon",
            buttonClassName: HEADER_ICON_BUTTON_CLASS,
            buttonLabel: t("customers.companies.detail.actions.sendMessage", "Send message")
          }
        ),
        /* @__PURE__ */ jsx(
          ObjectHistoryButton,
          {
            resourceKind: "customers.company",
            resourceId: company.id,
            organizationId: company.organizationId ?? void 0
          }
        ),
        /* @__PURE__ */ jsx(
          IconButton,
          {
            variant: "outline",
            size: "sm",
            type: "button",
            "aria-label": t("customers.companies.detail.actions.delete", "Delete company"),
            onClick: () => {
              void onDelete();
            },
            children: /* @__PURE__ */ jsx(Trash2, { className: "size-4" })
          }
        ),
        /* @__PURE__ */ jsx(
          Button,
          {
            type: "button",
            size: "sm",
            onClick: onSave,
            disabled: !isDirty || isSaving,
            children: t("customers.companies.detail.actions.save", "Save")
          }
        )
      ] }) })
    ] }),
    /* @__PURE__ */ jsx(
      CompanyTagsDialog,
      {
        open: manageTagsOpen,
        onClose: () => setManageTagsOpen(false),
        entityId: company.id,
        companyOrganizationId: company.organizationId ?? null,
        companyData: {
          status: company.status,
          lifecycleStage: company.lifecycleStage,
          source: company.source,
          temperature: company.temperature,
          renewalQuarter: company.renewalQuarter,
          industry: profile?.industry ?? null,
          customFields: data.customFields,
          tags: data.tags
        },
        onSaved: () => {
          void invalidateCustomerDictionary(queryClient, "statuses");
          void invalidateCustomerDictionary(queryClient, "lifecycle-stages");
          void invalidateCustomerDictionary(queryClient, "sources");
          void invalidateCustomerDictionary(queryClient, "temperature");
          void invalidateCustomerDictionary(queryClient, "renewal-quarters");
          onDataReload?.();
        }
      }
    )
  ] });
}
export {
  CompanyDetailHeader
};
//# sourceMappingURL=CompanyDetailHeader.js.map
