"use client";

import type { ComponentType } from "react";
import { Check, ChevronRight, CircleHelp, Download, Eye, MessageCircle, Package, Printer, Sparkles, Store, Truck } from "lucide-react";
import Image from "next/image";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { getAccessibleAccent, getReadableTextColor } from "@/lib/color-contrast";
import ConversaDoPedido from "@/components/client-portal/ConversaDoPedido";
import {
  type ClientPortalClient,
  type ClientPortalPaymentReceipt,
  ORDER_STATUS_LABEL,
  formatDate,
  formatDateTime,
  formatMoney,
  getStatusMeta,
  hexToRgba,
} from "@/components/client-portal/shared";

function WhatsAppIcon({ className = "" }: { className?: string }) {
  return (
    <svg viewBox="0 0 24 24" aria-hidden="true" className={className} fill="currentColor">
      <path d="M19.05 4.91A9.82 9.82 0 0 0 12.03 2C6.62 2 2.23 6.39 2.23 11.8c0 1.73.45 3.42 1.31 4.91L2.15 22l5.43-1.35a9.75 9.75 0 0 0 4.45 1.13h.01c5.4 0 9.79-4.39 9.8-9.8a9.72 9.72 0 0 0-2.79-7.07Zm-7.02 15.2h-.01a8.1 8.1 0 0 1-4.12-1.13l-.29-.17-3.22.8.86-3.14-.19-.32a8.1 8.1 0 0 1-1.24-4.34c0-4.48 3.64-8.13 8.13-8.13 2.17 0 4.22.85 5.75 2.39a8.07 8.07 0 0 1 2.38 5.75c0 4.48-3.65 8.13-8.05 8.13Zm4.46-6.08c-.24-.12-1.43-.7-1.66-.78-.22-.08-.39-.12-.55.12-.16.24-.63.78-.77.94-.14.16-.28.18-.52.06-.24-.12-1-.37-1.91-1.18-.7-.63-1.18-1.4-1.32-1.64-.14-.24-.01-.37.11-.49.11-.11.24-.28.37-.42.12-.14.16-.24.24-.4.08-.16.04-.3-.02-.42-.06-.12-.55-1.33-.76-1.82-.2-.48-.4-.41-.55-.42h-.47c-.16 0-.42.06-.64.3-.22.24-.84.82-.84 2s.86 2.32.98 2.48c.12.16 1.68 2.56 4.07 3.59.57.25 1.02.4 1.37.52.58.18 1.1.16 1.52.1.46-.07 1.43-.58 1.63-1.14.2-.56.2-1.04.14-1.14-.05-.1-.21-.16-.45-.28Z" />
    </svg>
  );
}

type OrderDetailsStandaloneProps = {
  slug: string;
  primaryColor: string;
  client: ClientPortalClient;
  storeWhatsapp?: string | null;
  storePhone?: string | null;
  details: {
    status_token?: string | null;
    status_payload?: {
      profile?: {
        slug?: string | null;
        store_name?: string | null;
        catalog_name?: 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;
      art_status?: "pending" | "approved" | "rejected" | null;
    };
    quote?: {
      id?: string | null;
      currency?: string | null;
      subtotal?: number | null;
      discount?: number | null;
      shipping?: number | null;
      total?: number | null;
      delivery_date?: string | null;
    } | null;
    catalog_shipping?: {
      provider?: string | null;
      provider_label?: string | null;
      carrier_name?: string | null;
      service_name?: string | null;
      amount?: number | null;
      delivery_time?: number | null;
      destination_zip?: string | null;
      logo_url?: string | null;
      pickup?: {
        name?: string | null;
        address_summary?: string | null;
        instructions?: string | null;
      } | null;
    } | null;
    delivery_address?: {
      source?: string | null;
      label?: string | null;
      recipient_name?: string | null;
      phone?: string | null;
      zip?: string | null;
      street?: string | null;
      number?: string | null;
      complement?: string | null;
      neighborhood?: string | null;
      city?: string | null;
      state?: string | null;
      reference?: string | null;
      summary?: string | null;
    } | null;
    delivery_tracking?: {
      codes: string[];
      url?: string | null;
      notes?: string | null;
      updated_at?: string | null;
    } | null;
    items?: Array<{
      id: string;
      product_name?: string | null;
      product_image_url?: string | null;
      title?: string | null;
      description?: string | null;
      quantity: number;
      unit_price: number;
      total_price: number;
    }>;
    payment_receipt?: ClientPortalPaymentReceipt | null;
  };
  onBackToOrders: () => void;
};

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: "Pago",
      backgroundColor: "#e9fbf0",
      color: "#1f9d57",
      borderColor: "#c4f1d3",
    };
  }

  if (normalized === "partially_paid") {
    return {
      label: "Parcial",
      backgroundColor: "#eff6ff",
      color: "#1d4ed8",
      borderColor: "#bfdbfe",
    };
  }

  if (normalized === "pending") {
    return {
      label: "Pendente",
      backgroundColor: "#fff7ed",
      color: "#c2410c",
      borderColor: "#fed7aa",
    };
  }

  if (normalized === "unpaid") {
    return {
      label: "Em aberto",
      backgroundColor: "#f5f5f5",
      color: "#52525b",
      borderColor: "#e4e4e7",
    };
  }

  if (normalized === "rejected" || normalized === "cancelled") {
    return {
      label: "Não aprovado",
      backgroundColor: "#fef2f2",
      color: "#b91c1c",
      borderColor: "#fecaca",
    };
  }

  return {
    label: "Registrado",
    backgroundColor: "#f5f5f5",
    color: "#52525b",
    borderColor: "#e4e4e7",
  };
}

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 buildWhatsappUrl(phone: string, message?: string) {
  const digits = String(phone || "").replace(/\D/g, "");
  if (!digits) return null;
  return `https://wa.me/${digits}${message ? `?text=${encodeURIComponent(message)}` : ""}`;
}

function formatZipCode(value: string | null | undefined) {
  const digits = String(value || "").replace(/\D/g, "");
  if (digits.length !== 8) return value || "-";
  return `${digits.slice(0, 5)}-${digits.slice(5)}`;
}

function formatShippingDeadline(days: number | null | undefined) {
  const safe = Number(days || 0);
  if (!Number.isFinite(safe) || safe <= 0) return "Prazo sob consulta";
  if (safe === 1) return "1 dia útil";
  return `${safe} dias úteis`;
}

function formatPickupDeadline(days: number | null | undefined) {
  const safe = Number(days || 0);
  if (!Number.isFinite(safe) || safe <= 0) return "Pronto para retirar";
  if (safe === 1) return "Pronto em 1 dia útil";
  return `Pronto em ${safe} dias úteis`;
}

function ActionTile({
  title,
  subtitle,
  href,
  icon: Icon,
  primaryColor,
  className,
}: {
  title: string;
  subtitle: string;
  href?: string | null;
  icon: ComponentType<{ className?: string }>;
  primaryColor: string;
  className?: string;
}) {
  const content = (
    <div className="grid min-h-[72px] grid-cols-[16px_minmax(0,1fr)_12px] items-start gap-x-3 px-4 py-4 sm:min-h-[80px] sm:grid-cols-[15px_minmax(0,1fr)_10px] sm:items-center">
      <span className="mt-0.5 shrink-0 text-[0] sm:mt-0" style={{ color: getAccessibleAccent(primaryColor) }}>
        <Icon className="h-4 w-4" />
      </span>
      <div className="min-w-0">
        <div className="break-words text-[12px] font-semibold leading-5 text-zinc-900">{title}</div>
        <div className="mt-1 break-words text-[11px] leading-5 text-zinc-500">{subtitle}</div>
      </div>
      <ChevronRight className="mt-0.5 h-3 w-3 shrink-0 text-zinc-400 sm:mt-0" />
    </div>
  );

  if (!href) {
    return <div className="opacity-60">{content}</div>;
  }

  const isExternal = /^https?:\/\//.test(href);
  if (isExternal) {
    return (
      <a href={href} target="_blank" rel="noreferrer" className={`transition hover:bg-[#fafafa] ${className || ""}`}>
        {content}
      </a>
    );
  }

  return (
    <Link href={href} className={`transition hover:bg-[#fafafa] ${className || ""}`}>
      {content}
    </Link>
  );
}

export default function OrderDetailsStandalone({
  slug,
  primaryColor,
  client,
  storeWhatsapp,
  storePhone,
  details,
  onBackToOrders,
}: OrderDetailsStandaloneProps) {
  const router = useRouter();
  const order = details.order;
  const items = Array.isArray(details.items) ? details.items : [];
  const leadItem = items[0] || null;
  const leadItemName = leadItem?.product_name || leadItem?.title || "Seu material";
  const leadItemImage = leadItem?.product_image_url || null;
  const paymentReceipt = details.payment_receipt || null;
  const publicStatus = details.status_payload || null;
  const publicOrder = publicStatus?.order || null;
  const publicProfile = publicStatus?.profile || null;
  const publicQuote = publicStatus?.quote || null;
  const currentStatus = String(publicOrder?.status || order.status || "").trim();
  const statusMeta = getStatusMeta(currentStatus || order.status, primaryColor);
  const statusDisplayLabel = String(
    publicOrder?.production_stage_label || order.production_stage_label || ORDER_STATUS_LABEL[currentStatus] || statusMeta.label
  ).trim();
  const paymentMethodLabel = String(paymentReceipt?.method_label || "").trim() || getPaymentMethodLabel(paymentReceipt?.method);
  const paymentConditionsLabel = String(paymentReceipt?.conditions_label || "").trim() || paymentMethodLabel;
  const paymentStatusMeta = getPaymentStatusMeta(paymentReceipt?.status);
  const lastUpdatedSource = String(publicOrder?.updated_at || publicOrder?.created_at || order.updated_at || order.created_at || "");
  /*
    Previsao de entrega, na ordem em que ela existe de verdade:
    1. a data combinada no pedido;
    2. a data do orcamento, quando o pedido nasceu de um;
    3. o prazo da entrega escolhida no checkout, contado do dia do pedido.
    Antes so a segunda linha era consultada — e pedido de catalogo nao tem
    orcamento. Dai a loja mostrar prazo na vitrine e o portal dizer "A definir".
  */
  const entregaCombinada = order.delivery_date || publicQuote?.delivery_date || null;
  const prazoDaEntrega = Number(details.catalog_shipping?.delivery_time || 0);
  const deliveryDate = entregaCombinada
    ? formatDate(String(entregaCombinada))
    : prazoDaEntrega > 0
      ? formatDate(
          new Date(
            new Date(String(order.created_at)).getTime() + prazoDaEntrega * 24 * 60 * 60 * 1000
          ).toISOString()
        )
      : null;
  const previsaoEhEstimativa = !entregaCombinada && prazoDaEntrega > 0;
  const entregaEhRetirada = Boolean(details.catalog_shipping?.pickup?.name);
  const entregaResumo = entregaEhRetirada
    ? String(details.catalog_shipping?.pickup?.name || "").trim()
    : [details.catalog_shipping?.carrier_name, details.catalog_shipping?.service_name]
        .map((parte) => String(parte || "").trim())
        .filter(Boolean)
        .join(" · ");
  const receiptUrl = `/${slug}/cliente/pedido/${order.id}/comprovante`;
  const statusToken = String(details.status_token || order.share_token || "").trim();
  const statusUrl = statusToken ? `/${slug}/status/${statusToken}` : null;
  const storeContact = String(publicProfile?.company_whatsapp || publicProfile?.phone || publicProfile?.company_phone || storeWhatsapp || storePhone || "");
  const whatsappUrl = buildWhatsappUrl(storeContact);
  const supportWhatsappUrl = buildWhatsappUrl(storeContact, `Olá! Preciso de ajuda com o pedido #${order.number}.`);
  const paymentReference = String(paymentReceipt?.reference || "").trim() || "-";
  const receiptIssuedAt = paymentReceipt?.paid_at || order.created_at;
  const receiptZigzagPoints = "0,100 5,0 10,100 15,0 20,100 25,0 30,100 35,0 40,100 45,0 50,100 55,0 60,100 65,0 70,100 75,0 80,100 85,0 90,100 95,0 100,100";
  const settledAmount = Number(order.paid_amount ?? paymentReceipt?.amount ?? 0);
  const pendingAmount = Math.max(0, Number(order.total_amount || 0) - settledAmount);
  const paymentIsSettled = paymentReceipt?.status === "approved" || paymentReceipt?.status === "partially_paid";
  const paymentHeaderLabel = paymentIsSettled ? "Pagamento do pedido" : "Status do pagamento";
  const paymentPrimaryLabel = paymentIsSettled ? "Pagamento" : "Status";
  const paymentPrimaryValue = paymentIsSettled ? paymentMethodLabel : paymentStatusMeta.label;
  const paymentSecondaryLabel = paymentIsSettled ? "Forma de pagamento" : "Situação";
  const paymentSecondaryValue = paymentIsSettled ? paymentConditionsLabel : "Aguardando baixa financeira";
  const paymentIssuedLabel = paymentIsSettled ? "Comprovante emitido em" : "Atualizado em";
  const paymentReferenceLabel = paymentIsSettled ? "Referência" : "Referência da tentativa";
  const paymentFootnote = paymentIsSettled
    ? "Documento emitido para acompanhamento do pagamento vinculado ao pedido."
    : "Documento emitido para acompanhamento do status financeiro do pedido no portal do cliente.";
  const quoteSubtotal = Math.max(
    0,
    Number(
      details.quote?.subtotal ??
        items.reduce((sum, item) => sum + Number(item.total_price || item.quantity * item.unit_price || 0), 0)
    )
  );
  const quoteDiscount = Math.max(0, Number(details.quote?.discount || 0));
  const quoteShipping = Math.max(
    0,
    Number(details.catalog_shipping?.amount ?? details.quote?.shipping ?? 0)
  );
  const quoteTotal = Number(details.quote?.total ?? order.total_amount ?? Math.max(0, quoteSubtotal - quoteDiscount + quoteShipping));
  const shippingIsPickup = String(details.catalog_shipping?.provider || "").toLowerCase() === "pickup";
  const pickupInstructions = String(details.catalog_shipping?.pickup?.instructions || "").trim();
  const pickupAddressSummary =
    String(details.catalog_shipping?.pickup?.address_summary || details.catalog_shipping?.carrier_name || "").trim();
  const shippingPrimaryLabel = shippingIsPickup
    ? String(details.catalog_shipping?.pickup?.name || details.catalog_shipping?.service_name || "").trim() ||
      "Retirada no balcão"
    : String(details.catalog_shipping?.service_name || details.catalog_shipping?.carrier_name || "").trim() ||
      "Frete do catálogo";
  const shippingSecondaryLabel =
    details.catalog_shipping?.service_name && details.catalog_shipping?.carrier_name
      ? details.catalog_shipping.carrier_name
      : details.catalog_shipping?.carrier_name || null;
  const deliveryAddressRecipient =
    String(details.delivery_address?.recipient_name || client.company_name || client.name || publicStatus?.client?.name || "").trim() || "Não informado";
  const deliveryAddressSummary =
    String(details.delivery_address?.summary || "").trim() ||
    [
      [
        String(details.delivery_address?.street || client.address_street || "").trim(),
        String(details.delivery_address?.number || client.address_number || "").trim(),
      ]
        .filter(Boolean)
        .join(", "),
      String(details.delivery_address?.complement || client.address_complement || "").trim(),
      String(details.delivery_address?.neighborhood || client.address_neighborhood || "").trim(),
      [
        String(details.delivery_address?.city || client.address_city || "").trim(),
        String(details.delivery_address?.state || client.address_state || "").trim(),
      ]
        .filter(Boolean)
        .join(" / "),
      formatZipCode(String(details.delivery_address?.zip || client.address_zip || "").trim()),
    ]
      .filter((value) => value && value !== "-")
      .join(" • ");
  const deliveryAddressPhone = String(details.delivery_address?.phone || client.phone || client.whatsapp || "").trim() || null;
  const deliveryAddressReference = String(details.delivery_address?.reference || "").trim() || null;
  const trackingCodes = Array.isArray(details.delivery_tracking?.codes) ? details.delivery_tracking?.codes : [];
  const trackingUrl = String(details.delivery_tracking?.url || "").trim() || null;
  const trackingNotes = String(details.delivery_tracking?.notes || "").trim() || null;
  const trackingUpdatedAt = details.delivery_tracking?.updated_at ? formatDateTime(details.delivery_tracking.updated_at) : null;
  const showCatalogCommercialDetails = Boolean(details.quote?.id) || quoteShipping > 0 || items.length > 0;
  const currentStatusDescription = (() => {
    switch (currentStatus) {
      case "pending_production":
        return "Seu pedido foi confirmado e está aguardando início da produção.";
      case "in_production":
        return "Seu pedido está em produção neste momento.";
      case "finished":
        return "Seu pedido foi finalizado e está pronto para a próxima etapa.";
      case "delivered":
        return "Seu pedido já foi entregue.";
      case "canceled":
        return "Este pedido foi cancelado.";
      default:
        return "Seu pedido segue em andamento.";
    }
  })();
  const currentStepKey = (() => {
    if (currentStatus === "delivered") return "delivered";
    if (currentStatus === "finished") return "finished";
    if (currentStatus === "in_production") return "in_production";
    return "pending_production";
  })();
  const steps = [
    {
      key: "pending_production",
      label: "Pedido confirmado",
      helper: formatDateTime(order.created_at),
      icon: Check,
    },
    {
      key: "in_production",
      label: "Em produção",
      helper: currentStepKey === "in_production" ? "Agora" : currentStepKey === "finished" || currentStepKey === "delivered" ? "Concluído" : "Aguardando",
      icon: Printer,
    },
    /* Os nomes tem que ser os mesmos que a loja ve no admin. "Acabamento" e
       "Saiu para entrega" diziam outra coisa: o pedido marcado como ENTREGUE
       aparecia para o cliente como se ainda estivesse a caminho. */
    {
      key: "finished",
      label: "Pronto",
      helper: currentStepKey === "finished" ? "Agora" : currentStepKey === "delivered" ? "Concluído" : "Aguardando",
      icon: Sparkles,
    },
    {
      key: "delivered",
      label: "Entregue",
      helper: currentStepKey === "delivered" ? "Concluído" : "Aguardando",
      icon: Truck,
    },
  ];
  const currentStepIndex = steps.findIndex((step) => step.key === currentStepKey);
  const updates = [
    {
      key: "current",
      title: statusDisplayLabel,
      description: currentStatusDescription,
      time: formatRelativeLabel(lastUpdatedSource),
    },
    paymentReceipt?.paid_at
      ? {
          key: "payment",
          title: "Pagamento identificado",
          description: "O pagamento foi confirmado e liberou o andamento do pedido.",
          time: formatRelativeLabel(paymentReceipt.paid_at),
        }
      : null,
    {
      key: "created",
      title: "Pedido confirmado",
      description: "Recebemos sua compra e iniciamos os preparativos.",
      time: formatDateTime(order.created_at),
    },
  ].filter(Boolean) as Array<{ key: string; title: string; description: string; time: string }>;

  return (
    <div className="-mx-3 min-h-[calc(100vh-76px)] bg-white px-3 py-5 text-zinc-950 sm:-mx-6 sm:px-6 sm:py-6 lg:-mx-8 lg:min-h-[calc(100vh-92px)] lg:px-8 lg:py-7">
      <div className="mx-auto max-w-[1280px]">
        <div className="flex flex-col gap-2 text-sm text-zinc-500 sm:flex-row sm:items-center sm:justify-between sm:gap-3">
          <div className="flex min-w-0 items-center gap-2 sm:gap-3">
            <button type="button" onClick={onBackToOrders} className="font-medium text-zinc-500 transition hover:text-zinc-900">
              Meus pedidos
            </button>
            <ChevronRight className="h-4 w-4 text-zinc-400" />
            <span className="truncate font-semibold text-zinc-900">Pedido #{order.number}</span>
          </div>
          <div className="flex items-center gap-2 text-[13px]">
            <span>Atualizado {formatRelativeLabel(lastUpdatedSource)}</span>
            <span className="h-1.5 w-1.5 rounded-full" style={{ backgroundColor: primaryColor, color: getReadableTextColor(primaryColor) }} />
          </div>
        </div>

        <div className="mt-4 grid gap-5 xl:grid-cols-[minmax(0,1fr)_360px] xl:gap-7">
          <div className="grid gap-5">
            <section className="grid items-start gap-5 sm:gap-6 lg:grid-cols-[220px_minmax(0,1fr)] xl:gap-8">
              <div className="flex items-start justify-center pt-1 lg:justify-start">
                <div className="relative h-[156px] w-[156px] overflow-hidden border border-[#efedf2] bg-white sm:h-[180px] sm:w-[180px]">
                  {leadItemImage ? (
                    <Image src={leadItemImage} alt={leadItemName} fill unoptimized className="object-cover" />
                  ) : (
                    <div className="flex h-full w-full items-center justify-center bg-white text-zinc-300">
                      <Package className="h-10 w-10" />
                    </div>
                  )}
                </div>
              </div>

              <div className="min-w-0 pt-0 sm:pt-2">
                <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>{statusDisplayLabel}</span>
                </div>
                <h1 className="mt-5 text-[22px] font-semibold tracking-[-0.03em] text-zinc-950 sm:mt-6 sm:text-[24px]">Pedido #{order.number}</h1>
                <div className="mt-1.5 text-[14px] text-zinc-700 sm:text-[15px]">{leadItemName}</div>
                <div className="mt-3 text-[18px] font-semibold leading-none" style={{ color: getAccessibleAccent(primaryColor) }}>
                  {formatMoney(order.total_amount)}
                </div>
                <div className="mt-4 text-[12px] text-zinc-500">Realizado em {formatDateTime(order.created_at)}</div>
              </div>
            </section>

            {/* Os atalhos ficavam na coluna estreita da direita, onde cada um
                virava uma coluna de tres letras. Aqui em cima, na largura da
                coluna central, cabem os tres lado a lado. */}
            <section className="overflow-hidden border border-[#efedf2] bg-white">
              {/* Eram quatro atalhos, dois deles mentindo: "Visualizar arte" abria a
                  pagina de status, porque arte anexada nao existe neste fluxo, e
                  "Solicitar suporte" abria o mesmo WhatsApp do atalho ao lado.
                  Ficaram os tres que fazem o que prometem. */}
              <div className="grid grid-cols-1 sm:grid-cols-3">
                {/* O atalho que antes nao abria arte nenhuma agora leva para a
                    conversa, que e onde a arte chega e e aprovada. */}
                <ActionTile
                  title={order.art_status === "pending" ? "Aprovar arte" : "Conversa e arte"}
                  subtitle={
                    order.art_status === "pending"
                      ? "A loja enviou uma arte"
                      : order.art_status === "approved"
                        ? "Arte aprovada"
                        : "Falar sobre este pedido"
                  }
                  href="#conversa-do-pedido"
                  icon={Eye}
                  primaryColor={primaryColor}
                  className="border-b border-[#efedf2] sm:border-b-0 sm:border-r"
                />
                <ActionTile
                  title="Falar com a loja"
                  subtitle="Tirar dúvidas no WhatsApp"
                  href={whatsappUrl}
                  icon={MessageCircle}
                  primaryColor={primaryColor}
                  className="border-b border-[#efedf2] sm:border-b-0 sm:border-r"
                />
                <ActionTile
                  title="Baixar comprovante"
                  subtitle="PDF da compra"
                  href={receiptUrl}
                  icon={Download}
                  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-900">Acompanhamento do pedido</div>

              <div className="mt-5 space-y-4 sm:hidden">
                {steps.map((step, index) => {
                  const isDone = index < currentStepIndex;
                  const isCurrent = index === currentStepIndex;
                  const Icon = step.icon;
                  return (
                    <div key={step.key} className="flex gap-3">
                      <div className="flex w-8 flex-col items-center">
                        <div
                          className="flex h-8 w-8 items-center justify-center rounded-full border text-sm"
                          style={
                            isCurrent
                              ? {
                                  backgroundColor: primaryColor,
                                  borderColor: hexToRgba(primaryColor, 0.24),
                                  color: getReadableTextColor(primaryColor),
                                  boxShadow: `0 0 0 4px ${hexToRgba(primaryColor, 0.08)}`,
                                }
                              : isDone
                                ? {
                                    backgroundColor: primaryColor,
                                    borderColor: primaryColor,
                                    color: getReadableTextColor(primaryColor),
                                  }
                                : {
                                    backgroundColor: "#ffffff",
                                    borderColor: "#ece7f2",
                                    color: "#8b8b98",
                                  }
                          }
                        >
                          <Icon className="h-4 w-4" />
                        </div>
                        {index < steps.length - 1 ? <div className="mt-2 h-full w-px bg-[#ece9f1]" /> : null}
                      </div>
                      <div className="min-w-0 pb-1">
                        <div className="text-[13px] font-semibold text-zinc-900">{step.label}</div>
                        <div className="mt-1 text-[12px] text-zinc-500">{step.helper}</div>
                      </div>
                    </div>
                  );
                })}
              </div>

              <div className="mt-7 hidden overflow-x-auto sm:block">
                <div className="relative min-w-[700px]">
                  <div className="absolute left-[8.5%] right-[8.5%] top-5 h-px border-t border-dashed border-[#e8e6eb]" />
                  <div className="grid grid-cols-4 gap-5">
                    {steps.map((step, index) => {
                      const isDone = index < currentStepIndex;
                      const isCurrent = index === currentStepIndex;
                      const Icon = step.icon;
                      return (
                        <div key={step.key} className="relative text-center">
                          <div className="mx-auto flex h-10 w-10 items-center justify-center rounded-full bg-white">
                            <div
                              className="flex h-10 w-10 items-center justify-center rounded-full border text-sm"
                              style={
                                isCurrent
                                  ? {
                                      backgroundColor: primaryColor,
                                      borderColor: hexToRgba(primaryColor, 0.24),
                                      color: getReadableTextColor(primaryColor),
                                      boxShadow: `0 0 0 6px ${hexToRgba(primaryColor, 0.08)}`,
                                    }
                                  : isDone
                                    ? {
                                        backgroundColor: primaryColor,
                                        borderColor: primaryColor,
                                        color: getReadableTextColor(primaryColor),
                                      }
                                    : {
                                        backgroundColor: "#ffffff",
                                        borderColor: "#ece7f2",
                                        color: "#8b8b98",
                                      }
                              }
                            >
                              <Icon className="h-4 w-4" />
                            </div>
                          </div>
                          <div className="mt-5 text-[12px] font-semibold text-zinc-900">{step.label}</div>
                          <div className="mt-1 text-[11px] text-zinc-500">{step.helper}</div>
                        </div>
                      );
                    })}
                  </div>
                </div>
              </div>

              {/* Antes: uma faixa lilas com o status a esquerda e um "Previsao de
                  entrega: A definir" solto na direita, sem dizer como o pedido
                  chega nem quando. Agora o estado explica a etapa e as linhas
                  abaixo respondem quando e por onde. */}
              <div
                className="mt-5 rounded-[14px] border px-4 py-3.5"
                style={{ backgroundColor: "#fbf8fe", borderColor: "#efedf2" }}
              >
                <div className="flex items-start gap-3">
                  <div
                    className="mt-0.5 flex h-9 w-9 shrink-0 items-center justify-center rounded-full"
                    style={{ backgroundColor: hexToRgba(primaryColor, 0.12), color: getAccessibleAccent(primaryColor) }}
                  >
                    <Sparkles className="h-4 w-4" />
                  </div>
                  <div className="min-w-0">
                    <div className="text-[13px] font-semibold text-zinc-900">{statusDisplayLabel}</div>
                    <div className="mt-0.5 text-[12px] leading-5 text-zinc-600">{currentStatusDescription}</div>
                  </div>
                </div>

                <dl className="mt-3 divide-y divide-[#efedf2] border-t border-[#efedf2] text-[13px]">
                  <div className="flex items-baseline justify-between gap-3 py-2">
                    <dt className="text-zinc-500">
                      {currentStatus === "delivered" ? "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-[11px] font-normal text-zinc-400">estimado</span>
                      ) : null}
                    </dd>
                  </div>
                  {/* O rastreio nao entra aqui de proposito: ele ja tem um painel
                      proprio na coluna da direita, com cada codigo em destaque. */}
                  {entregaResumo ? (
                    <div className="flex items-baseline justify-between gap-3 py-2">
                      <dt className="text-zinc-500">{entregaEhRetirada ? "Retirada" : "Envio por"}</dt>
                      <dd className="text-right font-semibold text-zinc-900">{entregaResumo}</dd>
                    </div>
                  ) : null}
                </dl>
              </div>
            </section>

            {/* Conversa do pedido: substitui o recado de mao unica que existia aqui.
                Mesmo desenho da conversa que a loja ve no admin. */}
            <ConversaDoPedido
              slug={slug}
              orderId={order.id}
              primaryColor={primaryColor}
              nomeDaLoja={publicProfile?.store_name || publicProfile?.catalog_name || null}
            />

            <section className="border border-[#efedf2] bg-white px-4 py-4 sm:px-6 sm:py-5">
              <div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between sm:gap-4">
                <div className="text-[15px] font-semibold text-zinc-900">Atualizações do pedido</div>
                <button type="button" onClick={() => router.refresh()} className="text-[13px] font-semibold transition hover:opacity-80" style={{ color: getAccessibleAccent(primaryColor) }}>
                  Atualizar
                </button>
              </div>

              <div className="mt-4 space-y-3.5">
                {updates.map((update, index) => (
                  <div key={update.key} className="flex gap-3">
                    <div className="flex w-7 flex-col items-center">
                      <div
                        className="flex h-7 w-7 items-center justify-center rounded-full"
                        style={{ backgroundColor: hexToRgba(primaryColor, index === 0 ? 0.14 : 0.08), color: getAccessibleAccent(primaryColor) }}
                      >
                        {index === updates.length - 1 ? <Check className="h-3.5 w-3.5" /> : <Printer className="h-3.5 w-3.5" />}
                      </div>
                      {index < updates.length - 1 ? <div className="mt-2 h-full w-px bg-[#ece9f1]" /> : null}
                    </div>
                    <div className="min-w-0 pb-1">
                      <div className="text-[13px] font-semibold text-zinc-900">{update.title}</div>
                      <div className="mt-0.5 text-[12px] text-zinc-500">{update.description}</div>
                      <div className="mt-1.5 text-[11px] text-zinc-400">{update.time}</div>
                    </div>
                  </div>
                ))}
              </div>
            </section>
          </div>

          <div className="grid content-start 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-900">Detalhes do pedido</div>

              <div className="relative mt-3 overflow-hidden bg-[#f8f7f4] px-4 pb-7 pt-4 sm:px-6 sm:pt-5">
                <div className="flex flex-col gap-2.5 border-b border-stone-200 pb-4 sm:flex-row sm:items-start sm:justify-between sm:gap-4">
                  <div>
                    <div className="text-[11px] font-medium uppercase tracking-[0.12em] text-slate-400">{paymentHeaderLabel}</div>
                    <div className="mt-1.5 text-[1.1rem] font-semibold tracking-[-0.04em] text-slate-950">Pedido #{order.number}</div>
                    <div className="mt-0.5 text-[12px] text-slate-500">
                      {paymentIssuedLabel} {formatDateTime(receiptIssuedAt)}
                    </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 className="space-y-3 pt-4 text-sm">
                  <div className="flex flex-col gap-1 sm:flex-row sm:items-center sm:justify-between sm:gap-4 text-slate-700">
                    <span>{paymentPrimaryLabel}</span>
                    <span className="break-words font-medium text-slate-950 sm:text-right">{paymentPrimaryValue}</span>
                  </div>
                  <div className="flex flex-col gap-1 sm:flex-row sm:items-center sm:justify-between sm:gap-4 text-slate-700">
                    <span>{paymentSecondaryLabel}</span>
                    <span className="break-words font-medium text-slate-950 sm:text-right">{paymentSecondaryValue}</span>
                  </div>
                  <div className="flex flex-col gap-1 sm:flex-row sm:items-center sm:justify-between sm:gap-4 text-slate-700">
                    <span>{paymentReferenceLabel}</span>
                    <span className="break-all font-medium text-slate-950 sm:text-right">{paymentReference}</span>
                  </div>
                </div>

                <div className="mt-4 border-t border-stone-200 pt-4">
                  <div className="flex flex-col gap-1 text-[1.05rem] font-semibold text-slate-950 sm:flex-row sm:items-center sm:justify-between sm:gap-4">
                    <span>Total do pedido</span>
                    <span className="sm:text-right">{formatMoney(order.total_amount)}</span>
                  </div>
                </div>

                <div className="mt-4 border-t border-stone-200 pt-4">
                  <div className="flex flex-col gap-1 text-[1.05rem] font-semibold text-slate-950 sm:flex-row sm:items-center sm:justify-between sm:gap-4">
                    <span>{paymentIsSettled ? "Valor pago" : "Valor pendente"}</span>
                    <span className="sm:text-right">{formatMoney(paymentIsSettled ? settledAmount : pendingAmount || order.total_amount)}</span>
                  </div>
                </div>

                {showCatalogCommercialDetails ? (
                  <div className="mt-4 border-t border-stone-200 pt-4">
                    <div className="text-[11px] font-semibold uppercase tracking-[0.12em] text-slate-400">Resumo comercial</div>

                    <div className="mt-2.5 space-y-2 text-[13px]">
                      {items.map((item) => {
                        const itemTitle = item.product_name || item.title || "Item";
                        return (
                          <div
                            key={item.id}
                            className="grid grid-cols-[1fr_auto] items-start gap-x-3 gap-y-1.5 border-b border-dashed border-stone-200 pb-2.5"
                          >
                            <div className="min-w-0 font-medium text-slate-900">{itemTitle}</div>
                            <div className="text-right font-semibold text-slate-950">{formatMoney(item.total_price)}</div>
                            <div className="text-[12px] text-slate-500">{item.quantity} x {formatMoney(item.unit_price)}</div>
                            <div className="text-right text-[11px] uppercase tracking-[0.1em] text-slate-400">Subtotal do item</div>
                          </div>
                        );
                      })}

                      <div className="space-y-2 pt-0.5 text-sm">
                        <div className="flex items-center justify-between gap-3 text-slate-700">
                          <span>Produtos</span>
                          <span className="font-semibold text-slate-950">{formatMoney(quoteSubtotal)}</span>
                        </div>
                        {quoteDiscount > 0 ? (
                          <div className="flex items-center justify-between gap-3 text-slate-700">
                            <span>Desconto</span>
                            <span className="font-semibold text-emerald-700">- {formatMoney(quoteDiscount)}</span>
                          </div>
                        ) : null}
                        <div className="flex items-center justify-between gap-3 text-slate-700">
                          <span>Frete</span>
                          <span className="font-semibold text-slate-950">{formatMoney(quoteShipping)}</span>
                        </div>
                        <div className="flex items-center justify-between gap-3 border-t border-stone-200 pt-2.5 text-[15px] font-semibold text-slate-950">
                          <span>Total do pedido</span>
                          <span>{formatMoney(quoteTotal)}</span>
                        </div>
                      </div>
                    </div>
                  </div>
                ) : null}

                {details.catalog_shipping ? (
                  <div className="mt-4 border-t border-stone-200 pt-4">
                    <div className="text-[11px] font-semibold uppercase tracking-[0.12em] text-slate-400">
                      {shippingIsPickup ? "Retirada escolhida" : "Frete escolhido"}
                    </div>

                    <div className="mt-2.5 space-y-2 text-sm">
                      <div className="grid grid-cols-[1fr_auto] items-start gap-3">
                        <div className="flex min-w-0 items-center gap-2.5">
                          {!shippingIsPickup && details.catalog_shipping.logo_url ? (
                            <Image
                              src={details.catalog_shipping.logo_url}
                              alt={details.catalog_shipping.carrier_name || shippingPrimaryLabel}
                              width={34}
                              height={34}
                              unoptimized
                              className="h-[34px] w-[34px] rounded-lg border border-stone-200 bg-white object-contain p-1"
                            />
                          ) : (
                            <div className="flex h-[34px] w-[34px] items-center justify-center rounded-lg border border-stone-200 bg-stone-50">
                              {shippingIsPickup ? (
                                <Store className="h-4 w-4 text-slate-500" />
                              ) : (
                                <Truck className="h-4 w-4 text-slate-500" />
                              )}
                            </div>
                          )}
                          <div className="min-w-0">
                            <div className="truncate font-semibold text-slate-950">{shippingPrimaryLabel}</div>
                            <div className="mt-0.5 flex flex-wrap items-center gap-1.5 text-[12px] text-slate-500">
                              {shippingIsPickup ? (
                                pickupAddressSummary ? <span>{pickupAddressSummary}</span> : null
                              ) : shippingSecondaryLabel ? (
                                <span>{shippingSecondaryLabel}</span>
                              ) : null}
                            </div>
                          </div>
                        </div>
                        <div className="text-right">
                          <div className="text-[11px] uppercase tracking-[0.1em] text-slate-400">Valor</div>
                          <div className="mt-0.5 text-[16px] font-semibold text-slate-950">
                            {shippingIsPickup && quoteShipping <= 0 ? "Grátis" : formatMoney(quoteShipping)}
                          </div>
                        </div>
                      </div>

                      <div className="grid gap-x-4 gap-y-2 border-t border-stone-200 pt-2.5 text-[13px] sm:grid-cols-2">
                        <div className="flex items-center justify-between gap-3 sm:block">
                          <div className="text-[11px] uppercase tracking-[0.1em] text-slate-400">Prazo</div>
                          <div className="font-semibold text-slate-950">
                            {shippingIsPickup
                              ? formatPickupDeadline(details.catalog_shipping.delivery_time)
                              : formatShippingDeadline(details.catalog_shipping.delivery_time)}
                          </div>
                        </div>
                        {shippingIsPickup ? (
                          pickupInstructions ? (
                            <div className="flex items-center justify-between gap-3 sm:block">
                              <div className="text-[11px] uppercase tracking-[0.1em] text-slate-400">Instruções</div>
                              <div className="font-semibold text-slate-950">{pickupInstructions}</div>
                            </div>
                          ) : null
                        ) : (
                          <div className="flex items-center justify-between gap-3 sm:block">
                            <div className="text-[11px] uppercase tracking-[0.1em] text-slate-400">CEP de destino</div>
                            <div className="font-semibold text-slate-950">
                              {formatZipCode(details.catalog_shipping.destination_zip)}
                            </div>
                          </div>
                        )}
                      </div>
                    </div>
                  </div>
                ) : null}

                {trackingCodes.length || trackingUrl || trackingNotes ? (
                  <div className="mt-4 border-t border-stone-200 pt-4">
                    <div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
                      <div className="text-[12px] font-semibold uppercase tracking-[0.12em] text-slate-400">Rastreamento</div>
                      {trackingUpdatedAt ? <div className="text-[11px] text-slate-500">Atualizado em {trackingUpdatedAt}</div> : null}
                    </div>

                    <div className="mt-2.5 rounded-[16px] border border-stone-200 bg-white px-3.5 py-3.5">
                      {trackingCodes.length ? (
                        <div className="space-y-2">
                          {trackingCodes.map((code) => (
                            <div key={code} className="flex flex-col gap-1 rounded-[12px] border border-stone-200 bg-stone-50 px-3 py-2.5">
                              <span className="text-[11px] uppercase tracking-[0.12em] text-slate-400">Código</span>
                              <span className="break-all font-semibold text-slate-950">{code}</span>
                            </div>
                          ))}
                        </div>
                      ) : null}

                      {trackingNotes ? (
                        <div className={`${trackingCodes.length ? "mt-3" : ""} rounded-[12px] border border-stone-200 bg-stone-50 px-3 py-2.5`}>
                          <div className="text-[11px] uppercase tracking-[0.12em] text-slate-400">Observações</div>
                          <div className="mt-1 whitespace-pre-wrap text-sm text-slate-700">{trackingNotes}</div>
                        </div>
                      ) : null}

                      {trackingUrl ? (
                        <a
                          href={trackingUrl}
                          target="_blank"
                          rel="noreferrer"
                          className="mt-3 inline-flex h-10 items-center justify-center rounded-[12px] px-4 text-sm font-semibold text-white transition hover:opacity-90"
                          style={{ backgroundColor: primaryColor, color: getReadableTextColor(primaryColor) }}
                        >
                          Acompanhar entrega
                        </a>
                      ) : null}
                    </div>
                  </div>
                ) : null}

                <div className="mt-4 border-t border-stone-200 pt-4">
                  <div className="text-[11px] font-semibold uppercase tracking-[0.12em] text-slate-400">Dados de entrega</div>

                  <div className="mt-2.5 grid gap-2 text-[13px]">
                    <div className="grid grid-cols-[92px_1fr] gap-3">
                      <span className="text-slate-500">Recebedor</span>
                      <span className="break-words font-medium text-slate-950">{deliveryAddressRecipient}</span>
                    </div>
                    <div className="grid grid-cols-[92px_1fr] gap-3">
                      <span className="text-slate-500">Endereço</span>
                      <span className="break-words font-medium leading-5 text-slate-950">
                        {deliveryAddressSummary || "Não informado"}
                      </span>
                    </div>
                    {deliveryAddressPhone ? (
                      <div className="grid grid-cols-[92px_1fr] gap-3">
                        <span className="text-slate-500">Contato</span>
                        <span className="break-words font-medium text-slate-950">{deliveryAddressPhone}</span>
                      </div>
                    ) : null}
                    {deliveryAddressReference ? (
                      <div className="grid grid-cols-[92px_1fr] gap-3">
                        <span className="text-slate-500">Referência</span>
                        <span className="break-words font-medium leading-5 text-slate-950">{deliveryAddressReference}</span>
                      </div>
                    ) : null}
                  </div>
                </div>

                <div className="mt-4 text-[11px] leading-5 text-slate-400">{paymentFootnote}</div>

                <div className="absolute inset-x-0 bottom-0 h-4 overflow-hidden">
                  <svg viewBox="0 0 100 100" preserveAspectRatio="none" className="h-full w-full">
                    <polygon points={receiptZigzagPoints} fill="#ffffff" />
                  </svg>
                </div>
              </div>
            </section>

            <section
              className="border px-4 py-3.5 sm:px-5"
              style={{
                backgroundColor: "#fbf8fe",
                borderColor: "#efedf2",
              }}
            >
              <div className="flex items-center justify-between gap-3">
                <div className="flex min-w-0 items-start gap-3">
                  <CircleHelp className="h-[18px] w-[18px] shrink-0" style={{ color: getAccessibleAccent(primaryColor) }} />
                  <div className="min-w-0">
                    <div className="text-[13px] font-semibold leading-5 text-zinc-900">Precisa de ajuda?</div>
                    <div className="mt-0.5 text-[12px] leading-5 text-zinc-600">Fale com nossa equipe.</div>
                  </div>
                </div>

                {supportWhatsappUrl ? (
                  <a
                    href={supportWhatsappUrl}
                    target="_blank"
                    rel="noreferrer"
                    aria-label="Abrir WhatsApp"
                    className="inline-flex h-9 w-9 shrink-0 items-center justify-center rounded-[6px] text-white transition hover:opacity-90"
                    style={{ backgroundColor: primaryColor, color: getReadableTextColor(primaryColor) }}
                  >
                    <WhatsAppIcon className="h-[22px] w-[22px]" />
                  </a>
                ) : (
                  <button
                    type="button"
                    disabled
                    aria-label="WhatsApp indisponível"
                    className="inline-flex h-9 w-9 shrink-0 items-center justify-center rounded-[6px] bg-zinc-200 text-zinc-500"
                  >
                    <WhatsAppIcon className="h-[22px] w-[22px]" />
                  </button>
                )}
              </div>
            </section>
          </div>
        </div>
      </div>
    </div>
  );
}
