"use client";

import { AlertCircle, ArrowRight, Ban, Calendar, Check, CreditCard, Heart, Mail, MapPin, MessageCircle, Package, Printer, ReceiptText, ShoppingBag, Star, ThumbsUp, User } from "lucide-react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import PagamentosPendentes from "@/components/client-portal/PagamentosPendentes";
import ClientPortalProfileForm from "@/components/ClientPortalProfileForm";
import ClientPortalFavoriteButton from "@/components/ClientPortalFavoriteButton";
import ClientAddressBook from "@/components/client-portal/ClientAddressBook";
import { getAccessibleAccent, getReadableTextColor } from "@/lib/color-contrast";
import {
  ClientPortalClient,
  ClientPortalOrder,
  ClientPortalPaymentReceipt,
  PremiumCard,
  formatDate,
  formatDateTime,
  formatMoney,
  getAddressSummary,
  getIncompleteProfileFields,
  getProfileCompletion,
  getStatusMeta,
  hexToRgba,
} from "@/components/client-portal/shared";

type SharedProps = {
  slug: string;
  primaryColor: string;
  client: ClientPortalClient;
  customerName: string;
  orders: ClientPortalOrder[];
  completion: number;
  totalSpent: number;
  latestOrder: ClientPortalOrder | null;
  onOpenSection: (section: "orders" | "account" | "addresses") => void;
  onAvatarChange?: (file: File) => void;
};

export function OverviewSection({
  slug,
  primaryColor,
  client,
  customerName,
  orders,
  completion,
  totalSpent,
  latestOrder,
  onOpenSection,
}: SharedProps) {
  const totalOrders = orders.length;
  const totalValue = totalSpent;
  const deliveryRate = totalOrders
    ? Math.round((orders.filter((item) => item.status === "delivered").length / totalOrders) * 100)
    : 0;
  const activeOrders = orders.filter((item) => item.status !== "delivered" && item.status !== "canceled").length;
  const profileSummary = completion >= 100 ? "Cadastro completo" : "Perfil em atualização";
  const addressSummary = getAddressSummary(client) || "Cadastre seu endereço para agilizar a entrega.";
  const latestStatus = latestOrder ? getStatusMeta(latestOrder.status, primaryColor) : null;
  const latestOrderDate = latestOrder ? formatDateTime(latestOrder.created_at) : "Você ainda não realizou pedidos.";
  const recentOrders = orders.slice(0, 4);

  return (
    <div className="space-y-6">
      <section className="border border-[#efedf2] bg-white">
        <div className="grid gap-0 xl:grid-cols-[minmax(0,1fr)_320px]">
          <div className="px-4 py-5 sm:px-7 sm:py-6">
            <div
              className="inline-flex items-center gap-2 rounded-[10px] px-3 py-1.5 text-[12px] font-semibold"
              style={{ backgroundColor: hexToRgba(primaryColor, 0.09), color: getAccessibleAccent(primaryColor) }}
            >
              <span className="h-1.5 w-1.5 rounded-full" style={{ backgroundColor: primaryColor, color: getReadableTextColor(primaryColor) }} />
              <span>{profileSummary}</span>
            </div>
            <h1 className="mt-4 text-[26px] font-semibold tracking-[-0.04em] text-zinc-950 sm:mt-5 sm:text-[30px]">{customerName}</h1>
            <p className="mt-2 max-w-[560px] text-[14px] leading-6 text-zinc-600">
              Acompanhe seus pedidos, revise seus dados e mantenha tudo organizado no portal do cliente.
            </p>
            <div className="mt-5 flex flex-col gap-3 sm:mt-6 sm:flex-row sm:flex-wrap">
              <Link
                href={`/${slug}`}
                className="inline-flex h-11 items-center gap-2 px-5 text-sm font-semibold text-white transition hover:opacity-90"
                style={{ backgroundColor: primaryColor, color: getReadableTextColor(primaryColor) }}
              >
                Comprar
                <ArrowRight className="h-4 w-4" />
              </Link>
              <button
                type="button"
                onClick={() => onOpenSection("orders")}
                className="inline-flex h-11 items-center border border-[#efedf2] px-5 text-sm font-semibold text-zinc-700 transition hover:bg-zinc-50 hover:text-zinc-950"
              >
                Ver pedidos
              </button>
            </div>
          </div>

          <div className="border-t border-[#efedf2] px-4 py-5 sm:px-7 sm:py-6 xl:border-l xl:border-t-0">
            <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-zinc-400">Último pedido</div>
            <div className="mt-3 text-[22px] font-semibold tracking-[-0.04em] text-zinc-950 sm:text-[24px]">
              {latestOrder ? `#${latestOrder.number}` : "--"}
            </div>
            <div className="mt-2 text-[13px] text-zinc-500">{latestOrderDate}</div>
            {latestOrder && latestStatus ? (
              <>
                <div
                  className="mt-4 inline-flex items-center gap-2 rounded-[10px] px-3 py-1.5 text-[12px] font-semibold"
                  style={{ backgroundColor: latestStatus.backgroundColor, color: latestStatus.color }}
                >
                  <span
                    className="h-1.5 w-1.5 rounded-full"
                    style={{ backgroundColor: latestStatus.color }}
                  />
                  <span>{latestStatus.label}</span>
                </div>
                <div className="mt-5 border-t border-[#efedf2] pt-4">
                  <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-zinc-400">Valor</div>
                  <div className="mt-2 text-[28px] font-semibold tracking-[-0.04em] text-zinc-950">
                    {formatMoney(latestOrder.total_amount)}
                  </div>
                </div>
              </>
            ) : (
              <div className="mt-5 border-t border-[#efedf2] pt-4 text-sm text-zinc-500">
                Seu histórico aparecerá aqui assim que o primeiro pedido for criado.
              </div>
            )}
          </div>
        </div>
      </section>

      <div className="grid grid-cols-2 gap-3 lg:grid-cols-4">
        <MetricCard label="Pedidos" value={String(totalOrders)} />
        <MetricCard label="Total" value={formatMoney(totalValue)} />
        <MetricCard label="Em andamento" value={String(activeOrders)} />
        <MetricCard label="Entrega" value={`${deliveryRate}%`} />
      </div>

      <div className="grid grid-cols-1 gap-5 xl:grid-cols-[minmax(0,1.35fr)_360px]">
        <section className="border border-[#efedf2] bg-white px-4 py-4 sm:px-6 sm:py-5">
          <div className="mb-4 flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between sm:gap-4">
            <h3 className="text-[15px] font-semibold text-zinc-950">Pedidos recentes</h3>
            <button
              type="button"
              onClick={() => onOpenSection("orders")}
              className="text-[13px] font-semibold transition hover:opacity-80"
              style={{ color: getAccessibleAccent(primaryColor) }}
            >
              Ver tudo
            </button>
          </div>

          <div className="space-y-0 border border-[#efedf2] bg-white">
            {recentOrders.map((order, index) => {
              const status = getStatusMeta(order.status, primaryColor);
              return (
                <button
                  key={order.id}
                  type="button"
                  onClick={() => onOpenSection("orders")}
                  className={`flex w-full flex-col items-start gap-3 px-4 py-4 text-left transition hover:bg-zinc-50 sm:flex-row sm:items-center sm:justify-between sm:gap-4 ${
                    index < recentOrders.length - 1 ? "border-b border-[#efedf2]" : ""
                  }`}
                >
                  <div className="min-w-0">
                    <div className="text-[14px] font-semibold text-zinc-950">Pedido #{order.number}</div>
                    <div className="mt-1 text-[12px] text-zinc-500">{formatDateTime(order.created_at)}</div>
                  </div>
                  <div className="flex w-full items-center justify-between gap-3 sm:w-auto sm:justify-end sm:gap-4">
                    <div className="text-left sm:text-right">
                      <div className="text-[11px] uppercase tracking-[0.16em] text-zinc-400">Total</div>
                      <div className="mt-1 text-[14px] font-semibold text-zinc-950">{formatMoney(order.total_amount)}</div>
                    </div>
                    <span
                      className="inline-flex items-center gap-2 rounded-[10px] px-3 py-1.5 text-[11px] font-semibold"
                      style={{ backgroundColor: status.backgroundColor, color: status.color }}
                    >
                      <span className="h-1.5 w-1.5 rounded-full" style={{ backgroundColor: status.color }} />
                      <span>{status.label}</span>
                    </span>
                  </div>
                </button>
              );
            })}
            {orders.length === 0 ? <div className="py-10 text-center text-sm text-zinc-500">Sem pedidos.</div> : null}
          </div>
        </section>

        <div className="grid gap-5">
          <section className="border border-[#efedf2] bg-white px-4 py-4 sm:px-6 sm:py-5">
            <div className="text-[15px] font-semibold text-zinc-950">Resumo da conta</div>
            <div className="mt-5 space-y-4">
              <div className="flex flex-col items-start justify-between gap-1 border-b border-[#efedf2] pb-4 sm:flex-row sm:items-center sm:gap-4">
                <span className="text-[13px] text-zinc-500">Cadastro</span>
                <span className="text-[13px] font-semibold text-zinc-950">{completion}% completo</span>
              </div>
              <div className="flex flex-col items-start justify-between gap-1 border-b border-[#efedf2] pb-4 sm:flex-row sm:items-center sm:gap-4">
                <span className="text-[13px] text-zinc-500">E-mail</span>
                <span className="text-right text-[13px] font-medium text-zinc-950">{client.email || "Não informado"}</span>
              </div>
              <div className="border-b border-[#efedf2] pb-4">
                <div className="text-[13px] text-zinc-500">Entrega</div>
                <div className="mt-2 text-[13px] leading-6 text-zinc-950">{addressSummary}</div>
              </div>
              <div className="flex flex-wrap gap-3 pt-1">
                <button
                  type="button"
                  onClick={() => onOpenSection("account")}
                  className="inline-flex h-10 items-center border border-[#efedf2] px-4 text-sm font-semibold text-zinc-700 transition hover:bg-zinc-50 hover:text-zinc-950"
                >
                  Editar perfil
                </button>
                <button
                  type="button"
                  onClick={() => onOpenSection("addresses")}
                  className="inline-flex h-10 items-center border border-[#efedf2] px-4 text-sm font-semibold text-zinc-700 transition hover:bg-zinc-50 hover:text-zinc-950"
                >
                  Entrega
                </button>
              </div>
            </div>
          </section>

          <section className="border border-[#efedf2] bg-white px-4 py-4 sm:px-6 sm:py-5">
            <div className="text-[15px] font-semibold text-zinc-950">Visão geral</div>
            <div className="mt-5 grid gap-4">
              <OverviewActionRow
                label="Último pedido"
                value={latestOrder ? `#${latestOrder.number}` : "--"}
              />
              <OverviewActionRow
                label="Status atual"
                value={latestStatus?.label || "Sem pedidos"}
                accentColor={latestStatus?.color || primaryColor}
              />
              <OverviewActionRow
                label="Taxa de entrega"
                value={`${deliveryRate}%`}
              />
            </div>
          </section>
        </div>
      </div>
    </div>
  );
}

function MetricCard({ label, value }: { label: string; value: string }) {
  return (
    <div className="border border-[#efedf2] bg-white px-4 py-4">
      <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-zinc-400">{label}</div>
      <div className="mt-2 truncate text-[20px] font-semibold tracking-[-0.04em] text-zinc-950 sm:text-[24px]">{value}</div>
    </div>
  );
}

function OverviewActionRow({
  label,
  value,
  accentColor,
}: {
  label: string;
  value: string;
  accentColor?: string;
}) {
  return (
    <div className="flex flex-col items-start justify-between gap-1 border-b border-[#efedf2] pb-4 last:border-b-0 last:pb-0 sm:flex-row sm:items-center sm:gap-4">
      <span className="text-[13px] text-zinc-500">{label}</span>
      <span className="max-w-full break-words text-left text-[13px] font-semibold sm:text-right" style={{ color: accentColor || "#18181b" }}>
        {value}
      </span>
    </div>
  );
}

function SupportActionTile({
  title,
  subtitle,
  icon: Icon,
  onClick,
  href,
  primaryColor,
  className = "",
}: {
  title: string;
  subtitle: string;
  icon: typeof Package;
  onClick?: () => void;
  href?: string;
  primaryColor?: string;
  className?: string;
}) {
  const content = (
    <>
      <Icon className="h-[18px] w-[18px] shrink-0" style={{ color: primaryColor || "#18181b" }} />
      <div className="min-w-0">
        <div className="break-words text-[14px] font-semibold text-zinc-950">{title}</div>
        <div className="mt-1 break-words text-[12px] leading-5 text-zinc-500">{subtitle}</div>
      </div>
    </>
  );

  if (href) {
    return (
      <a
        href={href}
        target={href.startsWith("http") ? "_blank" : undefined}
        rel={href.startsWith("http") ? "noreferrer" : undefined}
        className={`flex items-start gap-3 px-4 py-4 transition hover:bg-zinc-50 sm:px-5 sm:py-5 ${className}`}
      >
        {content}
      </a>
    );
  }

  return (
    <button
      type="button"
      onClick={onClick}
      className={`flex w-full items-start gap-3 px-4 py-4 text-left transition hover:bg-zinc-50 sm:px-5 sm:py-5 ${className}`}
    >
      {content}
    </button>
  );
}

function ContactInfoRow({
  label,
  value,
  href,
  last = false,
}: {
  label: string;
  value: string;
  href?: string;
  last?: boolean;
}) {
  const valueContent = href ? (
    <a
      href={href}
      target={href.startsWith("http") ? "_blank" : undefined}
      rel={href.startsWith("http") ? "noreferrer" : undefined}
      className="text-right text-[13px] font-semibold text-zinc-950 transition hover:opacity-70"
    >
      {value}
    </a>
  ) : (
    <span className="text-right text-[13px] font-semibold text-zinc-950">{value}</span>
  );

  return (
    <div className={`flex flex-col items-start justify-between gap-1 px-4 py-4 sm:flex-row sm:items-center sm:gap-4 ${last ? "" : "border-b border-[#efedf2]"}`}>
      <span className="text-[13px] text-zinc-500">{label}</span>
      {valueContent}
    </div>
  );
}

function formatPhoneDisplay(value?: string | null) {
  const digits = String(value || "").replace(/\D/g, "");
  if (!digits) return "";
  if (digits.length === 11) return digits.replace(/(\d{2})(\d{5})(\d{4})/, "($1) $2-$3");
  if (digits.length === 10) return digits.replace(/(\d{2})(\d{4})(\d{4})/, "($1) $2-$3");
  return String(value || "").trim();
}

function getPaymentMethodLabel(method?: string | null) {
  switch (String(method || "").trim()) {
    case "pix":
      return "Pix";
    case "credit_card":
      return "Cartão de crédito";
    case "debit_card":
      return "Cartão de débito";
    case "ticket":
      return "Boleto";
    case "wallet":
      return "Saldo em conta";
    case "cash":
      return "Dinheiro";
    case "transfer":
      return "Transferência bancária";
    default:
      return "A definir";
  }
}

function getPaymentStatusMeta(status?: string | null) {
  const normalized = String(status || "").trim();

  if (normalized === "approved") {
    return {
      label: "Pagamento confirmado com sucesso",
      description: "Seu pagamento foi recebido e o pedido segue normalmente.",
      backgroundColor: "#ecfdf3",
      color: "#027a48",
      borderColor: "#a7f3d0",
    };
  }

  if (normalized === "pending") {
    return {
      label: "Pagamento aguardando confirmação",
      description: "Existe uma cobrança iniciada, mas ela ainda não foi liquidada.",
      backgroundColor: "#fff7ed",
      color: "#c2410c",
      borderColor: "#fed7aa",
    };
  }

  if (normalized === "unpaid") {
    return {
      label: "Pagamento ainda não identificado",
      description: "Este pedido ainda não possui baixa financeira registrada.",
      backgroundColor: "#f8fafc",
      color: "#334155",
      borderColor: "#cbd5e1",
    };
  }

  if (normalized === "partially_paid") {
    return {
      label: "Pagamento parcial registrado",
      description: "Já recebemos uma parte do valor e ainda existe saldo pendente.",
      backgroundColor: "#eff6ff",
      color: "#1d4ed8",
      borderColor: "#bfdbfe",
    };
  }

  if (normalized === "rejected") {
    return {
      label: "Pagamento não aprovado",
      description: "Você pode tentar novamente com outra forma de pagamento.",
      backgroundColor: "#fef2f2",
      color: "#b91c1c",
      borderColor: "#fecaca",
    };
  }

  if (normalized === "cancelled") {
    return {
      label: "Pagamento cancelado",
      description: "Essa tentativa foi encerrada e não gerou cobrança ativa.",
      backgroundColor: "#f4f4f5",
      color: "#52525b",
      borderColor: "#d4d4d8",
    };
  }

  if (normalized === "refunded") {
    return {
      label: "Pagamento estornado",
      description: "O valor dessa transação foi devolvido.",
      backgroundColor: "#eff6ff",
      color: "#1d4ed8",
      borderColor: "#bfdbfe",
    };
  }

  return {
    label: "Pagamento registrado",
    description: "Os dados do pagamento foram vinculados a este pedido.",
    backgroundColor: "#f8fafc",
    color: "#334155",
    borderColor: "#cbd5e1",
  };
}

function formatRelativeLabel(value?: string | null) {
  if (!value) return "agora há pouco";
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return "agora há pouco";

  const diffMs = date.getTime() - Date.now();
  const diffMinutes = Math.round(diffMs / 60000);
  const formatter = new Intl.RelativeTimeFormat("pt-BR", { numeric: "auto" });

  if (Math.abs(diffMinutes) < 60) return formatter.format(diffMinutes, "minute");
  const diffHours = Math.round(diffMinutes / 60);
  if (Math.abs(diffHours) < 24) return formatter.format(diffHours, "hour");
  const diffDays = Math.round(diffHours / 24);
  return formatter.format(diffDays, "day");
}

function getOrderHeroCopy(status?: string | null) {
  switch (String(status || "").trim()) {
    case "in_production":
      return {
        eyebrow: "Em produção",
        title: "Seu pedido está ganhando forma.",
        description: "Nossa equipe está produzindo o seu material com atenção aos detalhes.",
      };
    case "finished":
      return {
        eyebrow: "Acabamento concluído",
        title: "Seu pedido está quase pronto.",
        description: "Finalizamos a produção e estamos preparando a próxima etapa.",
      };
    case "delivered":
      return {
        eyebrow: "Pedido entregue",
        title: "Seu pedido já chegou até você.",
        description: "A entrega foi concluída e o histórico continua disponível aqui no portal.",
      };
    case "canceled":
      return {
        eyebrow: "Pedido cancelado",
        title: "Este pedido foi encerrado.",
        description: "Se precisar, nossa equipe pode orientar os próximos passos.",
      };
    default:
      return {
        eyebrow: "Pedido confirmado",
        title: "Seu pedido entrou em produção.",
        description: "Recebemos sua compra e já iniciamos a preparação do material.",
      };
  }
}

export function OrdersSection({
  slug,
  orders,
  filteredOrders,
  paginatedOrders,
  primaryColor,
}: {
  slug?: string;
  orders: ClientPortalOrder[];
  filteredOrders?: ClientPortalOrder[];
  paginatedOrders?: ClientPortalOrder[];
  primaryColor: string;
}) {
  const router = useRouter();
  const sourceOrders = paginatedOrders || filteredOrders || orders;
  const totalValue = sourceOrders.reduce((sum, order) => (order.status === "canceled" ? sum : sum + Number(order.total_amount || 0)), 0);
  const activeOrders = sourceOrders.filter((order) => order.status !== "delivered" && order.status !== "canceled").length;
  const deliveredOrders = sourceOrders.filter((order) => order.status === "delivered").length;

  const openOrderDetails = (detailsUrl: string) => {
    try {
      if (slug) {
        const key = `ks_portal_return_to:${slug}`;
        window.sessionStorage.setItem(key, `${window.location.pathname}${window.location.search}`);
      }
    } catch {
    }
    router.push(detailsUrl);
  };

  if (sourceOrders.length === 0) {
    return (
      <div className="space-y-6">
        {slug ? <PagamentosPendentes slug={slug} primaryColor={primaryColor} /> : null}
        <section className="border border-[#efedf2] bg-white">
          <div className="grid gap-0 lg:grid-cols-[minmax(0,1fr)_300px]">
            <div className="px-4 py-5 sm:px-7 sm:py-6">
              <div
                className="inline-flex items-center gap-2 rounded-[10px] px-3 py-1.5 text-[12px] font-semibold"
                style={{ backgroundColor: hexToRgba(primaryColor, 0.09), color: getAccessibleAccent(primaryColor) }}
              >
                <span className="h-1.5 w-1.5 rounded-full" style={{ backgroundColor: primaryColor, color: getReadableTextColor(primaryColor) }} />
                <span>Histórico de compras</span>
              </div>
              <h1 className="mt-4 text-[26px] font-semibold tracking-[-0.04em] text-zinc-950 sm:mt-5 sm:text-[30px]">Meus pedidos</h1>
              <p className="mt-2 max-w-[560px] text-[14px] leading-6 text-zinc-600">
                Acompanhe cada compra feita na loja e abra os detalhes completos de produção, pagamento e entrega.
              </p>
            </div>

            <div className="border-t border-[#efedf2] px-4 py-5 sm:px-7 sm:py-6 lg:border-l lg:border-t-0">
              <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-zinc-400">Situação</div>
              <div className="mt-3 text-[24px] font-semibold tracking-[-0.04em] text-zinc-950">Sem pedidos</div>
              <div className="mt-2 text-[13px] text-zinc-500">Seu histórico aparecerá aqui assim que a primeira compra for criada.</div>
              {slug ? (
                <Link
                  href={`/${slug}`}
                  className="mt-5 inline-flex h-11 items-center gap-2 px-5 text-sm font-semibold text-white transition hover:opacity-90"
                  style={{ backgroundColor: primaryColor, color: getReadableTextColor(primaryColor) }}
                >
                  Fazer primeiro pedido
                  <ArrowRight className="h-4 w-4" />
                </Link>
              ) : null}
            </div>
          </div>
        </section>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {slug ? <PagamentosPendentes slug={slug} primaryColor={primaryColor} /> : null}
      <section className="border border-[#efedf2] bg-white">
        <div className="grid gap-0 xl:grid-cols-[minmax(0,1fr)_320px]">
          <div className="px-4 py-5 sm:px-7 sm:py-6">
            <div
              className="inline-flex items-center gap-2 rounded-[10px] px-3 py-1.5 text-[12px] font-semibold"
              style={{ backgroundColor: hexToRgba(primaryColor, 0.09), color: getAccessibleAccent(primaryColor) }}
            >
              <span className="h-1.5 w-1.5 rounded-full" style={{ backgroundColor: primaryColor, color: getReadableTextColor(primaryColor) }} />
              <span>{sourceOrders.length} pedido{sourceOrders.length !== 1 ? "s" : ""}</span>
            </div>
            <h1 className="mt-4 text-[26px] font-semibold tracking-[-0.04em] text-zinc-950 sm:mt-5 sm:text-[30px]">Meus pedidos</h1>
            <p className="mt-2 max-w-[560px] text-[14px] leading-6 text-zinc-600">
              Abra qualquer pedido para consultar comprovante, andamento e informações completas da compra.
            </p>
          </div>

          <div className="border-t border-[#efedf2] px-4 py-5 sm:px-7 sm:py-6 xl:border-l xl:border-t-0">
            <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-zinc-400">Valor movimentado</div>
            <div className="mt-3 text-[28px] font-semibold tracking-[-0.04em] text-zinc-950">{formatMoney(totalValue)}</div>
            <div className="mt-2 text-[13px] text-zinc-500">Soma dos pedidos presentes nesta visualização.</div>
          </div>
        </div>
      </section>

      <div className="grid grid-cols-2 gap-3 lg:grid-cols-4">
        <MetricCard label="Pedidos" value={String(sourceOrders.length)} />
        <MetricCard label="Em andamento" value={String(activeOrders)} />
        <MetricCard label="Entregues" value={String(deliveredOrders)} />
        <MetricCard label="Total" value={formatMoney(totalValue)} />
      </div>

      <section className="border border-[#efedf2] bg-white px-4 py-4 sm:px-6 sm:py-5">
        <div className="mb-4 flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between sm:gap-4">
          <h3 className="text-[15px] font-semibold text-zinc-950">Lista de pedidos</h3>
          <div className="text-[13px] text-zinc-500">Clique em um pedido para abrir o detalhe completo</div>
        </div>

        <div className="border border-[#efedf2] bg-white">
          {sourceOrders.map((order, index) => {
            const statusMeta = getStatusMeta(order.status, primaryColor);
            const detailsUrl = slug ? `/${slug}/cliente?section=orders&orderId=${encodeURIComponent(order.id)}` : null;
            const shareUrl = slug && order.share_token ? `/${slug}/status/${order.share_token}` : null;

            return (
              <div
                key={order.id}
                role="button"
                tabIndex={0}
                onClick={() => {
                  if (!detailsUrl) return;
                  openOrderDetails(detailsUrl);
                }}
                onKeyDown={(event) => {
                  if (event.key === "Enter" || event.key === " ") {
                    event.preventDefault();
                    if (!detailsUrl) return;
                    openOrderDetails(detailsUrl);
                  }
                }}
                className={`cursor-pointer px-4 py-4 transition hover:bg-zinc-50 ${index < sourceOrders.length - 1 ? "border-b border-[#efedf2]" : ""}`}
              >
              <div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between sm:gap-4">
                  <div className="min-w-0">
                    <div className="text-[14px] font-semibold text-zinc-950">Pedido #{order.number}</div>
                    <div className="mt-1 text-[12px] text-zinc-500">{formatDateTime(order.created_at)}</div>
                  </div>
                  <div className="text-left sm:text-right">
                    <div className="text-[14px] font-semibold text-zinc-950">{formatMoney(order.total_amount)}</div>
                    <div className="mt-1 text-[11px] uppercase tracking-[0.16em] text-zinc-400">Total</div>
                  </div>
                </div>

                <div className="mt-4 flex flex-col gap-3 sm:flex-row sm:flex-wrap sm:items-center sm:justify-between">
                  <span
                    className="inline-flex items-center gap-2 rounded-[10px] px-3 py-1.5 text-[11px] font-semibold"
                    style={{ backgroundColor: statusMeta.backgroundColor, color: statusMeta.color }}
                  >
                    <span className="h-1.5 w-1.5 rounded-full" style={{ backgroundColor: statusMeta.color }} />
                    <span>{statusMeta.label}</span>
                  </span>

                  <div className="flex flex-wrap items-center gap-3 sm:gap-4">
                    <span className="text-[12px] font-semibold" style={{ color: getAccessibleAccent(primaryColor) }}>
                      Ver detalhes
                    </span>
                    {shareUrl ? (
                      <button
                        type="button"
                        className="text-[12px] font-semibold text-zinc-600 transition hover:text-zinc-950"
                        onClick={(event) => {
                          event.stopPropagation();
                          void navigator.clipboard?.writeText(shareUrl).catch(() => {});
                        }}
                      >
                        Copiar link
                      </button>
                    ) : null}
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      </section>
    </div>
  );
}

export function OrderDetailsSection({
  slug,
  primaryColor,
  details,
  onBackToOrders,
}: {
  slug: string;
  primaryColor: string;
  details: {
    status_token?: string | null;
    status_payload?: {
      profile?: {
        slug?: string | null;
        store_name?: string | null;
        catalog_name?: string | null;
        logo_url?: string | null;
        catalog_logo_url?: string | null;
        phone?: string | null;
        company_phone?: string | null;
        company_whatsapp?: string | null;
      } | null;
      client?: { name?: string | null } | null;
      quote?: { currency?: string | null; delivery_date?: string | null } | null;
      order?: {
        number?: number | null;
        status?: string | null;
        created_at?: string | null;
        updated_at?: string | null;
        total_amount?: number | null;
        paid_amount?: number | null;
        production_stage_label?: string | null;
      } | null;
    } | null;
    order: {
      id: string;
      number: number;
      created_at: string;
      updated_at?: string | null;
      status: string;
      total_amount: number;
      paid_amount?: number | null;
      financial_status?: string | null;
      production_stage_label?: string | null;
      share_token?: string | null;
      delivery_date?: string | null;
    };
    quote?: {
      currency?: string | null;
      subtotal?: number | null;
      discount?: number | null;
      shipping?: number | null;
      total?: number | null;
      delivery_date?: string | null;
    } | null;
    /* Estes tres blocos ja vinham prontos do servidor e nao eram usados: por
       isso a previsao de entrega ficava "A definir" mesmo com prazo escolhido no
       checkout, e o codigo de rastreio que a loja cadastra nunca aparecia aqui,
       apesar de o admin prometer que apareceria. */
    catalog_shipping?: {
      carrier_name?: string | null;
      service_name?: string | null;
      delivery_time?: number | null;
      pickup?: { name?: string | null; address_summary?: string | null } | null;
    } | null;
    delivery_tracking?: {
      codes?: string[] | null;
      url?: string | null;
      notes?: string | null;
      updated_at?: string | null;
    } | null;
    items?: Array<{
      id: string;
      product_id?: string | null;
      product_name?: string | null;
      product_image_url?: string | null;
      title?: string | null;
      description?: string | null;
      quantity: number;
      unit_price: number;
      total_price: number;
      unit_type?: string | null;
      selected_options?: { options?: Array<{ attribute_name?: string | null; label?: string | null }> } | null;
    }>;
    payment_receipt?: ClientPortalPaymentReceipt | null;
  };
  onBackToOrders: () => void;
}) {
  const router = useRouter();
  const order = details.order;
  const items = Array.isArray(details.items) ? details.items : [];
  const statusMeta = getStatusMeta(order.status, primaryColor);
  const statusToken = String(details.status_token || order.share_token || "").trim();
  const statusUrl = statusToken ? `/${slug}/status/${statusToken}` : null;
  const publicStatus = details.status_payload || null;

  const paymentReceipt = details.payment_receipt || null;
  const paymentMethodLabel = paymentReceipt?.method_label || getPaymentMethodLabel(paymentReceipt?.method);
  const paymentStatusMeta = getPaymentStatusMeta(paymentReceipt?.status);
  const paymentSettledAmount = Number(order.paid_amount ?? paymentReceipt?.amount ?? 0);
  const paymentPendingAmount = Math.max(0, Number(order.total_amount || 0) - paymentSettledAmount);
  const paymentIsSettled = paymentReceipt?.status === "approved" || paymentReceipt?.status === "partially_paid";
  const paymentCardTitle = paymentIsSettled ? "Pagamento do pedido" : "Status do pagamento";
  const paymentCardValueLabel = paymentIsSettled ? "Valor pago" : "Valor pendente";
  const paymentCardValue = paymentIsSettled ? paymentSettledAmount : paymentPendingAmount || Number(order.total_amount || 0);
  const paymentCardFootnote = paymentReceipt?.paid_at
    ? formatDateTime(paymentReceipt.paid_at)
    : paymentReceipt?.status === "pending"
      ? "Cobranca aguardando confirmacao"
      : paymentReceipt?.status === "unpaid"
        ? "Nenhum pagamento identificado"
        : paymentReceipt?.created_at
          ? `Atualizado em ${formatDateTime(paymentReceipt.created_at)}`
          : "Sem baixa financeira";
  const paymentDetailsActionLabel = paymentIsSettled ? "Abrir comprovante" : "Abrir detalhes do pagamento";

  const formatOptions = (
    selectedOptions?: { options?: Array<{ attribute_name?: string | null; label?: string | null }> } | null
  ) => {
    const options = Array.isArray(selectedOptions?.options) ? selectedOptions.options : [];
    return options
      .map((opt) => {
        const a = String(opt?.attribute_name || "").trim();
        const l = String(opt?.label || "").trim();
        if (!a && !l) return "";
        if (!a) return l;
        if (!l) return a;
        return `${a}: ${l}`;
      })
      .filter(Boolean)
      .join(" • ");
  };

  const orderStatusSteps = [
    {
      key: "pending_production",
      title: "Aguardando produção",
      description: "Seu pedido foi confirmado e entrou na fila de produção.",
    },
    {
      key: "in_production",
      title: "Em produção",
      description: "Nossa equipe está produzindo os itens do seu pedido.",
    },
    {
      key: "finished",
      title: "Finalizado",
      description: "A produção foi concluída e está pronta para entrega/retirada.",
    },
    {
      key: "delivered",
      title: "Entregue",
      description: "Pedido entregue com sucesso.",
    },
  ];

  const publicOrder = publicStatus?.order || null;
  const publicProfile = publicStatus?.profile || null;
  const publicQuote = publicStatus?.quote || null;
  const publicOrderStatus = String(publicOrder?.status || "").trim();
  const currentStepIndex = orderStatusSteps.findIndex((step) => step.key === publicOrderStatus);
  const isCanceled = publicOrderStatus === "canceled";
  const isDelivered = publicOrderStatus === "delivered";
  const isFinished = publicOrderStatus === "finished";
  const totalAmount = Number(publicOrder?.total_amount ?? order.total_amount ?? 0) || 0;
  const paidAmount = Number(publicOrder?.paid_amount ?? order.paid_amount ?? 0) || 0;
  const remainingAmount = Math.max(0, totalAmount - paidAmount);
  const paymentProgress = totalAmount > 0 ? Math.min(100, Math.max(0, (paidAmount / totalAmount) * 100)) : 0;
  const shouldShowPaymentReminder = isFinished && remainingAmount > 0.009;
  const whatsappDigits = String(publicProfile?.company_whatsapp || publicProfile?.phone || publicProfile?.company_phone || "")
    .replace(/\D/g, "");
  const paymentReminderMessage = `Olá! Sobre o pedido #${order.number}, vi que falta ${formatMoney(
    remainingAmount
  )} para pagamento. Pode me orientar para quitar antes da retirada?`;
  const paymentReminderWhatsappUrl = whatsappDigits
    ? `https://wa.me/${whatsappDigits}?text=${encodeURIComponent(paymentReminderMessage)}`
    : null;
  const contactWhatsappUrl = whatsappDigits ? `https://wa.me/${whatsappDigits}` : null;
  const lastUpdatedAt = formatDateTime(String(publicOrder?.updated_at || publicOrder?.created_at || order.updated_at || order.created_at));
  const entregaCombinada = order.delivery_date || publicQuote?.delivery_date || null;
  const fretePortal = details.catalog_shipping || null;
  const prazoDoFrete = Number(fretePortal?.delivery_time || 0);
  /*
    Previsao de entrega, na ordem em que ela existe de verdade:
    1. a data que a loja combinou no pedido;
    2. a data do orcamento, quando o pedido nasceu de um;
    3. o prazo da transportadora escolhida no checkout, contado do dia do pedido.
    So depois disso e que vira "A combinar" — antes o portal pulava direto para
    o "A definir" mesmo tendo o prazo na mao.
  */
  const deliveryDate = entregaCombinada
    ? formatDate(String(entregaCombinada))
    : prazoDoFrete > 0
      ? formatDate(
          new Date(
            new Date(String(order.created_at)).getTime() + prazoDoFrete * 24 * 60 * 60 * 1000
          ).toISOString()
        )
      : null;
  const previsaoEhEstimativa = !entregaCombinada && prazoDoFrete > 0;
  const rastreio = details.delivery_tracking || null;
  const codigosDeRastreio = Array.isArray(rastreio?.codes) ? rastreio.codes.filter(Boolean) : [];
  const statusLabel = publicOrder?.production_stage_label || order.production_stage_label || statusMeta.label;
  const receiptUrl = `/${slug}/cliente/pedido/${order.id}/comprovante`;
  const receiptPrintUrl = `${receiptUrl}?print=1`;
  const heroCopy = getOrderHeroCopy(publicOrderStatus || order.status);
  const leadItem = items[0] || null;
  const leadItemName = leadItem?.product_name || leadItem?.title || "Seu material";
  const leadItemImage = leadItem?.product_image_url || null;
  const remainingItemsCount = Math.max(0, items.length - 1);
  const supportWhatsappUrl = whatsappDigits
    ? `https://wa.me/${whatsappDigits}?text=${encodeURIComponent(`Olá! Preciso de ajuda com o pedido #${order.number}.`)}`
    : null;
  const activityFeed = [
    {
      key: "created",
      time: order.created_at,
      title: "Pedido confirmado",
      description: "Recebemos a sua compra e iniciamos o acompanhamento por aqui.",
      icon: Check,
    },
    paymentReceipt?.paid_at
      ? {
          key: "paid",
          time: paymentReceipt.paid_at,
          title: "Pagamento identificado",
          description: "O pagamento foi reconhecido e o material seguiu para a próxima etapa.",
          icon: CreditCard,
        }
      : null,
    {
      key: "progress",
      time: String(publicOrder?.updated_at || publicOrder?.created_at || order.updated_at || order.created_at),
      title: heroCopy.eyebrow,
      description: heroCopy.description,
      icon: Package,
    },
    deliveryDate
      ? {
          key: "forecast",
          time: String(publicOrder?.updated_at || order.updated_at || order.created_at),
          title: isDelivered ? "Entrega concluída" : "Próxima etapa prevista",
          description: isDelivered ? "Seu pedido já foi entregue." : `Previsão atual: ${deliveryDate}.`,
          icon: ThumbsUp,
        }
      : null,
  ].filter(Boolean) as Array<{
    key: string;
    time: string;
    title: string;
    description: string;
    icon: typeof Check;
  }>;

  return (
    <div className="space-y-5">
      <div className="flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between">
        <div>
          <button
            type="button"
            onClick={onBackToOrders}
            className="text-xs font-semibold text-zinc-500 transition hover:text-zinc-900"
          >
            Voltar para pedidos
          </button>
          <h1 className="mt-2 text-2xl font-semibold text-zinc-900">Pedido #{order.number}</h1>
          <p className="mt-1 text-sm text-zinc-500">{formatDateTime(order.created_at)}</p>
        </div>

        <div className="flex items-center gap-3">
          <span
            className="rounded-full px-3 py-1.5 text-[11px] font-semibold"
            style={{ backgroundColor: statusMeta.backgroundColor, color: statusMeta.color }}
          >
            {statusMeta.label}
          </span>
          {order.production_stage_label ? (
            <span className="rounded-lg border border-zinc-200 bg-white px-3 py-1.5 text-[11px] font-semibold text-zinc-700">
              Produção: {order.production_stage_label}
            </span>
          ) : null}
        </div>
      </div>

      <section className="overflow-hidden rounded-[28px] border border-zinc-200/80 bg-white shadow-[0_18px_60px_rgba(15,23,42,0.06)]">
        <div className="relative">
          <div
            className="absolute inset-x-0 top-0 h-28"
            style={{ background: `linear-gradient(180deg, ${hexToRgba(primaryColor, 0.14)} 0%, rgba(255,255,255,0) 100%)` }}
          />
          <div className="relative grid gap-5 p-5 lg:grid-cols-[180px_minmax(0,1fr)_280px] lg:p-6">
            <div className="flex items-center justify-center">
              <div className="flex h-36 w-36 items-center justify-center overflow-hidden rounded-[24px] border border-zinc-200 bg-zinc-50 shadow-[inset_0_1px_0_rgba(255,255,255,0.65)]">
                {leadItemImage ? (
                  <img src={leadItemImage} alt={leadItemName} className="h-full w-full object-cover" />
                ) : (
                  <Package className="h-10 w-10 text-zinc-300" />
                )}
              </div>
            </div>

            <div className="min-w-0 space-y-4">
              <div className="flex flex-wrap items-center gap-2">
                <span
                  className="inline-flex items-center rounded-full px-3 py-1.5 text-[11px] font-semibold"
                  style={{ backgroundColor: statusMeta.backgroundColor, color: statusMeta.color }}
                >
                  {heroCopy.eyebrow}
                </span>
                <span className="text-xs font-medium text-zinc-400">Atualizado {formatRelativeLabel(publicOrder?.updated_at || order.updated_at || order.created_at)}</span>
              </div>

              <div>
                <h2 className="text-[28px] font-semibold tracking-[-0.05em] text-zinc-950 sm:text-[34px]">{heroCopy.title}</h2>
                <p className="mt-2 max-w-2xl text-sm leading-6 text-zinc-500">{heroCopy.description}</p>
              </div>

              <div className="space-y-2">
                <div className="text-lg font-semibold text-zinc-950">{leadItemName}</div>
                <div className="flex flex-wrap items-center gap-x-4 gap-y-2 text-sm text-zinc-500">
                  <span>Pedido #{order.number}</span>
                  <span>{formatDateTime(order.created_at)}</span>
                  {remainingItemsCount > 0 ? <span>+ {remainingItemsCount} item{remainingItemsCount > 1 ? "s" : ""}</span> : null}
                </div>
              </div>
            </div>

            <div className="rounded-[24px] border border-zinc-200 bg-zinc-50/80 p-4">
              <div className="text-[11px] font-medium uppercase tracking-[0.12em] text-zinc-400">Resumo</div>
              <div className="mt-4 text-2xl font-semibold tracking-[-0.04em] text-zinc-950">{formatMoney(order.total_amount)}</div>
              <div className="mt-1 text-sm text-zinc-500">{paymentReceipt ? paymentStatusMeta.label : "Pagamento em análise"}</div>

              <div className="mt-4 grid grid-cols-2 gap-3 border-t border-zinc-200 pt-4 text-sm">
                <div>
                  <div className="text-xs text-zinc-400">Pago</div>
                  <div className="mt-1 font-semibold text-zinc-900">{formatMoney(order.paid_amount ?? 0)}</div>
                </div>
                <div>
                  <div className="text-xs text-zinc-400">Data</div>
                  <div className="mt-1 font-semibold text-zinc-900">{formatDate(order.created_at)}</div>
                </div>
              </div>

              <div className="mt-4 grid grid-cols-2 gap-2">
                {contactWhatsappUrl ? (
                  <a
                    href={contactWhatsappUrl}
                    target="_blank"
                    rel="noreferrer"
                    className="inline-flex h-11 items-center justify-center rounded-xl px-4 text-sm font-semibold text-white transition hover:opacity-90"
                    style={{ backgroundColor: primaryColor, color: getReadableTextColor(primaryColor) }}
                  >
                    WhatsApp
                  </a>
                ) : null}
                {statusUrl ? (
                  <Link
                    href={statusUrl}
                    target="_blank"
                    className="inline-flex h-11 items-center justify-center rounded-xl border border-zinc-200 bg-white px-4 text-sm font-semibold text-zinc-700 transition hover:border-zinc-300 hover:text-zinc-950"
                  >
                    Visualizar arte
                  </Link>
                ) : null}
                <Link
                  href={receiptUrl}
                  target="_blank"
                  className="inline-flex h-11 items-center justify-center rounded-xl border border-zinc-200 bg-white px-4 text-sm font-semibold text-zinc-700 transition hover:border-zinc-300 hover:text-zinc-950"
                >
                  Baixar comprovante
                </Link>
                {supportWhatsappUrl ? (
                  <a
                    href={supportWhatsappUrl}
                    target="_blank"
                    rel="noreferrer"
                    className="inline-flex h-11 items-center justify-center rounded-xl border border-zinc-200 bg-white px-4 text-sm font-semibold text-zinc-700 transition hover:border-zinc-300 hover:text-zinc-950"
                  >
                    Solicitar suporte
                  </a>
                ) : null}
              </div>
            </div>
          </div>
        </div>
      </section>

      <div className="grid grid-cols-1 gap-4 lg:grid-cols-[minmax(0,1fr)_360px] lg:items-start">
        <div className="space-y-4">
          <PremiumCard className="rounded-[24px] border border-zinc-200/80 p-4 shadow-[0_12px_40px_rgba(15,23,42,0.04)]">
            <div className="flex items-center justify-between gap-3">
              <div className="text-base font-semibold text-zinc-950">Itens</div>
              <div className="text-xs text-zinc-500">{items.length} item{items.length !== 1 ? "s" : ""}</div>
            </div>
            <div className="mt-3 space-y-2.5">
              {items.map((item) => {
                const name = item.product_name || item.title || "Item";
                const options = formatOptions(item.selected_options);
                return (
                  <div key={item.id} className="flex gap-3 rounded-lg border border-zinc-200 bg-white p-3">
                    <div className="h-14 w-14 overflow-hidden rounded-lg border border-zinc-200 bg-zinc-50 flex items-center justify-center shrink-0">
                      {item.product_image_url ? (
                        <img src={item.product_image_url} alt={name} className="h-full w-full object-cover" />
                      ) : (
                        <ShoppingBag className="h-5 w-5 text-zinc-400" />
                      )}
                    </div>
                    <div className="min-w-0 flex-1">
                      <div className="flex items-start justify-between gap-3">
                        <div className="min-w-0">
                          <div className="text-sm font-semibold text-zinc-900 line-clamp-1">{name}</div>
                          {options ? <div className="mt-1 text-xs text-zinc-500 line-clamp-2">{options}</div> : null}
                          {item.description ? <div className="mt-1 text-xs text-zinc-500 line-clamp-2">{item.description}</div> : null}
                        </div>
                        <div className="text-sm font-semibold text-zinc-900 shrink-0">{formatMoney(item.total_price)}</div>
                      </div>
                      <div className="mt-2 grid grid-cols-2 gap-2">
                        <div className="text-xs text-zinc-600">
                          Qtd: <span className="font-semibold text-zinc-900">{item.quantity}</span>
                        </div>
                        <div className="text-xs text-zinc-600 text-right">
                          Unit: <span className="font-semibold text-zinc-900">{formatMoney(item.unit_price)}</span>
                        </div>
                      </div>
                    </div>
                  </div>
                );
              })}
              {items.length === 0 ? <div className="py-8 text-center text-sm text-zinc-500">Nenhum item encontrado.</div> : null}
            </div>
          </PremiumCard>
          <div className="space-y-4">
            <div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
              <div>
                <div className="text-base font-semibold text-zinc-950">Linha do tempo do pedido</div>
                <div className="text-sm text-zinc-500">Acompanhe o andamento e as próximas etapas.</div>
              </div>
              <div className="flex items-center gap-2">
                <button
                  type="button"
                  onClick={() => router.refresh()}
                  className="inline-flex h-9 items-center rounded-lg border border-zinc-200 bg-white px-3.5 text-sm font-medium text-zinc-700 hover:border-zinc-300 hover:text-zinc-950"
                >
                  Atualizar
                </button>
                {statusUrl ? (
                  <Link
                    href={statusUrl}
                    target="_blank"
                    className="inline-flex h-9 items-center rounded-lg border border-zinc-200 bg-white px-3.5 text-sm font-medium text-zinc-700 hover:border-zinc-300 hover:text-zinc-950"
                  >
                    Abrir link público
                  </Link>
                ) : null}
              </div>
            </div>

            {publicStatus && (!publicProfile?.slug || publicProfile.slug === slug) && publicOrder ? (
              <div className="space-y-4">
                <div className="rounded-[24px] border border-zinc-200/80 bg-white p-4 shadow-[0_12px_40px_rgba(15,23,42,0.04)]">
                  <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
                    <div className="min-w-0">
                      <div className="text-sm font-semibold text-zinc-900">{statusLabel}</div>
                      <div className="mt-1 text-sm text-zinc-500">Última atualização em {lastUpdatedAt || "-"}</div>
                    </div>
                    <span
                      className="inline-flex justify-center rounded-full px-3 py-1.5 text-[11px] font-semibold"
                      style={{ backgroundColor: statusMeta.backgroundColor, color: statusMeta.color }}
                    >
                      {statusLabel}
                    </span>
                  </div>

                  {/* Tres caixas cinzas dentro de um cartao branco, e uma delas
                      repetindo o status que ja esta escrito logo acima. Aqui viraram
                      duas linhas de rotulo e valor, sem moldura. */}
                  <dl className="mt-3 divide-y divide-zinc-100 border-t border-zinc-100 text-sm">
                    <div className="flex items-baseline justify-between gap-3 py-2.5">
                      <dt className="text-zinc-500">{isDelivered ? "Entregue em" : "Previsão de entrega"}</dt>
                      <dd className="text-right font-semibold text-zinc-900">
                        {deliveryDate || "A combinar com a loja"}
                        {previsaoEhEstimativa ? (
                          <span className="ml-1.5 text-xs font-normal text-zinc-400">estimado</span>
                        ) : null}
                      </dd>
                    </div>
                    {fretePortal?.pickup?.name || fretePortal?.carrier_name ? (
                      <div className="flex items-baseline justify-between gap-3 py-2.5">
                        <dt className="text-zinc-500">{fretePortal?.pickup?.name ? "Retirada" : "Envio por"}</dt>
                        <dd className="text-right font-semibold text-zinc-900">
                          {fretePortal?.pickup?.name
                            ? fretePortal.pickup.address_summary || fretePortal.pickup.name
                            : [fretePortal?.carrier_name, fretePortal?.service_name].filter(Boolean).join(" · ")}
                        </dd>
                      </div>
                    ) : null}
                    <div className="flex items-baseline justify-between gap-3 py-2.5">
                      <dt className="text-zinc-500">Última atualização</dt>
                      <dd className="text-right font-semibold text-zinc-900">{lastUpdatedAt || "-"}</dd>
                    </div>
                  </dl>

                  {codigosDeRastreio.length || rastreio?.url || rastreio?.notes ? (
                    <div className="mt-3 rounded-2xl border border-zinc-100 bg-zinc-50/70 p-3.5">
                      <div className="text-[11px] font-semibold uppercase tracking-[0.12em] text-zinc-400">
                        Rastreio
                      </div>
                      {codigosDeRastreio.length ? (
                        <div className="mt-2 flex flex-wrap gap-2">
                          {codigosDeRastreio.map((codigo) => (
                            <span
                              key={codigo}
                              className="inline-flex rounded-full border border-zinc-200 bg-white px-3 py-1 font-mono text-[13px] font-semibold text-zinc-900"
                            >
                              {codigo}
                            </span>
                          ))}
                        </div>
                      ) : null}
                      {rastreio?.notes ? (
                        <p className="mt-2 text-sm leading-6 text-zinc-600">{rastreio.notes}</p>
                      ) : null}
                      {rastreio?.url ? (
                        <a
                          href={rastreio.url}
                          target="_blank"
                          rel="noreferrer"
                          className="mt-2 inline-flex text-sm font-semibold underline-offset-4 hover:underline"
                          style={{ color: primaryColor }}
                        >
                          Acompanhar na transportadora
                        </a>
                      ) : null}
                    </div>
                  ) : null}
                </div>

                <div className="rounded-[24px] border border-zinc-200/80 bg-white p-5 shadow-[0_12px_40px_rgba(15,23,42,0.04)]">
                  <div className="text-sm font-semibold text-zinc-900">Andamento</div>

                  <div className="mt-4">
                    <div className="hidden h-1 w-full overflow-hidden rounded-full bg-zinc-100 sm:block">
                      <div
                        className="h-full rounded-full"
                        style={{
                          width:
                            isCanceled || currentStepIndex < 0
                              ? "0%"
                              : `${((Math.min(currentStepIndex, orderStatusSteps.length - 1) + 1) / orderStatusSteps.length) * 100}%`,
                          backgroundColor: primaryColor,
                        }}
                      />
                    </div>

                    <div className="mt-4 flex flex-col gap-4 sm:flex-row sm:justify-between sm:gap-2">
                      {orderStatusSteps.map((step, index) => {
                        const isDone = !isCanceled && currentStepIndex >= index;
                        const isCurrent = !isCanceled && currentStepIndex === index;
                        const markerStyle = isCurrent
                          ? { backgroundColor: primaryColor, borderColor: primaryColor, color: getReadableTextColor(primaryColor) }
                          : isDone
                            ? { backgroundColor: "#111827", borderColor: "#111827", color: "#fff" }
                            : { backgroundColor: "#fff", borderColor: "#e4e4e7", color: "#71717a" };

                        return (
                          <div key={step.key} className="flex items-start gap-3 sm:flex-1 sm:flex-col sm:items-center sm:text-center">
                            <div
                              className="flex h-7 w-7 items-center justify-center rounded-full border-2 text-xs font-bold shrink-0"
                              style={markerStyle}
                            >
                              {isDone ? <Check size={12} strokeWidth={3} /> : index + 1}
                            </div>
                            <div className="pt-0.5 sm:pt-0">
                              <div className="text-xs font-bold" style={{ color: isCurrent ? primaryColor : isDone ? "#111827" : "#71717a" }}>
                                {step.title}
                              </div>
                              {isCurrent ? <div className="mt-1 text-[11px] leading-snug text-zinc-500">{step.description}</div> : null}
                            </div>
                          </div>
                        );
                      })}
                    </div>
                  </div>
                </div>

                <div className="rounded-[24px] border border-zinc-200/80 bg-white p-5 shadow-[0_12px_40px_rgba(15,23,42,0.04)]">
                  <div className="flex items-center justify-between gap-3">
                    <div>
                      <div className="text-base font-semibold text-zinc-950">Atualizações do pedido</div>
                      <div className="mt-1 text-sm text-zinc-500">Um histórico claro do que já aconteceu com a sua compra.</div>
                    </div>
                    <div className="text-xs font-medium text-zinc-400">Feed</div>
                  </div>

                  <div className="mt-5 space-y-4">
                    {activityFeed.map((entry, index) => {
                      const EntryIcon = entry.icon;
                      return (
                        <div key={entry.key} className="flex gap-3">
                          <div className="flex flex-col items-center">
                            <div
                              className="flex h-10 w-10 items-center justify-center rounded-2xl border"
                              style={{
                                backgroundColor: hexToRgba(primaryColor, 0.08),
                                borderColor: hexToRgba(primaryColor, 0.16),
                              }}
                            >
                              <EntryIcon className="h-4 w-4" style={{ color: getAccessibleAccent(primaryColor) }} />
                            </div>
                            {index < activityFeed.length - 1 ? <div className="mt-2 h-full w-px bg-zinc-100" /> : null}
                          </div>
                          <div className="min-w-0 flex-1 pb-4">
                            <div className="flex flex-wrap items-center gap-x-3 gap-y-1">
                              <div className="text-sm font-semibold text-zinc-950">{entry.title}</div>
                              <div className="text-xs text-zinc-400">{formatRelativeLabel(entry.time)}</div>
                            </div>
                            <div className="mt-1 text-sm leading-6 text-zinc-500">{entry.description}</div>
                            <div className="mt-1 text-xs text-zinc-400">{formatDateTime(entry.time)}</div>
                          </div>
                        </div>
                      );
                    })}
                  </div>
                </div>

                {shouldShowPaymentReminder ? (
                  <div className="rounded-[24px] border border-zinc-200/80 bg-white p-4 shadow-[0_12px_40px_rgba(15,23,42,0.04)]">
                    <div className="flex items-start gap-3">
                      <div className="mt-0.5 flex h-8 w-8 items-center justify-center rounded-lg border border-amber-200 bg-amber-50 text-amber-700">
                        <AlertCircle size={16} />
                      </div>
                      <div className="min-w-0 flex-1">
                        <div className="text-sm font-semibold text-zinc-900">Falta {formatMoney(remainingAmount)} para pagamento</div>
                        <div className="mt-1 text-sm text-zinc-500">
                          Seu pedido já está pronto. Regularize o valor pendente para liberar a retirada ou entrega.
                        </div>
                      </div>
                    </div>

                    <div className="mt-4 grid grid-cols-1 gap-3 sm:grid-cols-2">
                      <div className="rounded-lg border border-zinc-200 bg-zinc-50 px-4 py-3">
                        <div className="text-[11px] font-medium uppercase tracking-[0.12em] text-zinc-400">Valor total</div>
                        <div className="mt-1 text-base font-semibold text-zinc-900">{formatMoney(totalAmount)}</div>
                      </div>
                      <div className="rounded-lg border border-zinc-200 bg-zinc-50 px-4 py-3">
                        <div className="text-[11px] font-medium uppercase tracking-[0.12em] text-zinc-400">Valor pago</div>
                        <div className="mt-1 text-base font-semibold text-zinc-900">{formatMoney(paidAmount)}</div>
                      </div>
                    </div>

                    <div className="mt-4 flex items-center gap-3">
                      <div className="h-2 flex-1 overflow-hidden rounded-full bg-zinc-100">
                        <div className="h-full rounded-full" style={{ width: `${paymentProgress}%`, backgroundColor: primaryColor }} />
                      </div>
                      <div className="whitespace-nowrap text-xs font-semibold text-zinc-600">{paymentProgress.toFixed(0)}% pago</div>
                    </div>

                    {paymentReminderWhatsappUrl ? (
                      <div className="mt-4">
                        <a
                          href={paymentReminderWhatsappUrl}
                          target="_blank"
                          rel="noreferrer"
                          className="inline-flex h-10 w-full items-center justify-center gap-2 rounded-lg px-4 text-sm font-semibold text-white transition hover:opacity-90"
                          style={{ backgroundColor: primaryColor, color: getReadableTextColor(primaryColor) }}
                        >
                          <MessageCircle size={16} />
                          Falar sobre o pagamento
                        </a>
                      </div>
                    ) : null}
                  </div>
                ) : null}

                {isDelivered ? (
                  <div className="flex items-center gap-3 rounded-[20px] border border-emerald-200 bg-emerald-50 px-4 py-3">
                    <ThumbsUp size={16} className="text-emerald-700" />
                    <div className="text-sm font-semibold text-emerald-900">Obrigado pela confiança. Pedido finalizado e entregue.</div>
                  </div>
                ) : null}

                {isCanceled ? (
                  <div className="flex items-center gap-3 rounded-[20px] border border-rose-200 bg-rose-50 px-4 py-3">
                    <Ban size={16} className="text-rose-700" />
                    <div className="text-sm font-semibold text-rose-900">Este pedido foi cancelado. Fale com a loja para mais detalhes.</div>
                  </div>
                ) : null}

                {!isDelivered && !isCanceled && !shouldShowPaymentReminder && contactWhatsappUrl ? (
                  <div className="flex justify-start">
                    <a
                      href={contactWhatsappUrl}
                      target="_blank"
                      rel="noreferrer"
                      className="inline-flex items-center gap-2 text-sm font-semibold text-zinc-600 hover:text-zinc-900"
                    >
                      <MessageCircle size={16} />
                      Dúvidas? Fale no WhatsApp
                    </a>
                  </div>
                ) : null}
              </div>
            ) : (
              <div className="rounded-xl border border-zinc-200 bg-white p-4">
                <div className="text-sm font-semibold text-zinc-900">Status indisponível</div>
                <div className="mt-1 text-sm text-zinc-500">
                  Não foi possível carregar os dados do status agora. Use “Atualizar” ou “Abrir link público”.
                </div>
              </div>
            )}
          </div>
        </div>

        <div className="space-y-4">
          {paymentReceipt ? (
            <PremiumCard className="sticky top-6 rounded-[24px] border border-zinc-200/80 p-0 shadow-[0_12px_40px_rgba(15,23,42,0.04)]">
              <div className="border-b border-zinc-200 px-4 py-4">
                <div className="flex items-start justify-between gap-3">
                  <div>
                    <div className="flex items-center gap-2 text-[11px] font-medium uppercase tracking-[0.12em] text-zinc-400">
                      <ReceiptText className="h-4 w-4" />
                        {paymentCardTitle}
                    </div>
                    <div className="mt-2 text-base font-semibold text-zinc-950">{paymentMethodLabel}</div>
                    <div className="mt-1 text-sm text-zinc-500">{paymentStatusMeta.description}</div>
                  </div>
                  <span
                    className="inline-flex rounded-full border px-2.5 py-1 text-[11px] font-semibold"
                    style={{
                      backgroundColor: paymentStatusMeta.backgroundColor,
                      color: paymentStatusMeta.color,
                      borderColor: paymentStatusMeta.borderColor,
                    }}
                  >
                    {paymentStatusMeta.label}
                  </span>
                </div>
              </div>

              <div className="space-y-4 px-4 py-4">
                <div className="rounded-lg bg-zinc-50 px-4 py-3">
                  <div className="text-[11px] font-medium uppercase tracking-[0.12em] text-zinc-400">{paymentCardValueLabel}</div>
                  <div className="mt-1 text-xl font-semibold text-zinc-950">{formatMoney(paymentCardValue)}</div>
                  <div className="mt-1 text-xs text-zinc-500">{paymentCardFootnote}</div>
                </div>

                <div className="divide-y divide-zinc-100 rounded-lg border border-zinc-200">
                  <div className="flex items-center justify-between gap-3 px-4 py-3 text-sm">
                    <span className="text-zinc-500">Forma de pagamento</span>
                    <span className="font-semibold text-zinc-900">{paymentMethodLabel}</span>
                  </div>
                  <div className="flex items-center justify-between gap-3 px-4 py-3 text-sm">
                    <span className="text-zinc-500">Status</span>
                    <span className="font-semibold text-zinc-900">{paymentStatusMeta.label}</span>
                  </div>
                  {paymentReceipt.paid_at ? (
                    <div className="flex items-center justify-between gap-3 px-4 py-3 text-sm">
                      <span className="inline-flex items-center gap-2 text-zinc-500">
                        <Calendar className="h-4 w-4" />
                        Data e hora
                      </span>
                      <span className="font-semibold text-zinc-900">{formatDateTime(paymentReceipt.paid_at)}</span>
                    </div>
                  ) : null}
                </div>

                {paymentReceipt.reference ? (
                  <div className="rounded-lg border border-zinc-200 px-4 py-3">
                    <div className="text-[11px] font-medium uppercase tracking-[0.12em] text-zinc-400">Referência da transação</div>
                    <div className="mt-1 break-all text-sm font-semibold text-zinc-900">{paymentReceipt.reference}</div>
                  </div>
                ) : null}

                {paymentReceipt.payer_name || paymentReceipt.payer_email || paymentReceipt.payer_document ? (
                  <div className="rounded-lg border border-zinc-200 px-4 py-3">
                    <div className="text-[11px] font-medium uppercase tracking-[0.12em] text-zinc-400">Dados do pagador</div>
                    <div className="mt-3 space-y-2.5">
                      {paymentReceipt.payer_name ? (
                        <div className="flex items-center justify-between gap-3 text-sm">
                          <span className="inline-flex items-center gap-2 text-zinc-500">
                            <User className="h-4 w-4" />
                            Nome
                          </span>
                          <span className="font-semibold text-zinc-900">{paymentReceipt.payer_name}</span>
                        </div>
                      ) : null}
                      {paymentReceipt.payer_email ? (
                        <div className="flex items-center justify-between gap-3 text-sm">
                          <span className="inline-flex items-center gap-2 text-zinc-500">
                            <Mail className="h-4 w-4" />
                            E-mail
                          </span>
                          <span className="break-all text-right font-semibold text-zinc-900">{paymentReceipt.payer_email}</span>
                        </div>
                      ) : null}
                      {paymentReceipt.payer_document ? (
                        <div className="flex items-center justify-between gap-3 text-sm">
                          <span className="inline-flex items-center gap-2 text-zinc-500">
                            <CreditCard className="h-4 w-4" />
                            Documento
                          </span>
                          <span className="font-semibold text-zinc-900">{paymentReceipt.payer_document}</span>
                        </div>
                      ) : null}
                    </div>
                  </div>
                ) : null}

                <div className="grid grid-cols-1 gap-2 sm:grid-cols-2">
                  <Link
                    href={receiptUrl}
                    target="_blank"
                    className="inline-flex h-10 items-center justify-center rounded-lg border border-zinc-200 bg-white px-4 text-sm font-medium text-zinc-700 transition hover:border-zinc-300 hover:text-zinc-950"
                  >
                    {paymentDetailsActionLabel}
                  </Link>
                  <Link
                    href={receiptPrintUrl}
                    target="_blank"
                    className="inline-flex h-10 items-center justify-center gap-2 rounded-lg bg-zinc-950 px-4 text-sm font-medium text-white transition hover:bg-zinc-800"
                  >
                    <Printer className="h-4 w-4" />
                    Salvar PDF / Imprimir
                  </Link>
                </div>
              </div>
            </PremiumCard>
          ) : null}
        </div>
      </div>
    </div>
  );
}

export function AccountSection({
  slug,
  client,
  primaryColor,
}: {
  slug: string;
  client: ClientPortalClient;
  primaryColor: string;
}) {
  const completion = getProfileCompletion(client);
  const incompleteFields = getIncompleteProfileFields(client);
  const profileName = client.company_name || client.name || "Cliente";
  const addressSummary = getAddressSummary(client) || "Não informado";

  return (
    <div className="space-y-6">
      <section className="border border-[#efedf2] bg-white">
        <div className="grid gap-0 xl:grid-cols-[minmax(0,1fr)_320px]">
          <div className="px-4 py-5 sm:px-7 sm:py-6">
            <div
              className="inline-flex items-center gap-2 rounded-[10px] px-3 py-1.5 text-[12px] font-semibold"
              style={{ backgroundColor: hexToRgba(primaryColor, 0.09), color: getAccessibleAccent(primaryColor) }}
            >
              <span className="h-1.5 w-1.5 rounded-full" style={{ backgroundColor: primaryColor, color: getReadableTextColor(primaryColor) }} />
              <span>Cadastro do cliente</span>
            </div>
            <h1 className="mt-4 text-[26px] font-semibold tracking-[-0.04em] text-zinc-950 sm:mt-5 sm:text-[30px]">Meus dados</h1>
            <p className="mt-2 max-w-[560px] text-[14px] leading-6 text-zinc-600">
              Mantenha suas informações atualizadas para agilizar atendimento, pagamento e entrega.
            </p>
          </div>

          <div className="border-t border-[#efedf2] px-4 py-5 sm:px-7 sm:py-6 xl:border-l xl:border-t-0">
            <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-zinc-400">Resumo</div>
            <div className="mt-3 text-[24px] font-semibold tracking-[-0.04em] text-zinc-950">{completion}%</div>
            <div className="mt-2 text-[13px] text-zinc-500">Perfil completo para uso no portal.</div>
            <div className="mt-5 border-t border-[#efedf2] pt-4 text-[13px] text-zinc-600">
              {incompleteFields.length > 0 ? `Pendências: ${incompleteFields.join(", ")}` : "Sem pendências no cadastro."}
            </div>
          </div>
        </div>
      </section>

      <div className="grid gap-5 xl:grid-cols-[360px_minmax(0,1fr)]">
        <section className="border border-[#efedf2] bg-white px-4 py-4 sm:px-6 sm:py-5">
          <div className="text-[15px] font-semibold text-zinc-950">Resumo da conta</div>
          <div className="mt-5 space-y-4">
            <OverviewActionRow label="Cliente" value={profileName} />
            <OverviewActionRow label="Documento" value={client.document || "Não informado"} />
            <OverviewActionRow label="E-mail" value={client.email || "Não informado"} />
            <OverviewActionRow label="Telefone" value={formatPhoneDisplay(client.phone) || "Não informado"} />
            <div className="border-t border-[#efedf2] pt-4">
              <div className="text-[13px] text-zinc-500">Entrega</div>
              <div className="mt-2 text-[13px] leading-6 text-zinc-950">{addressSummary}</div>
            </div>
          </div>
        </section>

        <div className="space-y-5">
          <section className="border border-[#efedf2] bg-white px-4 py-4 sm:px-6 sm:py-5">
            <div className="text-[15px] font-semibold text-zinc-950">Acesso ao portal</div>
            <div className="mt-2 text-[13px] leading-6 text-zinc-500">
              Redefina sua senha sempre que precisar. O link sera enviado para o e-mail usado no cadastro.
            </div>
            <div className="mt-5 space-y-4">
              <OverviewActionRow label="E-mail de acesso" value={client.email || "Nao informado"} />
              <div className="border-t border-[#efedf2] pt-4">
                {client.email ? (
                  <Link
                    href={`/${slug}/cliente/redefinir-senha?email=${encodeURIComponent(client.email)}`}
                    className="inline-flex h-10 items-center border border-[#efedf2] px-4 text-sm font-semibold text-zinc-700 transition hover:bg-zinc-50 hover:text-zinc-950"
                    style={{ color: getAccessibleAccent(primaryColor) }}
                  >
                    Redefinir senha
                  </Link>
                ) : (
                  <div className="text-[13px] text-zinc-500">
                    Cadastre um e-mail no perfil para receber o link de redefinicao.
                  </div>
                )}
              </div>
            </div>
          </section>

          <section className="border border-[#efedf2] bg-white px-4 py-4 sm:px-6 sm:py-5">
            <div className="text-[15px] font-semibold text-zinc-950">Editar cadastro</div>
            <div className="mt-2 text-[13px] leading-6 text-zinc-500">
              Os dados abaixo sao os mesmos utilizados no portal e no acompanhamento dos pedidos.
            </div>
            <div className="mt-5">
              <ClientPortalProfileForm
                slug={slug}
                initial={client}
                primaryColor={primaryColor}
              />
            </div>
          </section>
        </div>
      </div>
    </div>
  );
}

export function AddressesSection({
  client,
  primaryColor,
  completion,
  onOpenSection,
  slug,
  onClientChange,
}: {
  slug: string;
  client: ClientPortalClient;
  primaryColor?: string;
  completion?: number;
  onOpenSection?: () => void;
  onClientChange?: (client: ClientPortalClient) => void;
}) {
  const addressSummary = getAddressSummary(client);
  const completionValue = typeof completion === "number" ? completion : getProfileCompletion(client);
  const recipientName = client.company_name || client.name || "Não informado";

  return (
    <div className="space-y-6">
      <section className="border border-[#efedf2] bg-white">
        <div className="grid gap-0 xl:grid-cols-[minmax(0,1fr)_320px]">
          <div className="px-4 py-5 sm:px-7 sm:py-6">
            <div
              className="inline-flex items-center gap-2 rounded-[10px] px-3 py-1.5 text-[12px] font-semibold"
              style={{ backgroundColor: hexToRgba(primaryColor || "#18181b", 0.09), color: primaryColor || "#18181b" }}
            >
              <span className="h-1.5 w-1.5 rounded-full" style={{ backgroundColor: primaryColor || "#18181b" }} />
              <span>{addressSummary ? "Entrega cadastrada" : "Entrega pendente"}</span>
            </div>
            <h1 className="mt-4 text-[26px] font-semibold tracking-[-0.04em] text-zinc-950 sm:mt-5 sm:text-[30px]">Entrega</h1>
            <p className="mt-2 max-w-[560px] text-[14px] leading-6 text-zinc-600">
              Revise o endereço usado nas compras para evitar divergências em retirada, entrega e contato.
            </p>
          </div>

          <div className="border-t border-[#efedf2] px-4 py-5 sm:px-7 sm:py-6 xl:border-l xl:border-t-0">
            <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-zinc-400">Perfil</div>
            <div className="mt-3 text-[24px] font-semibold tracking-[-0.04em] text-zinc-950">{completionValue}%</div>
            <div className="mt-2 text-[13px] text-zinc-500">Cadastro concluído para compras e entregas.</div>
          </div>
        </div>
      </section>

      {addressSummary ? (
        <section className="border border-[#efedf2] bg-white px-4 py-4 sm:px-6 sm:py-5">
          <div className="text-[15px] font-semibold text-zinc-950">Endereço principal</div>
          <div className="mt-5 grid gap-4 sm:grid-cols-2">
            <OverviewActionRow label="Destinatário" value={recipientName} />
            <OverviewActionRow label="CEP" value={client.address_zip || "Não informado"} />
            <OverviewActionRow label="Logradouro" value={client.address_street || "Não informado"} />
            <OverviewActionRow label="Número" value={client.address_number || "Não informado"} />
            <OverviewActionRow label="Bairro" value={client.address_neighborhood || "Não informado"} />
            <OverviewActionRow label="Cidade / UF" value={[client.address_city, client.address_state].filter(Boolean).join(" / ") || "Não informado"} />
          </div>
          {client.address_complement ? (
            <div className="mt-5 border-t border-[#efedf2] pt-4">
              <div className="text-[13px] text-zinc-500">Complemento</div>
              <div className="mt-2 text-[13px] leading-6 text-zinc-950">{client.address_complement}</div>
            </div>
          ) : null}
          {onOpenSection ? (
            <div className="mt-5 border-t border-[#efedf2] pt-4">
              <button
                type="button"
                onClick={onOpenSection}
                className="inline-flex h-10 items-center border border-[#efedf2] px-4 text-sm font-semibold text-zinc-700 transition hover:bg-zinc-50 hover:text-zinc-950"
              >
                Atualizar endereço
              </button>
            </div>
          ) : null}
        </section>
      ) : (
        <section className="border border-[#efedf2] bg-white px-4 py-7 text-center sm:px-6 sm:py-8">
          <MapPin className="mx-auto h-10 w-10 text-zinc-300" />
          <div className="mt-4 text-[20px] font-semibold tracking-[-0.03em] text-zinc-950">Nenhum endereço cadastrado</div>
          <p className="mx-auto mt-2 max-w-[520px] text-[14px] leading-6 text-zinc-500">
            Adicione um endereço no seu cadastro para facilitar a entrega e manter os dados consistentes em todos os pedidos.
          </p>
          {onOpenSection ? (
            <button
              type="button"
              onClick={onOpenSection}
              className="mt-5 inline-flex h-11 items-center border border-[#efedf2] px-5 text-sm font-semibold text-zinc-700 transition hover:bg-zinc-50 hover:text-zinc-950"
              style={primaryColor ? { color: primaryColor } : undefined}
            >
              Completar perfil ({completionValue}%)
            </button>
          ) : null}
        </section>
      )}

      <section className="border border-[#efedf2] bg-white px-4 py-4 sm:px-6 sm:py-5">
        <ClientAddressBook
          slug={slug}
          client={client}
          primaryColor={primaryColor || "#18181b"}
          onClientChange={onClientChange}
        />
      </section>
    </div>
  );
}

export function CatalogSection({
  slug,
  storeName,
  primaryColor,
  onOpenSection,
}: {
  slug: string;
  storeName: string;
  primaryColor: string;
  onOpenSection: () => void;
}) {
  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-semibold text-zinc-900">Catálogo</h1>
        <p className="mt-1 text-sm text-zinc-500">Volte para a loja e continue comprando</p>
      </div>

      <PremiumCard className="p-8 text-center">
        <div className="p-4 rounded-2xl bg-blue-50 inline-flex items-center justify-center mb-6">
          <Package className="h-12 w-12 text-blue-600" />
        </div>
        <h3 className="text-xl font-semibold text-zinc-900 mb-4">
          Voltar para {storeName}
        </h3>
        <p className="text-sm text-zinc-500 mb-6 max-w-md mx-auto">
          Continue explorando nossos produtos e faça seu próximo pedido.
        </p>
        <div className="flex flex-col sm:flex-row gap-3 justify-center">
          <Link
            href={`/${slug}`}
            className="inline-flex items-center gap-2 px-6 py-3 rounded-xl text-sm font-medium text-white transition hover:opacity-90"
            style={{ background: `linear-gradient(135deg, ${primaryColor} 0%, ${hexToRgba(primaryColor, 0.8)} 100%)` }}
          >
            <Package className="h-4 w-4" />
            Ver Catálogo
          </Link>
          <button
            onClick={onOpenSection}
            className="inline-flex items-center gap-2 px-6 py-3 rounded-xl border border-zinc-200 bg-white text-sm font-medium text-zinc-700 transition hover:border-zinc-300 hover:text-zinc-900"
          >
            Meus Pedidos
          </button>
        </div>
      </PremiumCard>
    </div>
  );
}

export type FavoriteProduct = {
  id: string;
  name: string;
  price: number;
  image_url: string | null;
  price_on_request: boolean;
  unit_type: string;
  product_price_tiers?: unknown[];
};

export type ReviewHistoryItem = {
  id: string;
  product_id: string;
  product_name: string;
  product_image_url: string | null;
  rating: number;
  comment: string;
  status: "pending" | "approved" | "rejected";
  created_at: string;
  updated_at?: string | null;
};

export function FavoritesSection({
  slug,
  primaryColor,
  favoriteProducts,
  onOpenCatalog,
  clientId,
}: {
  slug: string;
  primaryColor: string;
  favoriteProducts: FavoriteProduct[];
  onOpenCatalog: () => void;
  clientId?: string | null;
}) {
  return (
    <div className="space-y-6">
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div>
          <h1 className="text-2xl font-semibold text-zinc-900">Meus Favoritos</h1>
          <p className="mt-1 text-sm text-zinc-500">Produtos que você salvou para ver depois</p>
        </div>
      </div>

      {favoriteProducts.length === 0 ? (
        <PremiumCard className="p-12 text-center flex flex-col items-center">
          <div className="w-16 h-16 rounded-full bg-rose-50 flex items-center justify-center mb-4">
            <Heart className="w-8 h-8 text-rose-300" />
          </div>
          <h3 className="text-lg font-semibold text-zinc-900 mb-2">Sua lista está vazia</h3>
          <p className="text-sm text-zinc-500 max-w-md mx-auto mb-6">
            Você ainda não favoritou nenhum produto. Navegue pelo catálogo e clique no coração para salvar os produtos que você mais gostar.
          </p>
          <button
            onClick={onOpenCatalog}
            className="px-6 py-2.5 bg-zinc-900 text-white text-sm font-medium rounded-xl hover:bg-zinc-800 transition-colors"
          >
            Explorar Catálogo
          </button>
        </PremiumCard>
      ) : (
        <div className="grid grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-3">
          {favoriteProducts.map((product) => (
            <Link
              key={product.id}
              href={`/${slug}/p/${product.id}`}
              className="group flex min-h-[138px] flex-col overflow-hidden border border-gray-200 bg-white transition-all hover:shadow-md sm:h-[160px] sm:flex-row md:h-[180px]"
            >
              <div className="relative flex h-[180px] w-full flex-shrink-0 items-center justify-center bg-gray-100 p-2 sm:h-full sm:w-[160px] sm:min-w-[160px] md:w-[180px] md:min-w-[180px]">
                {product.image_url ? (
                  <img
                    src={product.image_url}
                    alt={product.name}
                    className="max-w-full max-h-full object-contain mix-blend-multiply"
                  />
                ) : (
                  <ShoppingBag className="text-gray-300 w-12 h-12" />
                )}
                <ClientPortalFavoriteButton
                  productId={product.id}
                  clientId={clientId}
                  initialFavorites={favoriteProducts.map((p) => p.id)}
                  primaryColor={primaryColor}
                />
              </div>
              
              <div className="p-4 flex flex-col flex-1 min-w-0">
                <h3 className="mb-1 line-clamp-2 text-[15px] font-medium leading-tight text-zinc-900 md:text-base" title={product.name}>
                  {product.name}
                </h3>
                
                {/* Mocked Rating Stars for visual match */}
                <div className="flex items-center gap-0.5 mb-2">
                  {[...Array(5)].map((_, i) => (
                    <svg key={i} className="w-3.5 h-3.5 fill-current" style={{ color: getAccessibleAccent(primaryColor) }} viewBox="0 0 20 20">
                      <path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z" />
                    </svg>
                  ))}
                </div>

                <div className="mt-auto">
                  {product.price_on_request ? (
                    <p className="text-lg font-bold tracking-tight text-zinc-900">Preço sob consulta</p>
                  ) : (
                    <>
                      <p className="text-xl md:text-2xl font-bold text-zinc-900 tracking-tight leading-none">
                        {new Intl.NumberFormat("pt-BR", { style: "currency", currency: "BRL" }).format(product.price)}
                      </p>
                      <div className="mt-2 inline-flex items-center px-4 py-1 border border-zinc-400 rounded-full text-[11px] font-bold text-zinc-700 hover:bg-zinc-50 transition-colors uppercase tracking-wider">
                        Seleção
                      </div>
                    </>
                  )}
                </div>
              </div>
            </Link>
          ))}
        </div>
      )}
    </div>
  );
}

export function ReviewsSection({
  slug,
  reviews,
  onOpenCatalog,
}: {
  slug: string;
  reviews: ReviewHistoryItem[];
  onOpenCatalog: () => void;
}) {
  const statusMap: Record<ReviewHistoryItem["status"], { label: string; className: string }> = {
    pending: {
      label: "Aguardando aprovacao",
      className: "bg-amber-50 text-amber-700 border-amber-200",
    },
    approved: {
      label: "Publicado",
      className: "bg-emerald-50 text-emerald-700 border-emerald-200",
    },
    rejected: {
      label: "Precisa revisar",
      className: "bg-rose-50 text-rose-700 border-rose-200",
    },
  };

  return (
    <div className="space-y-6">
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div>
          <h1 className="text-2xl font-semibold text-zinc-900">Minhas Avaliacoes</h1>
          <p className="mt-1 text-sm text-zinc-500">Produtos que voce comentou e avaliou</p>
        </div>
      </div>

      {reviews.length === 0 ? (
        <PremiumCard className="p-12 text-center flex flex-col items-center">
          <div className="w-16 h-16 rounded-full bg-amber-50 flex items-center justify-center mb-4">
            <Star className="w-8 h-8 text-amber-300" />
          </div>
          <h3 className="text-lg font-semibold text-zinc-900 mb-2">Nenhuma avaliacao enviada</h3>
          <p className="text-sm text-zinc-500 max-w-md mx-auto mb-6">
            Quando voce comentar algum produto, ele aparecera aqui com o status da aprovacao.
          </p>
          <button
            onClick={onOpenCatalog}
            className="px-6 py-2.5 bg-zinc-900 text-white text-sm font-medium rounded-xl hover:bg-zinc-800 transition-colors"
          >
            Ir para o catalogo
          </button>
        </PremiumCard>
      ) : (
        <div className="grid grid-cols-1 gap-4 xl:grid-cols-2">
          {reviews.map((review) => {
            const status = statusMap[review.status];

            return (
              <Link
                key={review.id}
                href={`/${slug}/p/${review.product_id}`}
                className="group overflow-hidden rounded-[28px] border border-zinc-200 bg-white transition hover:shadow-md"
              >
                <div className="flex min-h-[180px] flex-col sm:flex-row">
                  <div className="relative flex h-[180px] w-full items-center justify-center bg-zinc-100 p-3 sm:h-auto sm:w-[150px] sm:min-w-[150px]">
                    {review.product_image_url ? (
                      <img
                        src={review.product_image_url}
                        alt={review.product_name}
                        className="max-h-full max-w-full object-contain mix-blend-multiply"
                      />
                    ) : (
                      <ShoppingBag className="h-10 w-10 text-zinc-300" />
                    )}
                  </div>

                  <div className="flex min-w-0 flex-1 flex-col p-4 sm:p-5">
                    <div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
                      <div className="min-w-0">
                        <h3 className="line-clamp-2 text-base font-semibold text-zinc-900">
                          {review.product_name}
                        </h3>
                        <div className="mt-2 flex items-center gap-1">
                          {Array.from({ length: 5 }).map((_, index) => (
                            <Star
                              key={index}
                              className={index + 1 <= review.rating ? "h-4 w-4 fill-amber-400 text-amber-400" : "h-4 w-4 text-zinc-300"}
                            />
                          ))}
                        </div>
                      </div>
                      <span className={`inline-flex rounded-full border px-2.5 py-1 text-[11px] font-semibold ${status.className}`}>
                        {status.label}
                      </span>
                    </div>

                    <p className="mt-3 line-clamp-3 text-sm leading-6 text-zinc-600">
                      {review.comment || "Avaliacao sem comentario detalhado."}
                    </p>

                    <div className="mt-auto pt-4 text-xs text-zinc-500">
                      Enviado em {formatDate(review.created_at)}
                    </div>
                  </div>
                </div>
              </Link>
            );
          })}
        </div>
      )}
    </div>
  );
}

export function FinanceSection({
  latestOrder,
  totalSpent,
  orders,
}: {
  latestOrder: ClientPortalOrder | null;
  totalSpent: number;
  orders: ClientPortalOrder[];
}) {
  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-semibold text-zinc-900">Pagamentos</h1>
        <p className="mt-1 text-sm text-zinc-500">Resumo financeiro das suas compras</p>
      </div>

      <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
        <PremiumCard className="p-5">
          <div className="flex items-center gap-4">
            <div className="p-3 rounded-xl bg-green-50">
              <CreditCard className="h-6 w-6 text-green-600" />
            </div>
            <div>
              <div className="text-2xl font-semibold text-zinc-900">
                {formatMoney(totalSpent)}
              </div>
              <div className="text-sm text-zinc-500">Total Gasto</div>
            </div>
          </div>
        </PremiumCard>

        <PremiumCard className="p-5">
          <div className="flex items-center gap-4">
            <div className="p-3 rounded-xl bg-blue-50">
              <Package className="h-6 w-6 text-blue-600" />
            </div>
            <div>
              <div className="text-2xl font-semibold text-zinc-900">{orders.length}</div>
              <div className="text-sm text-zinc-500">Pedidos Realizados</div>
            </div>
          </div>
        </PremiumCard>

        {latestOrder && (
          <PremiumCard className="p-5">
            <div className="flex items-center gap-4">
              <div className="p-3 rounded-xl bg-purple-50">
                <Calendar className="h-6 w-6 text-purple-600" />
              </div>
              <div>
                <div className="text-lg font-semibold text-zinc-900">
                  {latestOrder ? `#${latestOrder.number}` : 'Nenhum'}
                </div>
                <div className="text-sm text-zinc-500">Último Pedido</div>
              </div>
            </div>
          </PremiumCard>
        )}
      </div>

      {orders.length > 0 && (
        <PremiumCard className="p-6">
          <h3 className="text-lg font-semibold text-zinc-900 mb-4">Histórico de Pagamentos</h3>
          <div className="space-y-3">
            {orders.slice(0, 5).map((order) => (
              <div key={order.id} className="flex items-center justify-between py-2 border-b border-zinc-100 last:border-b-0">
                <div>
                  <div className="text-sm font-medium text-zinc-900">Pedido #{order.number}</div>
                  <div className="text-xs text-zinc-500">{formatDate(order.created_at)}</div>
                </div>
                <div className="text-sm font-semibold text-zinc-900">
                  {formatMoney(order.total_amount)}
                </div>
              </div>
            ))}
          </div>
        </PremiumCard>
      )}
    </div>
  );
}

export function SupportSection({
  onOpenOrders,
  onOpenAccount,
  primaryColor,
  storeEmail,
  storeWhatsapp,
  storePhone,
  storeAddress,
}: {
  onOpenOrders: () => void;
  onOpenAccount: () => void;
  primaryColor?: string;
  storeEmail?: string | null;
  storeWhatsapp?: string | null;
  storePhone?: string | null;
  storeAddress?: string | null;
}) {
  const whatsappDigits = String(storeWhatsapp || "").replace(/\D/g, "");
  const whatsappUrl = whatsappDigits ? `https://wa.me/${whatsappDigits}` : null;

  return (
    <div className="space-y-6">
      <section className="border border-[#efedf2] bg-white">
        <div className="grid gap-0 xl:grid-cols-[minmax(0,1fr)_320px]">
          <div className="px-4 py-5 sm:px-7 sm:py-6">
            <div
              className="inline-flex items-center gap-2 rounded-[10px] px-3 py-1.5 text-[12px] font-semibold"
              style={{ backgroundColor: hexToRgba(primaryColor || "#18181b", 0.09), color: primaryColor || "#18181b" }}
            >
              <span className="h-1.5 w-1.5 rounded-full" style={{ backgroundColor: primaryColor || "#18181b" }} />
              <span>Atendimento</span>
            </div>
            <h1 className="mt-4 text-[26px] font-semibold tracking-[-0.04em] text-zinc-950 sm:mt-5 sm:text-[30px]">Ajuda e suporte</h1>
            <p className="mt-2 max-w-[560px] text-[14px] leading-6 text-zinc-600">
              Use os atalhos abaixo para acompanhar pedidos, revisar seus dados ou falar com a loja pelos canais disponíveis.
            </p>
          </div>

          <div className="border-t border-[#efedf2] px-4 py-5 sm:px-7 sm:py-6 xl:border-l xl:border-t-0">
            <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-zinc-400">Canal principal</div>
            <div className="mt-3 text-[24px] font-semibold tracking-[-0.04em] text-zinc-950">
              {storeWhatsapp ? "WhatsApp" : storeEmail ? "E-mail" : "Portal"}
            </div>
            <div className="mt-2 text-[13px] text-zinc-500">
              {storeWhatsapp || storeEmail || "Use os atalhos internos do portal para continuar o atendimento."}
            </div>
          </div>
        </div>
      </section>

      <section className="overflow-hidden border border-[#efedf2] bg-white">
        <div className="grid grid-cols-1 sm:grid-cols-2">
          <SupportActionTile
            title="Meus pedidos"
            subtitle="Acompanhar compras"
            icon={Package}
            onClick={onOpenOrders}
            primaryColor={primaryColor}
            className="border-b border-[#efedf2] sm:border-r"
          />
          <SupportActionTile
            title="Meus dados"
            subtitle="Revisar cadastro"
            icon={User}
            onClick={onOpenAccount}
            primaryColor={primaryColor}
            className="border-b border-[#efedf2]"
          />
          <SupportActionTile
            title="WhatsApp"
            subtitle={storeWhatsapp ? formatPhoneDisplay(storeWhatsapp) || "Abrir conversa" : "Indisponível"}
            icon={MessageCircle}
            href={whatsappUrl || undefined}
            primaryColor={primaryColor}
            className="sm:border-r sm:border-[#efedf2]"
          />
          <SupportActionTile
            title="E-mail"
            subtitle={storeEmail || "Indisponível"}
            icon={Mail}
            href={storeEmail ? `mailto:${storeEmail}` : undefined}
            primaryColor={primaryColor}
          />
        </div>
      </section>

      <section className="border border-[#efedf2] bg-white px-4 py-4 sm:px-6 sm:py-5">
        <div className="text-[15px] font-semibold text-zinc-950">Contato da loja</div>
        <div className="mt-5 space-y-0 border border-[#efedf2] bg-white">
          {storeEmail ? <ContactInfoRow label="E-mail" value={storeEmail} href={`mailto:${storeEmail}`} /> : null}
          {storeWhatsapp ? <ContactInfoRow label="WhatsApp" value={formatPhoneDisplay(storeWhatsapp) || storeWhatsapp} href={whatsappUrl || undefined} /> : null}
          {storePhone ? <ContactInfoRow label="Telefone" value={formatPhoneDisplay(storePhone) || storePhone} href={`tel:${String(storePhone).replace(/\D/g, "")}`} /> : null}
          {storeAddress ? <ContactInfoRow label="Endereço" value={storeAddress} /> : null}
          <ContactInfoRow label="Atendimento" value="Seg-Sex: Horário comercial" last />
        </div>
      </section>
    </div>
  );
}

export function SettingsSection({
  completion,
  lastLogin,
  onOpenAccount,
}: {
  completion: number;
  lastLogin?: string | null;
  onOpenAccount: () => void;
}) {
  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-semibold text-zinc-900">Configurações</h1>
        <p className="mt-1 text-sm text-zinc-500">Gerencie suas preferências e acesso</p>
      </div>

      <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
        <PremiumCard className="p-5">
          <div className="flex items-center gap-4">
            <div className="p-3 rounded-xl bg-blue-50">
              <User className="h-6 w-6 text-blue-600" />
            </div>
            <div>
              <div className="text-lg font-semibold text-zinc-900">{completion}%</div>
              <div className="text-sm text-zinc-500">Perfil Completo</div>
            </div>
          </div>
          <button
            onClick={onOpenAccount}
            className="mt-4 w-full text-sm font-medium text-blue-600 hover:text-blue-700"
          >
            Completar Perfil →
          </button>
        </PremiumCard>

        <PremiumCard className="p-5">
          <div className="flex items-center gap-4">
            <div className="p-3 rounded-xl bg-green-50">
              <Calendar className="h-6 w-6 text-green-600" />
            </div>
            <div>
              <div className="text-sm font-medium text-zinc-900">
                {lastLogin ? formatDateTime(lastLogin) : 'Primeiro acesso'}
              </div>
              <div className="text-xs text-zinc-500">Último Acesso</div>
            </div>
          </div>
        </PremiumCard>
      </div>

      <PremiumCard className="p-6">
        <h3 className="text-lg font-semibold text-zinc-900 mb-4">Preferências</h3>
        <div className="space-y-4">
          <div className="flex items-center justify-between">
            <div>
              <div className="text-sm font-medium text-zinc-900">Notificações por Email</div>
              <div className="text-xs text-zinc-500">Status de pedidos e promoções</div>
            </div>
            <div className="relative inline-flex h-6 w-11 items-center rounded-full bg-zinc-200">
              <div className="h-4 w-4 translate-x-1 rounded-full bg-white transition" />
            </div>
          </div>

          <div className="flex items-center justify-between">
            <div>
              <div className="text-sm font-medium text-zinc-900">Lembretes por WhatsApp</div>
              <div className="text-xs text-zinc-500">Alertas de entrega e novidades</div>
            </div>
            <div className="relative inline-flex h-6 w-11 items-center rounded-full bg-blue-600">
              <div className="h-4 w-4 translate-x-6 rounded-full bg-white transition" />
            </div>
          </div>
        </div>
      </PremiumCard>
    </div>
  );
}
