import { useEffect, useMemo, useRef, useState } from "react";
import {
  ArrowLeft,
  Zap,
  Building2,
  Check,
  Clock,
  Contact,
  Copy,
  FileDown,
  Info,
  ListChecks,
  MessageCircle,
  Pencil,
  Pipette,
  Plus,
  Receipt,
  RotateCcw,
  Save,
  Search,
  Smartphone,
  Trash2,
  X,
  ChevronDown,
  ShieldCheck,
  CalendarClock,
  BadgeCheck,
  StickyNote,
} from "lucide-react";
import { Link } from "react-router-dom";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
} from "@/components/ui/dialog";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { Textarea } from "@/components/ui/textarea";
import { toast } from "sonner";
import { useLocalStorage, formatBRL } from "@/features/orcamento/storage";
import { DEFAULT_SERVICES } from "@/features/orcamento/defaults";
import {
  Budget,
  BudgetItem,
  ClientInfo,
  CompanyInfo,
  Service,
} from "@/features/orcamento/types";
import {
  buildWhatsappMessage,
  type PdfFormat,
  type PdfResult,
} from "@/features/orcamento/exporters";
import PdfPreviewModal from "@/features/orcamento/PdfPreviewModal";
import { extractBrandColors } from "@/features/orcamento/extractBrandColors";
import { Onboarding } from "@/features/orcamento/Onboarding";
import { LogoEyedropper } from "@/features/orcamento/LogoEyedropper";

const uid = () =>
  typeof crypto !== "undefined" && "randomUUID" in crypto
    ? crypto.randomUUID()
    : Math.random().toString(36).slice(2);

const emptyClient: ClientInfo = { name: "", phone: "", address: "" };

// Formata telefone brasileiro: (11) 91234-5678 ou (11) 1234-5678
const formatPhoneBR = (raw: string) => {
  const d = raw.replace(/\D/g, "").slice(0, 11);
  if (d.length === 0) return "";
  if (d.length <= 2) return `(${d}`;
  if (d.length <= 6) return `(${d.slice(0, 2)}) ${d.slice(2)}`;
  if (d.length <= 10)
    return `(${d.slice(0, 2)}) ${d.slice(2, 6)}-${d.slice(6)}`;
  return `(${d.slice(0, 2)}) ${d.slice(2, 7)}-${d.slice(7)}`;
};

// Switch deslizante com bom contraste em ambos os estados
const ToggleSwitch = ({
  checked,
  onChange,
  label,
}: {
  checked: boolean;
  onChange: () => void;
  label: string;
}) => (
  <button
    type="button"
    role="switch"
    aria-checked={checked}
    aria-label={label}
    onClick={(e) => {
      e.preventDefault();
      onChange();
    }}
    className={`relative inline-flex h-6 w-11 shrink-0 items-center rounded-full transition-colors duration-200 focus:outline-none focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-2 focus-visible:ring-offset-background ${
      checked ? "bg-primary" : "bg-input border border-border"
    }`}
  >
    <span
      aria-hidden="true"
      className={`inline-block h-5 w-5 rounded-full bg-white shadow ring-1 ring-black/10 transition-transform duration-200 ${
        checked ? "translate-x-[22px]" : "translate-x-0.5"
      }`}
    />
  </button>
);

const App = () => {
  const [services, setServices] = useLocalStorage<Service[]>(
    "elg.services.v1",
    DEFAULT_SERVICES,
  );
  const [company, setCompany] = useLocalStorage<CompanyInfo>("elg.company.v1", {
    name: "",
    document: "",
    contact: "",
    pixKey: "",
    warrantyEnabled: true,
    warrantyDays: 90,
    validityEnabled: true,
    validityDays: 7,
    inmetroEnabled: true,
    customNote: "",
  });
  const [client, setClient] = useLocalStorage<ClientInfo>(
    "elg.currentClient.v1",
    emptyClient,
  );
  const [items, setItems] = useLocalStorage<BudgetItem[]>(
    "elg.currentItems.v1",
    [],
  );
  const [kind, setKind] = useLocalStorage<"orcamento" | "pedido">(
    "elg.currentKind.v1",
    "orcamento",
  );
  // Número inicial aleatório (~1200-4800) pra parecer que já houve uso prévio.
  // Mantemos numa chave v2 e só geramos uma vez — o valor é persistido em localStorage.
  const initialCounter = useMemo(() => {
    if (typeof window === "undefined") return 1247;
    const stored = window.localStorage.getItem("elg.counter.v2");
    if (stored) return parseInt(stored, 10) || 1247;
    return 1200 + Math.floor(Math.random() * 3600);
  }, []);
  const [counter, setCounter] = useLocalStorage<number>("elg.counter.v2", initialCounter);
  const [laborCost, setLaborCost] = useLocalStorage<number>(
    "elg.currentLabor.v1",
    0,
  );
  const [materialCost, setMaterialCost] = useLocalStorage<number>(
    "elg.currentMaterial.v1",
    0,
  );
  const [history, setHistory] = useLocalStorage<Budget[]>(
    "elg.history.v1",
    [],
  );
  const [onboardingDone, setOnboardingDone] = useLocalStorage<boolean>(
    "elg.onboardingDone.v1",
    false,
  );

  const [tab, setTab] = useState<string>("budget");
  const [search, setSearch] = useState("");
  const [editingService, setEditingService] = useState<string | null>(null);
  const [whatsappOpen, setWhatsappOpen] = useState(false);
  const [whatsappMsg, setWhatsappMsg] = useState("");
  const [copied, setCopied] = useState(false);
  const [pulseId, setPulseId] = useState<string | null>(null);
  const [pickerOpen, setPickerOpen] = useState(false);
  const [pickerSearch, setPickerSearch] = useState("");
  const [newBudgetConfirmOpen, setNewBudgetConfirmOpen] = useState(false);
  const [customDraftName, setCustomDraftName] = useState("");
  const [customDraftPrice, setCustomDraftPrice] = useState("");
  const [pdfMenuOpen, setPdfMenuOpen] = useState(false);
  const [historyOpen, setHistoryOpen] = useState(false);
  const [eyedropperFor, setEyedropperFor] = useState<
    "primary" | "accent" | null
  >(null);
  const [companySaved, setCompanySaved] = useState(false);
  const [pdfOptionsOpen, setPdfOptionsOpen] = useState(false);
  const [pdfPreviewOpen, setPdfPreviewOpen] = useState(false);
  const [pdfPreview, setPdfPreview] = useState<PdfResult | null>(null);
  const [pdfPreviewMsg, setPdfPreviewMsg] = useState<string>("");
  const [pdfPreviewPhone, setPdfPreviewPhone] = useState<string>("");
  const [pdfPreviewTitle, setPdfPreviewTitle] = useState<string>("");
  const hasContactPicker =
    typeof navigator !== "undefined" &&
    // @ts-expect-error - Contact Picker API ainda não tipada
    typeof navigator.contacts?.select === "function";

  const itemsTotal = useMemo(
    () => items.reduce((s, it) => s + it.price * it.qty, 0),
    [items],
  );
  const total = itemsTotal + (laborCost || 0) + (materialCost || 0);

  const filteredServices = useMemo(() => {
    const q = search.trim().toLowerCase();
    if (!q) return services;
    return services.filter((s) => s.name.toLowerCase().includes(q));
  }, [services, search]);

  const qtyByServiceId = useMemo(() => {
    const map: Record<string, number> = {};
    items.forEach((it) => {
      if (it.serviceId) map[it.serviceId] = (map[it.serviceId] ?? 0) + it.qty;
    });
    return map;
  }, [items]);

  const addServiceToBudget = (s: Service) => {
    setItems((prev) => {
      const existing = prev.find((it) => it.serviceId === s.id);
      if (existing) {
        return prev.map((it) =>
          it.id === existing.id ? { ...it, qty: it.qty + 1 } : it,
        );
      }
      return [
        ...prev,
        { id: uid(), serviceId: s.id, name: s.name, price: s.price, qty: 1 },
      ];
    });
    const nextQty = (qtyByServiceId[s.id] ?? 0) + 1;
    setPulseId(s.id);
    window.setTimeout(() => setPulseId((cur) => (cur === s.id ? null : cur)), 350);
    toast.success(`${s.name} • ${nextQty}x no orçamento`, {
      action: {
        label: "Ver",
        onClick: () => {
          setTab("budget");
          window.scrollTo({ top: 0, behavior: "smooth" });
        },
      },
    });
  };

  const updateItem = (id: string, patch: Partial<BudgetItem>) => {
    setItems((prev) => prev.map((it) => (it.id === id ? { ...it, ...patch } : it)));
  };

  const removeItem = (id: string) => {
    setItems((prev) => prev.filter((it) => it.id !== id));
  };

  const addCustomItem = () => {
    setItems((prev) => [
      ...prev,
      { id: uid(), name: "Novo serviço", price: 0, qty: 1 },
    ]);
  };

  const buildBudget = (): Budget => ({
    id: uid(),
    number: counter,
    createdAt: new Date().toISOString(),
    client,
    items,
    kind,
    laborCost: laborCost > 0 ? laborCost : undefined,
    materialCost: materialCost > 0 ? materialCost : undefined,
  });

  const ensureReady = () => {
    if (items.length === 0 && laborCost <= 0 && materialCost <= 0) {
      toast.error("Adicione um serviço, mão de obra ou material.");
      return false;
    }
    return true;
  };

  const HISTORY_LIMIT = 20;
  const saveToHistory = (b: Budget) => {
    setHistory((prev) => [b, ...prev].slice(0, HISTORY_LIMIT));
  };

  const handlePDF = async (format: PdfFormat = "a4") => {
    if (!ensureReady()) return;

    // 1) Fecha o seletor de formato ANTES de abrir o preview (evita 2 dialogs sobrepostos no Android)
    setPdfMenuOpen(false);

    // 2) Abre o modal de preview já em estado de loading
    setPdfPreview(null);
    setPdfPreviewOpen(true);

    try {
      const { exportBudgetPDF } = await import("@/features/orcamento/exporters");
      const b = buildBudget();
      const result = await exportBudgetPDF(b, company, format);
      saveToHistory(b);
      setCounter((c) => c + 1);

      const docLabel = b.kind === "pedido" ? "Cobrança" : "Orçamento";
      setPdfPreview(result);
      setPdfPreviewMsg(buildWhatsappMessage(b, company));
      setPdfPreviewPhone(b.client.phone ?? "");
      setPdfPreviewTitle(`${docLabel} Nº ${String(b.number).padStart(4, "0")}`);
    } catch (error) {
      console.error("PDF generation failed:", error);
      toast.error("Erro ao gerar PDF. Tente novamente.");
      setPdfPreviewOpen(false);
    }
  };

  const handleWhatsapp = () => {
    if (!ensureReady()) return;
    const b = buildBudget();
    const msg = buildWhatsappMessage(b, company);
    setWhatsappMsg(msg);
    setCopied(false);
    setWhatsappOpen(true);
    saveToHistory(b);
    setCounter((c) => c + 1);
  };

  const copyWhatsappMsg = async () => {
    try {
      await navigator.clipboard.writeText(whatsappMsg);
      setCopied(true);
      toast.success("Mensagem copiada! Agora abra o WhatsApp e cole na conversa.");
    } catch {
      toast.error("Não foi possível copiar. Selecione e copie manualmente.");
    }
  };

  const openWhatsappLink = async () => {
    // Copia a mensagem ANTES de abrir (evita perder o gesto do usuário em mobile).
    // Não enviamos via ?text= no link porque o WhatsApp quebra emojis nesse fluxo.
    let copiedOk = false;
    try {
      await navigator.clipboard.writeText(whatsappMsg);
      copiedOk = true;
      setCopied(true);
      window.setTimeout(() => setCopied(false), 2000);
    } catch {
      copiedOk = false;
    }

    const phone = client.phone.replace(/\D/g, "");
    const url = phone ? `https://wa.me/55${phone}` : `https://wa.me/`;
    window.open(url, "_blank");

    if (copiedOk) {
      toast.success("Mensagem copiada! Cole na conversa (toque e segure).");
    } else {
      toast.error("Não foi possível copiar — copie manualmente antes de enviar.");
    }
  };

  const newBudget = () => {
    // Sempre leva pra aba do orçamento, mesmo se já estiver vazia.
    setTab("budget");
    if (items.length === 0 && !client.name) {
      toast.success("Pronto pra novo orçamento");
      return;
    }
    setNewBudgetConfirmOpen(true);
  };

  const confirmNewBudget = () => {
    setItems([]);
    setClient(emptyClient);
    setLaborCost(0);
    setMaterialCost(0);
    setNewBudgetConfirmOpen(false);
    toast.success("Novo orçamento iniciado");
  };

  // Importar telefone dos contatos do celular (Contact Picker API — Chrome Android)
  const importContact = async () => {
    if (!hasContactPicker) {
      toast.error(
        "Seu navegador não permite acessar contatos. Use Chrome no Android.",
      );
      return;
    }
    try {
      // @ts-expect-error - Contact Picker API
      const contacts = await navigator.contacts.select(["name", "tel"], {
        multiple: false,
      });
      if (!contacts || contacts.length === 0) return;
      const c = contacts[0];
      const name = Array.isArray(c.name) ? c.name[0] : c.name;
      const tel = Array.isArray(c.tel) ? c.tel[0] : c.tel;
      setClient({
        ...client,
        name: name || client.name,
        phone: (tel as string) || client.phone,
      });
      toast.success("Contato importado");
    } catch {
      toast.error("Não foi possível importar o contato.");
    }
  };

  // Service editor
  const addNewService = () => {
    const s: Service = { id: uid(), name: "Novo serviço", price: 0, unit: "un" };
    setServices((prev) => [s, ...prev]);
    setEditingService(s.id);
  };

  const updateService = (id: string, patch: Partial<Service>) => {
    setServices((prev) => prev.map((s) => (s.id === id ? { ...s, ...patch } : s)));
  };

  const removeService = (id: string) => {
    if (!confirm("Remover este serviço do catálogo?")) return;
    setServices((prev) => prev.filter((s) => s.id !== id));
  };

  // Logo upload + extração automática de cores
  const logoInputRef = useRef<HTMLInputElement>(null);
  const handleLogo = (file?: File) => {
    if (!file) return;
    const reader = new FileReader();
    reader.onload = async () => {
      const dataUrl = reader.result as string;
      const colors = await extractBrandColors(dataUrl);
      setCompany((c) => ({
        ...c,
        logoDataUrl: dataUrl,
        ...(colors && {
          brandColor: colors.primary,
          brandColorAccent: colors.accent,
          logoBackground: colors.background ?? undefined,
          logoAspectRatio: colors.aspectRatio,
        }),
      }));
      toast.success(
        colors
          ? "Logo e cores da marca detectadas"
          : "Logo atualizada",
      );
    };
    reader.readAsDataURL(file);
  };

  useEffect(() => {
    if (onboardingDone) {
      window.scrollTo(0, 0);
    }
  }, [onboardingDone]);

  useEffect(() => {
    document.title = "Eletri-Pro — Orçamentos Profissionais";
    const desc = "Crie orçamentos profissionais e envie por WhatsApp ou PDF em segundos.";
    let m = document.querySelector('meta[name="description"]');
    if (!m) {
      m = document.createElement("meta");
      m.setAttribute("name", "description");
      document.head.appendChild(m);
    }
    m.setAttribute("content", desc);

    // Bloqueio de back para a página de vendas se estiver no fluxo
    if (onboardingDone) {
      window.history.pushState(null, "", location.href);
      const onPopState = () => {
        window.history.pushState(null, "", location.href);
        toast.info("Você já está no sistema de orçamentos", {
          description: "Use o botão de novo orçamento se precisar limpar os dados.",
          duration: 2000
        });
      };
      window.addEventListener("popstate", onPopState);
      return () => window.removeEventListener("popstate", onPopState);
    }
  }, [onboardingDone]);

  return (
    <div className="flex min-h-dvh flex-col bg-background text-foreground overflow-x-hidden selection:bg-primary/20">
      {!onboardingDone && (
        <Onboarding
          company={company}
          setCompany={(updater) => setCompany(updater)}
          onDone={() => {
            setOnboardingDone(true);
            window.scrollTo(0, 0);
          }}
        />
      )}

      {/* Top bar */}
      <header className="sticky top-0 z-30 border-b border-border/60 bg-background/85 backdrop-blur pt-[env(safe-area-inset-top)] isolate">
        <div className="mx-auto flex max-w-3xl items-center justify-between gap-2 px-3 py-2.5 sm:px-4 sm:py-3">
          <div className="flex items-center gap-2">
            <span className="flex h-7 w-7 items-center justify-center rounded-md bg-primary text-primary-foreground">
              <Zap className="h-4 w-4" />
            </span>
            <span className="font-display text-sm uppercase tracking-wide text-muted-foreground">
              {company.numberPrefix?.trim()
                ? `${company.numberPrefix.trim()} · Nº ${String(counter).padStart(4, "0")}`
                : `Nº ${String(counter).padStart(4, "0")}`}
            </span>
          </div>
          <div className="flex items-center gap-1">
            <Button
              variant="ghost"
              size="icon"
              onClick={() => setHistoryOpen(true)}
              className="relative h-8 w-8 text-muted-foreground hover:text-foreground"
              aria-label="Histórico"
            >
              <Clock className="h-4 w-4" />
              {history.length > 0 && (
                <span className="absolute -right-0.5 -top-0.5 flex h-4 min-w-[16px] items-center justify-center rounded-full bg-primary px-1 text-[9px] font-bold text-primary-foreground">
                  {history.length > 99 ? "99+" : history.length}
                </span>
              )}
            </Button>
            <Button
              variant="ghost"
              size="sm"
              onClick={newBudget}
              className="h-8 px-2 text-xs"
            >
              Novo
            </Button>
          </div>
        </div>
      </header>

      <main className="mx-auto max-w-3xl px-3 pb-44 pt-3 sm:px-4 sm:pt-4">
        <Tabs value={tab} onValueChange={setTab} className="w-full">
          <TabsList className="grid w-full grid-cols-3 bg-secondary">
            <TabsTrigger value="budget" className="gap-1.5">
              <Receipt className="h-4 w-4" />
              <span className="text-[11px] sm:text-sm">Orçamento</span>
            </TabsTrigger>
            <TabsTrigger value="services" className="gap-1.5">
              <ListChecks className="h-4 w-4" />
              <span className="text-[11px] sm:text-sm">Serviços</span>
            </TabsTrigger>
            <TabsTrigger value="company" className="gap-1.5">
              <Building2 className="h-4 w-4" />
              <span className="text-[11px] sm:text-sm">Empresa</span>
            </TabsTrigger>
          </TabsList>

          {/* ======================== BUDGET ======================== */}
          <TabsContent value="budget" className="mt-6 space-y-7 sm:space-y-8">
            {/* Tipo do documento — pílula compacta */}
            <div className="inline-flex w-full rounded-full border border-border/60 bg-card p-1">
              {(["orcamento", "pedido"] as const).map((k) => {
                const active = kind === k;
                const label = k === "orcamento" ? "Orçamento" : "Cobrança";
                return (
                  <button
                    key={k}
                    type="button"
                    onClick={() => setKind(k)}
                    className={`flex-1 rounded-full px-3 py-1.5 text-sm font-semibold transition-all ${
                      active
                        ? "bg-primary text-primary-foreground shadow-sm"
                        : "text-muted-foreground hover:text-foreground"
                    }`}
                  >
                    {label}
                  </button>
                );
              })}
            </div>

            {/* Client */}
            <section className="space-y-3">
              <div className="flex items-center justify-between">
                <h2 className="text-[11px] font-semibold uppercase tracking-wider text-muted-foreground">
                  Cliente
                </h2>
                {hasContactPicker && (
                  <Button
                    type="button"
                    size="sm"
                    variant="ghost"
                    onClick={importContact}
                    className="h-7 gap-1 px-2 text-xs text-primary"
                  >
                    <Contact className="h-3.5 w-3.5" /> Dos contatos
                  </Button>
                )}
              </div>
              <div className="space-y-2">
                <Input
                  placeholder="Nome do cliente"
                  value={client.name}
                  onChange={(e) => setClient({ ...client, name: e.target.value })}
                />
                <Input
                  placeholder="(11) 91234-5678"
                  inputMode="tel"
                  value={client.phone}
                  onChange={(e) =>
                    setClient({ ...client, phone: formatPhoneBR(e.target.value) })
                  }
                  maxLength={16}
                />
                <Input
                  placeholder="Endereço"
                  value={client.address}
                  onChange={(e) =>
                    setClient({ ...client, address: e.target.value })
                  }
                />
              </div>
            </section>

            {/* Items */}
            <section className="space-y-3">
              <div className="flex items-center justify-between">
                <h2 className="text-[11px] font-semibold uppercase tracking-wider text-muted-foreground">
                  Serviços
                </h2>
                {items.length > 0 && (
                  <Button
                    size="sm"
                    variant="ghost"
                    onClick={() => {
                      setPickerSearch("");
                      setPickerOpen(true);
                    }}
                    className="h-7 gap-1 px-2 text-xs text-primary"
                  >
                    <Plus className="h-3.5 w-3.5" /> Adicionar
                  </Button>
                )}
              </div>

              {items.length === 0 ? (
                <button
                  type="button"
                  onClick={() => {
                    setPickerSearch("");
                    setPickerOpen(true);
                  }}
                  className="flex w-full flex-col items-center gap-2 rounded-xl border border-dashed border-border/60 px-4 py-8 text-center transition-colors hover:border-primary/60 hover:bg-primary/5"
                >
                  <span className="flex h-10 w-10 items-center justify-center rounded-full bg-primary/15 text-primary">
                    <Plus className="h-5 w-5" />
                  </span>
                  <span className="text-sm font-medium">Adicionar serviço</span>
                </button>
              ) : (
                <ul className="divide-y divide-border/60 overflow-hidden rounded-xl bg-secondary/30">
                  {items.map((it) => (
                    <li key={it.id} className="p-3">
                      <Input
                        value={it.name}
                        onChange={(e) =>
                          updateItem(it.id, { name: e.target.value })
                        }
                        className="mb-2 h-9 border-transparent bg-transparent px-1 text-sm font-medium focus-visible:border-border focus-visible:bg-background"
                      />
                      <div className="flex items-center gap-2">
                        <div className="flex items-center rounded-md border border-border/60 bg-background">
                          <button
                            type="button"
                            onClick={() =>
                              updateItem(it.id, { qty: Math.max(1, it.qty - 1) })
                            }
                            className="px-2.5 py-1.5 text-muted-foreground hover:text-foreground"
                            aria-label="Diminuir"
                          >
                            −
                          </button>
                          <span className="min-w-[28px] text-center text-sm font-semibold">
                            {it.qty}
                          </span>
                          <button
                            type="button"
                            onClick={() => updateItem(it.id, { qty: it.qty + 1 })}
                            className="px-2.5 py-1.5 text-muted-foreground hover:text-foreground"
                            aria-label="Aumentar"
                          >
                            +
                          </button>
                        </div>

                        <div className="relative flex-1">
                          <span className="pointer-events-none absolute left-2 top-1/2 -translate-y-1/2 text-xs text-muted-foreground">
                            R$
                          </span>
                          <Input
                            inputMode="decimal"
                            value={it.price}
                            onChange={(e) => {
                              const v = parseFloat(
                                e.target.value.replace(",", "."),
                              );
                              updateItem(it.id, {
                                price: Number.isFinite(v) ? v : 0,
                              });
                            }}
                            className="h-9 pl-8 text-sm"
                          />
                        </div>

                        <Button
                          size="icon"
                          variant="ghost"
                          onClick={() => removeItem(it.id)}
                          className="h-9 w-9 text-muted-foreground hover:text-destructive"
                          aria-label="Remover"
                        >
                          <Trash2 className="h-4 w-4" />
                        </Button>
                      </div>
                      <div className="mt-1.5 text-right text-xs text-muted-foreground">
                        {formatBRL(it.price * it.qty)}
                      </div>
                    </li>
                  ))}
                </ul>
              )}
            </section>

            {/* Mão de obra + Material (valores adicionais) */}
            <section className="space-y-3">
              <h2 className="text-[11px] font-semibold uppercase tracking-wider text-muted-foreground">
                Valores adicionais
              </h2>
              <div className="grid grid-cols-2 gap-2">
                {/* Mão de obra */}
                <div>
                  <div className="mb-1 flex items-center justify-between">
                    <label className="text-[11px] font-medium text-muted-foreground">
                      Mão de obra
                    </label>
                    {laborCost > 0 && (
                      <button
                        type="button"
                        onClick={() => setLaborCost(0)}
                        className="text-[10px] text-muted-foreground hover:text-destructive"
                      >
                        limpar
                      </button>
                    )}
                  </div>
                  <div className="relative">
                    <span className="pointer-events-none absolute left-2.5 top-1/2 -translate-y-1/2 text-xs text-muted-foreground">
                      R$
                    </span>
                    <Input
                      inputMode="decimal"
                      placeholder="0,00"
                      value={laborCost > 0 ? String(laborCost) : ""}
                      onChange={(e) => {
                        const v = parseFloat(e.target.value.replace(",", "."));
                        setLaborCost(Number.isFinite(v) && v > 0 ? v : 0);
                      }}
                      className="h-11 pl-8 text-sm font-semibold"
                    />
                  </div>
                </div>

                {/* Material */}
                <div>
                  <div className="mb-1 flex items-center justify-between">
                    <label className="text-[11px] font-medium text-muted-foreground">
                      Material
                    </label>
                    {materialCost > 0 && (
                      <button
                        type="button"
                        onClick={() => setMaterialCost(0)}
                        className="text-[10px] text-muted-foreground hover:text-destructive"
                      >
                        limpar
                      </button>
                    )}
                  </div>
                  <div className="relative">
                    <span className="pointer-events-none absolute left-2.5 top-1/2 -translate-y-1/2 text-xs text-muted-foreground">
                      R$
                    </span>
                    <Input
                      inputMode="decimal"
                      placeholder="0,00"
                      value={materialCost > 0 ? String(materialCost) : ""}
                      onChange={(e) => {
                        const v = parseFloat(e.target.value.replace(",", "."));
                        setMaterialCost(Number.isFinite(v) && v > 0 ? v : 0);
                      }}
                      className="h-11 pl-8 text-sm font-semibold"
                    />
                  </div>
                </div>
              </div>

              {(laborCost > 0 || materialCost > 0) && items.length > 0 && (
                <div className="space-y-1 rounded-lg bg-secondary/30 p-3 text-xs">
                  <div className="flex justify-between text-muted-foreground">
                    <span>Serviços</span>
                    <span>{formatBRL(itemsTotal)}</span>
                  </div>
                  {laborCost > 0 && (
                    <div className="flex justify-between text-muted-foreground">
                      <span>Mão de obra</span>
                      <span>{formatBRL(laborCost)}</span>
                    </div>
                  )}
                  {materialCost > 0 && (
                    <div className="flex justify-between text-muted-foreground">
                      <span>Material</span>
                      <span>{formatBRL(materialCost)}</span>
                    </div>
                  )}
                  <div className="flex justify-between border-t border-border/60 pt-1 font-semibold text-foreground">
                    <span>Total</span>
                    <span>{formatBRL(total)}</span>
                  </div>
                </div>
              )}
            </section>
          </TabsContent>
          <TabsContent value="services" className="mt-4 space-y-3">
            <div className="flex gap-2">
              <div className="relative flex-1">
                <Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
                <Input
                  placeholder="Buscar serviço…"
                  value={search}
                  onChange={(e) => setSearch(e.target.value)}
                  className="pl-9"
                />
              </div>
              <Button onClick={addNewService} size="icon" variant="electric">
                <Plus className="h-4 w-4" />
              </Button>
            </div>

            {items.length > 0 && (
              <button
                type="button"
                onClick={() => setTab("budget")}
                className="flex w-full items-center justify-between rounded-lg border border-primary/40 bg-primary/10 px-3 py-2.5 text-left transition-colors hover:bg-primary/15"
              >
                <span className="flex items-center gap-2 text-sm">
                  <Receipt className="h-4 w-4 text-primary" />
                  <span className="font-medium">
                    {items.reduce((s, it) => s + it.qty, 0)}{" "}
                    {items.reduce((s, it) => s + it.qty, 0) === 1
                      ? "item"
                      : "itens"}{" "}
                    no orçamento
                  </span>
                </span>
                <span className="text-sm font-bold text-primary">
                  {formatBRL(total)} →
                </span>
              </button>
            )}

            <ul className="space-y-2">
              {filteredServices.map((s) => {
                const isEditing = editingService === s.id;
                const qtyInBudget = qtyByServiceId[s.id] ?? 0;
                const isSelected = qtyInBudget > 0;
                const isPulsing = pulseId === s.id;
                return (
                  <li
                    key={s.id}
                    className={`rounded-xl border bg-card p-3 transition-all ${
                      isSelected
                        ? "border-primary/60 bg-primary/5"
                        : "border-border/60"
                    } ${isPulsing ? "scale-[1.015] ring-2 ring-primary/50" : ""}`}
                  >
                    {isEditing ? (
                      <div className="space-y-2">
                        <Input
                          value={s.name}
                          onChange={(e) =>
                            updateService(s.id, { name: e.target.value })
                          }
                          placeholder="Nome do serviço"
                        />
                        <div className="flex gap-2">
                          <div className="relative flex-1">
                            <span className="pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-xs text-muted-foreground">
                              R$
                            </span>
                            <Input
                              inputMode="decimal"
                              value={s.price}
                              onChange={(e) => {
                                const v = parseFloat(
                                  e.target.value.replace(",", "."),
                                );
                                updateService(s.id, {
                                  price: Number.isFinite(v) ? v : 0,
                                });
                              }}
                              className="pl-8"
                            />
                          </div>
                          <Input
                            value={s.unit ?? ""}
                            onChange={(e) =>
                              updateService(s.id, { unit: e.target.value })
                            }
                            placeholder="un"
                            className="w-20"
                          />
                        </div>
                        <div className="flex gap-2 pt-1">
                          <Button
                            size="sm"
                            variant="electric"
                            onClick={() => setEditingService(null)}
                            className="flex-1 gap-1"
                          >
                            <Check className="h-4 w-4" /> Salvar
                          </Button>
                          <Button
                            size="sm"
                            variant="ghost"
                            onClick={() => removeService(s.id)}
                            className="text-destructive"
                          >
                            <Trash2 className="h-4 w-4" />
                          </Button>
                        </div>
                      </div>
                    ) : (
                      <div className="flex items-center gap-3">
                        <button
                          type="button"
                          onClick={() => addServiceToBudget(s)}
                          className="flex flex-1 items-center justify-between text-left active:scale-[0.98] transition-transform"
                        >
                          <div className="min-w-0 flex items-center gap-2">
                            {isSelected && (
                              <span className="flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-primary text-primary-foreground text-[10px] font-bold">
                                {qtyInBudget}
                              </span>
                            )}
                            <div className="min-w-0">
                              <p className="truncate text-sm font-medium">
                                {s.name}
                              </p>
                              <p className="text-xs text-muted-foreground">
                                {formatBRL(s.price)}
                                {s.unit ? ` / ${s.unit}` : ""}
                                {isSelected && (
                                  <span className="ml-1.5 text-primary font-medium">
                                    • {qtyInBudget} no orçamento
                                  </span>
                                )}
                              </p>
                            </div>
                          </div>
                          <span
                            className={`ml-3 flex h-9 w-9 shrink-0 items-center justify-center rounded-full transition-colors ${
                              isSelected
                                ? "bg-primary text-primary-foreground"
                                : "bg-primary/15 text-primary"
                            }`}
                          >
                            <Plus className="h-4 w-4" />
                          </span>
                        </button>
                        <Button
                          size="icon"
                          variant="ghost"
                          onClick={() => setEditingService(s.id)}
                          className="h-8 w-8 text-muted-foreground"
                          aria-label="Editar"
                        >
                          <Pencil className="h-3.5 w-3.5" />
                        </Button>
                      </div>
                    )}
                  </li>
                );
              })}
              {filteredServices.length === 0 && (
                <li className="rounded-lg border border-dashed border-border/60 p-6 text-center text-sm text-muted-foreground">
                  Nenhum serviço encontrado.
                </li>
              )}
            </ul>
          </TabsContent>


          {/* ======================== COMPANY ======================== */}
          <TabsContent value="company" className="mt-6 space-y-8">
            {/* Logo */}
            <div className="flex items-center gap-4">
              <button
                type="button"
                onClick={() => logoInputRef.current?.click()}
                className="flex h-20 w-20 shrink-0 items-center justify-center overflow-hidden rounded-2xl border border-dashed border-border/60 bg-secondary/30 transition-colors hover:border-primary/60 hover:bg-primary/5"
              >
                {company.logoDataUrl ? (
                  <img
                    src={company.logoDataUrl}
                    alt="Logo"
                    className="h-full w-full object-contain"
                  />
                ) : (
                  <Plus className="h-5 w-5 text-muted-foreground" />
                )}
              </button>
              <div className="min-w-0 flex-1">
                <p className="text-sm font-semibold">
                  {company.logoDataUrl ? "Sua logo" : "Adicionar logo"}
                </p>
                <p className="text-xs text-muted-foreground">
                  Aparece no PDF e ajuda a detectar suas cores.
                </p>
                {company.logoDataUrl && (
                  <button
                    type="button"
                    onClick={() =>
                      setCompany({ ...company, logoDataUrl: undefined })
                    }
                    className="mt-1 text-[11px] text-muted-foreground underline-offset-2 hover:text-destructive hover:underline"
                  >
                    Remover
                  </button>
                )}
                <input
                  ref={logoInputRef}
                  type="file"
                  accept="image/*"
                  className="hidden"
                  onChange={(e) => handleLogo(e.target.files?.[0])}
                />
              </div>
            </div>

            {/* Cores da marca (aparece quando há logo) */}
            {company.logoDataUrl && (
              <div className="space-y-3">
                <h2 className="text-[11px] font-semibold uppercase tracking-wider text-muted-foreground">
                  Cores da marca
                </h2>
                {[
                  {
                    key: "primary" as const,
                    label: "Principal",
                    value: company.brandColor ?? "#FFC400",
                    onChange: (v: string) =>
                      setCompany({ ...company, brandColor: v }),
                  },
                  {
                    key: "accent" as const,
                    label: "Destaque",
                    value: company.brandColorAccent ?? "#111111",
                    onChange: (v: string) =>
                      setCompany({ ...company, brandColorAccent: v }),
                  },
                ].map((c) => (
                  <div key={c.key} className="flex items-center gap-3">
                    <input
                      type="color"
                      value={c.value}
                      onChange={(e) => c.onChange(e.target.value)}
                      className="h-9 w-10 cursor-pointer rounded-md border border-border bg-transparent"
                      aria-label={c.label}
                    />
                    <div className="min-w-0 flex-1">
                      <p className="text-sm">{c.label}</p>
                      <p className="font-mono text-[11px] text-muted-foreground">
                        {c.value.toUpperCase()}
                      </p>
                    </div>
                    <button
                      type="button"
                      onClick={() => setEyedropperFor(c.key)}
                      className="flex items-center gap-1 text-xs text-primary hover:underline"
                    >
                      <Pipette className="h-3.5 w-3.5" /> Da logo
                    </button>
                  </div>
                ))}
                {(company.brandColor || company.brandColorAccent) && (
                  <button
                    type="button"
                    onClick={() =>
                      setCompany({
                        ...company,
                        brandColor: undefined,
                        brandColorAccent: undefined,
                      })
                    }
                    className="text-[11px] text-muted-foreground underline-offset-2 hover:text-foreground hover:underline"
                  >
                    Voltar pras cores padrão
                  </button>
                )}
              </div>
            )}

            {/* Dados */}
            <div className="space-y-3">
              <h2 className="text-[11px] font-semibold uppercase tracking-wider text-muted-foreground">
                Dados
              </h2>
              <Input
                placeholder="Nome / razão social"
                value={company.name}
                onChange={(e) => setCompany({ ...company, name: e.target.value })}
              />
              <Input
                placeholder="CPF ou CNPJ"
                value={company.document}
                onChange={(e) =>
                  setCompany({ ...company, document: e.target.value })
                }
              />
              <Input
                placeholder="Telefone / e-mail"
                value={company.contact}
                onChange={(e) =>
                  setCompany({ ...company, contact: e.target.value })
                }
              />
            </div>

            {/* PIX */}
            <div className="space-y-3">
              <h2 className="text-[11px] font-semibold uppercase tracking-wider text-muted-foreground">
                Chave PIX
              </h2>
              <div className="flex gap-2">
                <Input
                  placeholder="CPF, e-mail, telefone ou chave aleatória"
                  value={company.pixKey ?? ""}
                  onChange={(e) =>
                    setCompany({ ...company, pixKey: e.target.value })
                  }
                  maxLength={140}
                />
                <Button
                  type="button"
                  size="icon"
                  variant="secondary"
                  disabled={!company.pixKey}
                  onClick={async () => {
                    if (!company.pixKey) return;
                    try {
                      await navigator.clipboard.writeText(company.pixKey);
                      toast.success("Chave PIX copiada!");
                    } catch {
                      toast.error("Não foi possível copiar.");
                    }
                  }}
                  aria-label="Copiar chave PIX"
                  className="shrink-0"
                >
                  <Copy className="h-4 w-4" />
                </Button>
              </div>
            </div>

            {/* Identificação extra (CRT, registro, etc.) — opcional */}
            <div className="space-y-3">
              <h2 className="text-[11px] font-semibold uppercase tracking-wider text-muted-foreground">
                Registro / Numeração <span className="font-normal normal-case text-muted-foreground/70">(opcional)</span>
              </h2>
              <Input
                placeholder='Ex: CRT-12345 ou CREA 0000000'
                value={company.numberPrefix ?? ""}
                onChange={(e) =>
                  setCompany({ ...company, numberPrefix: e.target.value })
                }
                maxLength={40}
              />
              <p className="text-[11px] leading-relaxed text-muted-foreground">
                Aparece junto ao número do orçamento (ex: <span className="font-mono">CRT-12345 · Nº 0001</span>).
              </p>
            </div>
            {/* ============ OPÇÕES DA PROPOSTA (impressas no PDF) ============ */}
            <div className="space-y-3">
              <h2 className="text-[11px] font-semibold uppercase tracking-wider text-muted-foreground">
                Opções da proposta
              </h2>

              {/* GARANTIA — toggle principal, sempre visível */}
              <label className="flex items-start gap-3 rounded-xl border border-border bg-card/40 p-3 cursor-pointer hover:bg-card/60 transition-colors">
                <div className="shrink-0 w-9 h-9 rounded-lg bg-primary/15 border border-primary/25 flex items-center justify-center mt-0.5">
                  <ShieldCheck className="w-4 h-4 text-primary" />
                </div>
                <div className="flex-1 min-w-0">
                  <div className="flex items-center justify-between gap-3">
                    <span className="text-sm font-semibold text-foreground">Garantia do serviço</span>
                    <ToggleSwitch
                      checked={!!company.warrantyEnabled}
                      onChange={() =>
                        setCompany({ ...company, warrantyEnabled: !company.warrantyEnabled })
                      }
                      label="Ativar garantia"
                    />
                  </div>
                  <p className="text-[11px] leading-relaxed text-muted-foreground mt-0.5">
                    {company.warrantyEnabled
                      ? `Será impresso no PDF: "Garantia de ${company.warrantyDays ?? 90} dias sobre os serviços executados."`
                      : "Nenhuma linha de garantia será impressa no PDF."}
                  </p>
                  {company.warrantyEnabled && (
                    <div className="flex items-center gap-2 mt-2.5">
                      <Input
                        inputMode="numeric"
                        value={company.warrantyDays ?? 90}
                        onChange={(e) => {
                          const v = parseInt(e.target.value.replace(/\D/g, ""), 10);
                          setCompany({
                            ...company,
                            warrantyDays: Number.isFinite(v) ? Math.min(v, 999) : 0,
                          });
                        }}
                        className="w-20 h-9 text-center"
                        maxLength={3}
                      />
                      <span className="text-xs text-muted-foreground">dias de garantia</span>
                    </div>
                  )}
                </div>
              </label>

              {/* MAIS OPÇÕES — collapsible */}
              <div className="rounded-xl border border-border bg-card/40 overflow-hidden">
                <button
                  type="button"
                  onClick={() => setPdfOptionsOpen((v) => !v)}
                  aria-expanded={pdfOptionsOpen}
                  className="w-full flex items-center justify-between gap-3 px-3 py-2.5 hover:bg-card/60 transition-colors"
                >
                  <span className="flex items-center gap-2 text-sm font-semibold text-foreground">
                    <Info className="w-4 h-4 text-muted-foreground" />
                    Mais opções da proposta
                  </span>
                  <ChevronDown
                    className={`w-4 h-4 text-muted-foreground transition-transform ${
                      pdfOptionsOpen ? "rotate-180" : ""
                    }`}
                  />
                </button>

                {pdfOptionsOpen && (
                  <div className="px-3 pb-3 pt-1 space-y-3 border-t border-border">
                    {/* VALIDADE */}
                    <div className="rounded-lg border border-border/60 bg-background/40 p-3">
                      <div className="flex items-start gap-3">
                        <div className="shrink-0 w-8 h-8 rounded-lg bg-primary/10 border border-primary/20 flex items-center justify-center mt-0.5">
                          <CalendarClock className="w-4 h-4 text-primary" />
                        </div>
                        <div className="flex-1 min-w-0">
                          <div className="flex items-center justify-between gap-3">
                            <span className="text-sm font-semibold text-foreground">Validade do orçamento</span>
                            <ToggleSwitch
                              checked={company.validityEnabled !== false}
                              onChange={() =>
                                setCompany({
                                  ...company,
                                  validityEnabled: !(company.validityEnabled !== false),
                                })
                              }
                              label="Ativar validade"
                            />
                          </div>
                          <p className="text-[11px] leading-relaxed text-muted-foreground mt-0.5">
                            {company.validityEnabled !== false
                              ? `Impresso: "Orçamento válido por ${company.validityDays ?? 7} dias a partir da data de emissão."`
                              : "Nenhuma linha de validade será impressa."}
                          </p>
                          {company.validityEnabled !== false && (
                            <div className="flex items-center gap-2 mt-2.5">
                              <Input
                                inputMode="numeric"
                                value={company.validityDays ?? 7}
                                onChange={(e) => {
                                  const v = parseInt(e.target.value.replace(/\D/g, ""), 10);
                                  setCompany({
                                    ...company,
                                    validityDays: Number.isFinite(v) ? Math.min(v, 999) : 0,
                                  });
                                }}
                                className="w-20 h-9 text-center"
                                maxLength={3}
                              />
                              <span className="text-xs text-muted-foreground">dias de validade</span>
                            </div>
                          )}
                        </div>
                      </div>
                    </div>

                    {/* INMETRO */}
                    <div className="rounded-lg border border-border/60 bg-background/40 p-3">
                      <div className="flex items-start gap-3">
                        <div className="shrink-0 w-8 h-8 rounded-lg bg-primary/10 border border-primary/20 flex items-center justify-center mt-0.5">
                          <BadgeCheck className="w-4 h-4 text-primary" />
                        </div>
                        <div className="flex-1 min-w-0">
                          <div className="flex items-center justify-between gap-3">
                            <span className="text-sm font-semibold text-foreground">Selo INMETRO</span>
                            <ToggleSwitch
                              checked={company.inmetroEnabled !== false}
                              onChange={() =>
                                setCompany({
                                  ...company,
                                  inmetroEnabled: !(company.inmetroEnabled !== false),
                                })
                              }
                              label="Ativar selo INMETRO"
                            />
                          </div>
                          <p className="text-[11px] leading-relaxed text-muted-foreground mt-0.5">
                            {company.inmetroEnabled !== false
                              ? 'Impresso: "Material elétrico de qualidade certificada pelo INMETRO."'
                              : "Nenhuma linha sobre material certificado será impressa."}
                          </p>
                        </div>
                      </div>
                    </div>

                    {/* OBSERVAÇÃO LIVRE */}
                    <div className="rounded-lg border border-border/60 bg-background/40 p-3">
                      <div className="flex items-start gap-3">
                        <div className="shrink-0 w-8 h-8 rounded-lg bg-primary/10 border border-primary/20 flex items-center justify-center mt-0.5">
                          <StickyNote className="w-4 h-4 text-primary" />
                        </div>
                        <div className="flex-1 min-w-0">
                          <span className="text-sm font-semibold text-foreground">Observação adicional</span>
                          <p className="text-[11px] leading-relaxed text-muted-foreground mt-0.5 mb-2">
                            Texto livre que aparece nas condições do PDF (ex: "Visita técnica gratuita na região").
                          </p>
                          <Textarea
                            placeholder="Ex: Pagamento em até 3x sem juros no PIX"
                            value={company.customNote ?? ""}
                            onChange={(e) =>
                              setCompany({ ...company, customNote: e.target.value.slice(0, 140) })
                            }
                            rows={2}
                            className="text-sm resize-none"
                          />
                          <p className="text-[10px] text-muted-foreground mt-1 text-right">
                            {(company.customNote ?? "").length}/140
                          </p>
                        </div>
                      </div>
                    </div>
                  </div>
                )}
              </div>
            </div>

            {/* Botão salvar (dados já salvam automaticamente — só feedback) */}
            <Button
              type="button"
              variant={companySaved ? "default" : "electric"}
              className={`h-12 w-full gap-2 text-sm ${
                companySaved ? "bg-success text-white hover:bg-success/90" : ""
              }`}
              onClick={() => {
                setCompanySaved(true);
                toast.success("Informações salvas");
                window.setTimeout(() => setCompanySaved(false), 2200);
              }}
            >
              {companySaved ? (
                <>
                  <Check className="h-4 w-4" /> Salvo!
                </>
              ) : (
                <>
                  <Save className="h-4 w-4" /> Salvar
                </>
              )}
            </Button>
          </TabsContent>
        </Tabs>
        <div className="h-28" /> {/* Espaço extra para não cobrir o conteúdo pelo rodapé fixo */}
      </main>

      {/* Sticky bottom bar */}
      {tab === "budget" && (
        <div
          className="fixed bottom-0 left-0 right-0 z-40 border-t border-border/60 bg-background/95 shadow-[0_-8px_24px_-12px_rgba(0,0,0,0.5)] backdrop-blur"
          style={{ paddingBottom: "max(env(safe-area-inset-bottom), 1.25rem)" }}
        >
          <div className="mx-auto max-w-3xl px-3 py-2 sm:px-4 sm:py-3">
            <div className="mb-1.5 flex items-baseline justify-between sm:mb-2">
              <span className="text-[10px] uppercase tracking-wider text-muted-foreground sm:text-xs">
                Total
              </span>
              <span className="font-display text-xl sm:text-2xl">{formatBRL(total)}</span>
            </div>
            <div className="grid grid-cols-2 gap-2">
              <Button
                onClick={handleWhatsapp}
                className="h-10 gap-1.5 bg-success text-white hover:bg-success/90 sm:h-11"
              >
                <MessageCircle className="h-4 w-4" /> WhatsApp
              </Button>
              <Button
                onClick={() => setPdfMenuOpen(true)}
                variant="electric"
                className="h-10 gap-1.5 sm:h-11"
              >
                <FileDown className="h-4 w-4" /> PDF
              </Button>
            </div>
          </div>
        </div>
      )}

      {/* PDF format chooser */}
      <Dialog open={pdfMenuOpen} onOpenChange={setPdfMenuOpen}>
        <DialogContent
          className="max-w-sm"
          onOpenAutoFocus={(e) => e.preventDefault()}
        >
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <FileDown className="h-5 w-5 text-primary" />
              Exportar PDF
            </DialogTitle>
            <DialogDescription>
              Escolha o formato ideal pro seu cliente.
            </DialogDescription>
          </DialogHeader>
          <div className="grid gap-2">
            <div className="grid grid-cols-2 gap-3 pt-2">
              <button
                type="button"
                onClick={() => handlePDF("a4")}
                className="group relative flex flex-col items-center gap-3 rounded-2xl border-2 border-border/50 bg-card p-4 transition-all hover:border-primary/60 hover:bg-primary/5 active:scale-[0.98]"
              >
                <div className="relative aspect-[1/1.414] w-full overflow-hidden rounded-lg border border-border/60 bg-white shadow-md transition-transform group-hover:-translate-y-1">
                  {/* Miniatura simulada A4 - Estruturada */}
                  <div className="flex h-full w-full flex-col p-2.5">
                    <div className="flex items-center justify-between border-b border-slate-100 pb-1.5">
                      <div className="h-2 w-8 rounded-full bg-primary/30" />
                      <div className="h-1.5 w-6 rounded-full bg-slate-200" />
                    </div>
                    <div className="mt-2 space-y-1">
                      <div className="h-1 w-full rounded-full bg-slate-100" />
                      <div className="h-1 w-full rounded-full bg-slate-100" />
                      <div className="h-1 w-3/4 rounded-full bg-slate-100" />
                    </div>
                    <div className="mt-auto border-t border-slate-50 pt-1.5">
                      <div className="h-2 w-full rounded-sm bg-primary/10" />
                    </div>
                  </div>
                  <div className="absolute inset-0 flex items-center justify-center bg-primary/5 opacity-0 transition-all group-hover:opacity-100">
                    <FileDown className="h-7 w-7 text-primary" />
                  </div>
                </div>
                <div className="text-center">
                  <p className="text-xs font-bold uppercase tracking-tight">PDF A4</p>
                  <p className="mt-0.5 text-[10px] leading-tight text-muted-foreground">Padrão p/ imprimir</p>
                </div>
              </button>

              <button
                type="button"
                onClick={() => handlePDF("mobile")}
                className="group relative flex flex-col items-center gap-3 rounded-2xl border-2 border-border/50 bg-card p-4 transition-all hover:border-primary/60 hover:bg-primary/5 active:scale-[0.98]"
              >
                <div className="relative aspect-[1/2] w-14 overflow-hidden rounded-lg border border-border/60 bg-white shadow-md transition-transform group-hover:-translate-y-1">
                  {/* Miniatura simulada Mobile - Estruturada */}
                  <div className="flex h-full w-full flex-col p-1.5">
                    <div className="mb-2 flex flex-col items-center gap-1 border-b border-slate-50 pb-1">
                      <div className="h-1.5 w-4 rounded-full bg-primary/40" />
                      <div className="h-1 w-6 rounded-full bg-slate-100" />
                    </div>
                    <div className="space-y-1">
                      <div className="h-1 w-full rounded-sm bg-slate-50" />
                      <div className="h-1 w-full rounded-sm bg-slate-50" />
                      <div className="h-1 w-full rounded-sm bg-slate-50" />
                    </div>
                    <div className="mt-auto space-y-1">
                      <div className="h-2 w-full rounded-sm bg-primary/20" />
                      <div className="h-3 w-full rounded-sm bg-slate-900" />
                    </div>
                  </div>
                  <div className="absolute inset-0 flex items-center justify-center bg-primary/5 opacity-0 transition-all group-hover:opacity-100">
                    <Smartphone className="h-7 w-7 text-primary" />
                  </div>
                </div>
                <div className="text-center">
                  <p className="text-xs font-bold uppercase tracking-tight">Mobile</p>
                  <p className="mt-0.5 text-[10px] leading-tight text-muted-foreground">Cupom (Zap)</p>
                </div>
              </button>
            </div>
          </div>
        </DialogContent>
      </Dialog>

      {/* Service picker modal */}
      <Dialog open={pickerOpen} onOpenChange={setPickerOpen}>
        <DialogContent
          className="max-w-md p-0"
          onOpenAutoFocus={(e) => e.preventDefault()}
        >
          <DialogHeader className="px-5 pt-5">
            <DialogTitle className="flex items-center gap-2">
              <ListChecks className="h-5 w-5 text-primary" />
              Adicionar serviço
            </DialogTitle>
            <DialogDescription>
              Crie um item personalizado ou escolha do seu catálogo abaixo.
            </DialogDescription>
          </DialogHeader>

          {/* Item personalizado — campo aberto pra digitar direto */}
          <div className="space-y-2 px-5">
            <p className="text-[11px] font-semibold uppercase tracking-wider text-muted-foreground">
              Personalizado
            </p>
            <div className="space-y-2 rounded-xl border border-dashed border-primary/40 bg-primary/5 p-3">
              <Input
                placeholder="Descrição do serviço"
                value={customDraftName}
                onChange={(e) => setCustomDraftName(e.target.value)}
                className="h-10 bg-background text-sm"
                autoFocus={false}
              />

              {/* Autocompletar do catálogo */}
              {(() => {
                const norm = (s: string) =>
                  s
                    .toLowerCase()
                    .normalize("NFD")
                    .replace(/[\u0300-\u036f]/g, "");
                const q = norm(customDraftName.trim());
                if (q.length < 2) return null;
                const matches = services
                  .filter((s) => norm(s.name).includes(q))
                  .slice(0, 4);
                if (matches.length === 0) return null;
                return (
                  <div className="space-y-1 rounded-lg border border-border/60 bg-background/60 p-1.5">
                    <p className="px-1.5 pt-0.5 text-[10px] font-semibold uppercase tracking-wider text-muted-foreground">
                      Já existe no catálogo
                    </p>
                    <ul className="space-y-1">
                      {matches.map((s) => (
                        <li key={s.id}>
                          <button
                            type="button"
                            onClick={() => {
                              addServiceToBudget(s);
                              setCustomDraftName("");
                              setCustomDraftPrice("");
                              setPickerOpen(false);
                              window.scrollTo({ top: 0, behavior: "smooth" });
                            }}
                            className="flex w-full items-center justify-between gap-2 rounded-md px-2 py-1.5 text-left text-sm hover:bg-secondary active:scale-[0.99]"
                          >
                            <span className="truncate">{s.name}</span>
                            <span className="shrink-0 text-xs font-semibold text-primary">
                              {formatBRL(s.price)}
                            </span>
                          </button>
                        </li>
                      ))}
                    </ul>
                  </div>
                );
              })()}

              <div className="flex gap-2">
                <div className="relative flex-1">
                  <span className="pointer-events-none absolute left-2.5 top-1/2 -translate-y-1/2 text-xs text-muted-foreground">
                    R$
                  </span>
                  <Input
                    inputMode="decimal"
                    placeholder="0,00"
                    value={customDraftPrice}
                    onChange={(e) => setCustomDraftPrice(e.target.value)}
                    className="h-10 bg-background pl-8 text-sm"
                  />
                </div>
                <Button
                  type="button"
                  variant="electric"
                  className="h-10 shrink-0 gap-1.5 px-4"
                  onClick={() => {
                    // Normaliza espaços duplicados (comum vindo de teclado mobile / ditado de voz)
                    const name =
                      customDraftName.replace(/\s+/g, " ").trim() ||
                      "Novo serviço";
                    const priceVal = parseFloat(
                      customDraftPrice.replace(",", "."),
                    );
                    setItems((prev) => [
                      ...prev,
                      {
                        id: uid(),
                        name,
                        price: Number.isFinite(priceVal) ? priceVal : 0,
                        qty: 1,
                      },
                    ]);
                    setCustomDraftName("");
                    setCustomDraftPrice("");
                    setPickerOpen(false);
                    window.scrollTo({ top: 0, behavior: "smooth" });
                    toast.success(`${name} adicionado`);
                  }}
                >
                  <Plus className="h-4 w-4" /> Adicionar
                </Button>
              </div>
            </div>
          </div>

          {/* Catálogo */}
          <div className="space-y-2 px-5 pt-4">
            <p className="text-[11px] font-semibold uppercase tracking-wider text-muted-foreground">
              Do seu catálogo
            </p>
            <div className="relative">
              <Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
              <Input
                placeholder="Buscar serviço…"
                value={pickerSearch}
                onChange={(e) => setPickerSearch(e.target.value)}
                className="pl-9"
              />
            </div>
          </div>

          <ul className="max-h-[40vh] space-y-2 overflow-y-auto px-5 pb-2 pt-2">
            {services
              .filter((s) =>
                s.name.toLowerCase().includes(pickerSearch.trim().toLowerCase()),
              )
              .map((s) => {
                const qtyInBudget = qtyByServiceId[s.id] ?? 0;
                const isSelected = qtyInBudget > 0;
                const isPulsing = pulseId === s.id;
                return (
                  <li key={s.id}>
                    <button
                      type="button"
                      onClick={() => addServiceToBudget(s)}
                      className={`flex w-full items-center justify-between gap-3 rounded-xl border p-3 text-left transition-all active:scale-[0.98] ${
                        isSelected
                          ? "border-primary/60 bg-primary/5"
                          : "border-border/60 bg-card hover:border-border"
                      } ${isPulsing ? "ring-2 ring-primary/50" : ""}`}
                    >
                      <div className="flex min-w-0 items-center gap-2">
                        {isSelected && (
                          <span className="flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-primary text-[10px] font-bold text-primary-foreground">
                            {qtyInBudget}
                          </span>
                        )}
                        <div className="min-w-0">
                          <p className="truncate text-sm font-medium">{s.name}</p>
                          <p className="text-xs text-muted-foreground">
                            {formatBRL(s.price)}
                            {s.unit ? ` / ${s.unit}` : ""}
                          </p>
                        </div>
                      </div>
                      <span
                        className={`flex h-9 w-9 shrink-0 items-center justify-center rounded-full transition-colors ${
                          isSelected
                            ? "bg-primary text-primary-foreground"
                            : "bg-primary/15 text-primary"
                        }`}
                      >
                        <Plus className="h-4 w-4" />
                      </span>
                    </button>
                  </li>
                );
              })}
            {services.filter((s) =>
              s.name.toLowerCase().includes(pickerSearch.trim().toLowerCase()),
            ).length === 0 && (
              <li className="space-y-3 rounded-xl border border-dashed border-primary/50 bg-primary/5 p-5 text-center">
                <p className="text-sm text-muted-foreground">
                  Nenhum serviço com{" "}
                  <span className="font-semibold text-foreground">
                    "{pickerSearch}"
                  </span>
                </p>
                <Button
                  size="sm"
                  variant="electric"
                  onClick={() => {
                    const name = pickerSearch.trim();
                    const newService: Service = {
                      id: uid(),
                      name,
                      price: 0,
                      unit: "un",
                    };
                    setServices((prev) => [newService, ...prev]);
                    addServiceToBudget(newService);
                    setPickerSearch("");
                    setEditingService(newService.id);
                    setPickerOpen(false);
                    setTab("services");
                    toast.success(`"${name}" criado. Defina o preço.`);
                  }}
                  className="gap-1.5"
                >
                  <Plus className="h-4 w-4" /> Criar "{pickerSearch}"
                </Button>
              </li>
            )}
          </ul>

          <div className="flex items-center justify-between gap-2 border-t border-border/60 bg-secondary/40 px-5 py-3">
            <div className="text-xs text-muted-foreground">
              {items.reduce((s, it) => s + it.qty, 0)}{" "}
              {items.reduce((s, it) => s + it.qty, 0) === 1 ? "item" : "itens"} •{" "}
              <span className="font-semibold text-foreground">
                {formatBRL(total)}
              </span>
            </div>
            <Button
              size="sm"
              variant="electric"
              onClick={() => setPickerOpen(false)}
              className="gap-1.5"
            >
              <Check className="h-4 w-4" /> Concluir
            </Button>
          </div>
        </DialogContent>
      </Dialog>

      {/* WhatsApp message modal */}
      <Dialog open={whatsappOpen} onOpenChange={setWhatsappOpen}>
        <DialogContent
          className="max-w-md"
          onOpenAutoFocus={(e) => e.preventDefault()}
        >
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <MessageCircle className="h-5 w-5 text-success" />
              {kind === "pedido" ? "Mensagem da cobrança" : "Mensagem do orçamento"}
            </DialogTitle>
            <DialogDescription>
              {copied
                ? "Mensagem copiada! Agora abra o WhatsApp e cole na conversa do cliente (toque e segure no campo de texto)."
                : "Primeiro copie a mensagem. Depois você abre o WhatsApp e cola na conversa."}
            </DialogDescription>
          </DialogHeader>

          <Textarea
            value={whatsappMsg}
            onChange={(e) => setWhatsappMsg(e.target.value)}
            className="min-h-[260px] resize-none font-mono text-xs leading-relaxed"
          />

          {kind === "pedido" && company.pixKey && company.pixKey.trim() && (
            <button
              type="button"
              onClick={async () => {
                try {
                  await navigator.clipboard.writeText(company.pixKey!);
                  toast.success("Chave PIX copiada!");
                } catch {
                  toast.error("Não foi possível copiar.");
                }
              }}
              className="flex items-center justify-between gap-2 rounded-lg border border-border/60 bg-secondary/50 px-3 py-2.5 text-left transition-colors hover:bg-secondary"
            >
              <div className="min-w-0">
                <p className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground">
                  Chave PIX
                </p>
                <p className="truncate text-sm font-medium">{company.pixKey}</p>
              </div>
              <Copy className="h-4 w-4 shrink-0 text-muted-foreground" />
            </button>
          )}

          {/* Botão único que muda de estado: Copiar → Abrir WhatsApp e colar */}
          {copied ? (
            <Button
              onClick={() => {
                const phone = client.phone.replace(/\D/g, "");
                const url = phone ? `https://wa.me/55${phone}` : `https://wa.me/`;
                window.open(url, "_blank");
              }}
              className="h-12 w-full gap-2 bg-success text-white hover:bg-success/90"
            >
              <MessageCircle className="h-5 w-5" /> Abrir WhatsApp e colar
            </Button>
          ) : (
            <Button
              onClick={copyWhatsappMsg}
              variant="electric"
              className="h-12 w-full gap-2"
            >
              <Copy className="h-5 w-5" /> Copiar mensagem
            </Button>
          )}
        </DialogContent>
      </Dialog>

      {/* Histórico (drawer) */}
      <Dialog open={historyOpen} onOpenChange={setHistoryOpen}>
        <DialogContent
          className="max-w-md p-0"
          onOpenAutoFocus={(e) => e.preventDefault()}
        >
          <DialogHeader className="px-5 pt-5">
            <DialogTitle className="flex items-center gap-2">
              <Clock className="h-5 w-5 text-primary" />
              Histórico
            </DialogTitle>
            <DialogDescription>
              {history.length === 0
                ? `Seus orçamentos aparecem aqui depois de exportar. Salvamos só os ${HISTORY_LIMIT} mais recentes neste aparelho.`
                : `${history.length} de ${HISTORY_LIMIT} ${history.length === 1 ? "salvo" : "salvos"} neste aparelho. Os mais antigos saem automaticamente.`}
            </DialogDescription>
          </DialogHeader>

          {history.length === 0 ? (
            <div className="px-5 py-10 text-center">
              <Clock className="mx-auto mb-2 h-6 w-6 text-muted-foreground" />
              <p className="text-sm text-muted-foreground">Nada por aqui ainda.</p>
            </div>
          ) : (
            <ul className="max-h-[60vh] space-y-1 overflow-y-auto px-3 pb-2">
              {history.map((b) => {
                const sub =
                  b.items.reduce((s, it) => s + it.price * it.qty, 0) +
                  (b.laborCost || 0) +
                  (b.materialCost || 0);
                const date = new Date(b.createdAt);
                return (
                  <li
                    key={b.id}
                    className="rounded-lg p-2.5 transition-colors hover:bg-secondary/50"
                  >
                    <div className="flex items-start justify-between gap-2">
                      <div className="min-w-0 flex-1">
                        <p className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground">
                          #{b.number} •{" "}
                          {b.kind === "pedido" ? "Cobrança" : "Orçamento"}
                        </p>
                        <p className="truncate text-sm font-semibold">
                          {b.client.name || "Sem cliente"}
                        </p>
                        <p className="text-[11px] text-muted-foreground">
                          {date.toLocaleDateString("pt-BR")}
                        </p>
                      </div>
                      <p className="shrink-0 font-display text-base text-primary">
                        {formatBRL(sub)}
                      </p>
                    </div>
                    <div className="mt-1.5 flex gap-1">
                      <Button
                        size="sm"
                        variant="ghost"
                        onClick={() => {
                          setItems(b.items);
                          setClient(b.client);
                          setKind(b.kind);
                          setLaborCost(b.laborCost ?? 0);
                          setMaterialCost(b.materialCost ?? 0);
                          setTab("budget");
                          setHistoryOpen(false);
                          toast.success("Orçamento restaurado");
                        }}
                        className="h-7 gap-1 px-2 text-xs text-primary"
                      >
                        <RotateCcw className="h-3 w-3" /> Reabrir
                      </Button>
                      <Button
                        size="sm"
                        variant="ghost"
                        onClick={async () => {
                          const { exportBudgetPDF } = await import("@/features/orcamento/exporters");
                          setHistoryOpen(false);
                          setPdfPreviewOpen(true);
                          setPdfPreview(null);
                          try {
                            const result = await exportBudgetPDF(b, company, "a4");
                            const docLabel = b.kind === "pedido" ? "Cobrança" : "Orçamento";
                            setPdfPreview(result);
                            setPdfPreviewMsg(buildWhatsappMessage(b, company));
                            setPdfPreviewPhone(b.client.phone ?? "");
                            setPdfPreviewTitle(`${docLabel} Nº ${String(b.number).padStart(4, "0")}`);
                          } catch (err) {
                            setPdfPreviewOpen(false);
                            toast.error("Erro ao gerar PDF");
                          }
                        }}
                        className="h-7 gap-1 px-2 text-xs"
                      >
                        <FileDown className="h-3 w-3" /> PDF
                      </Button>
                      <Button
                        size="sm"
                        variant="ghost"
                        onClick={() => {
                          const msg = buildWhatsappMessage(b, company);
                          setWhatsappMsg(msg);
                          setCopied(false);
                          setHistoryOpen(false);
                          setWhatsappOpen(true);
                        }}
                        className="h-7 gap-1 px-2 text-xs text-success"
                      >
                        <MessageCircle className="h-3 w-3" />
                      </Button>
                      <Button
                        size="icon"
                        variant="ghost"
                        onClick={() => {
                          if (confirm("Remover do histórico?")) {
                            setHistory((prev) =>
                              prev.filter((h) => h.id !== b.id),
                            );
                          }
                        }}
                        className="ml-auto h-7 w-7 text-muted-foreground hover:text-destructive"
                        aria-label="Remover"
                      >
                        <Trash2 className="h-3 w-3" />
                      </Button>
                    </div>
                  </li>
                );
              })}
            </ul>
          )}

          {history.length > 0 && (
            <div className="flex justify-end border-t border-border/60 px-5 py-2">
              <button
                type="button"
                onClick={() => {
                  if (confirm("Apagar todo o histórico?")) {
                    setHistory([]);
                    toast.success("Histórico apagado");
                  }
                }}
                className="text-[11px] text-muted-foreground hover:text-destructive"
              >
                Limpar tudo
              </button>
            </div>
          )}
        </DialogContent>
      </Dialog>

      {company.logoDataUrl && eyedropperFor && (
        <LogoEyedropper
          logoDataUrl={company.logoDataUrl}
          label={eyedropperFor === "primary" ? "Principal" : "Destaque"}
          open={!!eyedropperFor}
          onOpenChange={(open) => !open && setEyedropperFor(null)}
          onPick={(hex) => {
            if (eyedropperFor === "primary") {
              setCompany({ ...company, brandColor: hex });
            } else {
              setCompany({ ...company, brandColorAccent: hex });
            }
            toast.success(`Cor ${hex} aplicada`);
          }}
        />
      )}

      <AlertDialog open={newBudgetConfirmOpen} onOpenChange={setNewBudgetConfirmOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Iniciar novo orçamento?</AlertDialogTitle>
            <AlertDialogDescription>
              O orçamento atual (cliente, itens e valores) será limpo. Essa ação não pode ser desfeita.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>Cancelar</AlertDialogCancel>
            <AlertDialogAction onClick={confirmNewBudget}>
              Limpar e começar
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      <PdfPreviewModal
        open={pdfPreviewOpen}
        onOpenChange={setPdfPreviewOpen}
        pdf={pdfPreview}
        whatsappMessage={pdfPreviewMsg}
        whatsappPhone={pdfPreviewPhone}
        title={pdfPreviewTitle}
      />
      <footer className="mt-auto border-t border-border/40 bg-card/30 py-6 px-4">
        <div className="mx-auto max-w-3xl text-center">
          <p className="text-xs text-muted-foreground">
            © {new Date().getFullYear()} {company.name || "Eletri-Pro"} — Orçamentos Profissionais
          </p>
        </div>
      </footer>
    </div>
  );
};

export default App;
