import { useEffect, useMemo, useRef, useState, useCallback } from "react";
import {
  ArrowLeft,
  Zap,
  Building2,
  Check,
  Clock,
  Contact,
  Copy,
  FileDown,
  Info,
  ListChecks,
  MessageCircle,
  Pencil,
  Pipette,
  Plus,
  PlusCircle,
  Receipt,
  RotateCcw,
  Save,
  Search,
  Smartphone,
  Share2,
  Trash2,
  X,
  ChevronDown,
  ShieldCheck,
  CalendarClock,
  BadgeCheck,
  StickyNote,
  Package,
  Lock,
  Files,
  FileText,
  Calendar,
  PlusSquare,
  MinusSquare,
  Settings,
  Play,
} from "lucide-react";
import { Link, useNavigate, useLocation } 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,
  DialogTrigger,
} 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 { DEFAULT_MATERIALS } from "@/features/orcamento/materialDefaults";
import {
  Budget,
  BudgetItem,
  ClientInfo,
  CompanyInfo,
  Service,
  Material,
  ExecutionInfo,
  ContractClause,
} from "@/features/orcamento/types";

// Exporting formatting functions for use in other components
export { formatPhoneBR, formatDocumentBR };
import {
  buildWhatsappMessage,
  type PdfFormat,
  type PdfResult,
} from "@/features/orcamento/exporters";
import PdfCanvasPreview from "@/features/orcamento/PdfCanvasPreview";
import { extractBrandColors } from "@/features/orcamento/extractBrandColors";
import { Onboarding } from "@/features/orcamento/Onboarding";
import { LogoEyedropper } from "@/features/orcamento/LogoEyedropper";
import { SignaturePad } from "@/components/SignaturePad";
import { DEFAULT_CLAUSES } from "@/features/orcamento/clauseDefaults";

import UpsellModal from "@/components/UpsellModal";
import { MoneyInput } from "@/components/MoneyInput";


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

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

const emptyExecution: ExecutionInfo = {
  validityDays: 10,
  estimatedDeadline: "",
  estimatedDuration: "",
};

// 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)}`;
};

const formatDocumentBR = (raw: string) => {
  const d = raw.replace(/\D/g, "").slice(0, 14);
  if (d.length <= 11) {
    // CPF: 000.000.000-00
    return d
      .replace(/(\d{3})(\d)/, "$1.$2")
      .replace(/(\d{3})(\d)/, "$1.$2")
      .replace(/(\d{3})(\d{1,2})$/, "$1-$2");
  }
  // CNPJ: 00.000.000/0000-00
  return d
    .replace(/(\d{2})(\d)/, "$1.$2")
    .replace(/(\d{3})(\d)/, "$1.$2")
    .replace(/(\d{3})(\d)/, "$1/$2")
    .replace(/(\d{4})(\d{1,2})$/, "$1-$2");
};

// 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 navigate = useNavigate();
  const location = useLocation();
  const [services, setServices] = useLocalStorage<Service[]>(
    "elg.services.v1",
    DEFAULT_SERVICES,
  );
  const [catalogMaterials, setCatalogMaterials] = useLocalStorage<Material[]>(
    "elg.catalogMaterials.v1",
    DEFAULT_MATERIALS,
  );
  const [company, setCompany] = useLocalStorage<CompanyInfo>("elg.company.v1", {
    name: "",
    document: "",
    contact: "",
    pixKey: "",
    warrantyEnabled: true,
    warrantyDays: 90,
    validityEnabled: true,
    validityDays: 7,
    inmetroEnabled: true,
    customNote: "",
    documentPosition: "footer",
    hourlyRate: 0,
    dailyRate: 0,
    signatureDataUrl: "", // Garantindo que inicie vazio
  });
  const [budgetNumber, setBudgetNumber] = useState<number | null>(null);
  const [client, setClient] = useLocalStorage<ClientInfo>(
    "elg.currentClient.v1",
    emptyClient,
  );
  const [items, setItems] = useLocalStorage<BudgetItem[]>(
    "elg.currentItems.v1",
    [],
  );
  const [kind, setKind] = useLocalStorage<"orcamento" | "pedido" | "contrato">(
    "elg.currentKind.v1",
    "orcamento",
  );
  const [upsellOpen, setUpsellOpen] = useState(false);
  const [upsellSubject, setUpsellSubject] = useState<"contrato" | "arquivos">("contrato");


  const [observations, setObservations] = useLocalStorage<string>("elg.observations.v1", "");
  const [materials, setMaterials] = useLocalStorage<string>("elg.materials.v1", "");
  const [materialProvidedByClient, setMaterialProvidedByClient] = useLocalStorage<boolean>("elg.materialProvidedByClient.v1", false);
  const [execution, setExecution] = useLocalStorage<ExecutionInfo>("elg.execution.v1", emptyExecution);
  const [paymentConditions, setPaymentConditions] = useLocalStorage<string>("elg.paymentConditions.v1", "");
  const [clauses, setClauses] = useLocalStorage<ContractClause[]>("elg.clauses.v1", DEFAULT_CLAUSES);
  const [startDate, setStartDate] = useLocalStorage<string>("elg.startDate.v1", "");
  const [endDate, setEndDate] = useLocalStorage<string>("elg.endDate.v1", "");
  const [cityOverride, setCityOverride] = useLocalStorage<string>("elg.cityOverride.v1", "");

  // 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 [editingCounter, setEditingCounter] = useState(false);
  const [editingBudgetNumber, setEditingBudgetNumber] = useState(false);
  const [search, setSearch] = useState("");
  const [materialSearch, setMaterialSearch] = useState("");
  const [selectedMaterialForQty, setSelectedMaterialForQty] = useState<Material | null>(null);
  const [tempMaterialQty, setTempMaterialQty] = useState<string>("");
  const [laborCostRaw, setLaborCostRaw] = useState<string>("");
  const [materialCostRaw, setMaterialCostRaw] = useState<string>("");
  const [discountType, setDiscountType] = useLocalStorage<'fixed' | 'percentage'>("elg.discountType.v1", "fixed");
  const [discountValue, setDiscountValue] = useLocalStorage<number>("elg.discountValue.v1", 0);
  const [discountRaw, setDiscountRaw] = useState<string>("");
  const [editingService, setEditingService] = useState<string | null>(null);
  const [editingCatalogMaterial, setEditingCatalogMaterial] = useState<string | null>(null);
  const [materialPricePromptOpen, setMaterialPricePromptOpen] = useState(false);
  const [materialForPricePrompt, setMaterialForPricePrompt] = useState<Material | null>(null);
  const [promptedMaterialPrice, setPromptedMaterialPrice] = useState("");
  const [materialPickerOpen, setMaterialPickerOpen] = useState(false);
  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 [cropperOpen, setCropperOpen] = 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 [pdfPreviewDocKind, setPdfPreviewDocKind] = useState<"orcamento" | "pedido" | "contrato">("orcamento");

  // Gesture handling state
  const touchStartRef = useRef<number | null>(null);
  const touchEndRef = useRef<number | null>(null);
  const minSwipeDistance = 50;

  const onTouchStart = (e: React.TouchEvent) => {
    touchEndRef.current = null;
    touchStartRef.current = e.targetTouches[0].clientX;
  };

  const onTouchMove = (e: React.TouchEvent) => {
    touchEndRef.current = e.targetTouches[0].clientX;
  };

  const onTouchEnd = useCallback(() => {
    if (!touchStartRef.current || !touchEndRef.current) return;
    
    const distanceX = touchStartRef.current - touchEndRef.current;
    const isRightSwipe = distanceX < -150; // Aumentado para 150px para evitar toques acidentais

    if (isRightSwipe) {
      // Apenas o swipe longo da esquerda para a direita volta para o Início
      if (tab !== "budget") {
        setTab("budget");
      }
    }
  }, [tab]);

  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 totalBeforeDiscount = itemsTotal + (laborCost || 0) + (materialCost || 0);
  
  const discountAmount = useMemo(() => {
    if (discountType === 'percentage') {
      return (totalBeforeDiscount * (discountValue || 0)) / 100;
    }
    return discountValue || 0;
  }, [totalBeforeDiscount, discountType, discountValue]);

  const total = totalBeforeDiscount - discountAmount;

  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);
  };

  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 handleDocumentKindChange = (newKind: "orcamento" | "pedido" | "contrato") => {
    if (newKind === "contrato") {
      setUpsellSubject("contrato");
      setUpsellOpen(true);
      return;
    }
    setKind(newKind);
    if ((newKind as any) === "contrato") {
      setTab("contract");
    } else {
      setTab("budget");
    }
  };



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

  const buildBudget = (): Budget => ({
    id: uid(),
    number: budgetNumber ?? counter,
    createdAt: new Date().toISOString(),
    client,
    items,
    kind,
    laborCost: laborCost > 0 ? laborCost : undefined,
    materialCost: materialCost > 0 ? materialCost : undefined,
    discountValue: discountValue > 0 ? discountValue : undefined,
    discountType: discountValue > 0 ? discountType : undefined,
    observations,
    materials,
    materialProvidedByClient,
    execution,
    paymentConditions,
    numberPrefix: company.numberPrefix,
    startDate,
    endDate,
    clauses,
    city: cityOverride || company.city,
    state: company.state,
  });

  const ensureReady = () => {
    if (items.length === 0 && laborCost <= 0 && materialCost <= 0) {
      
      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;

    if ((format as any) === "contrato") {
      setUpsellSubject("contrato");
      setUpsellOpen(true);
      return;
    }


    // Lógica para decidir qual modal abrir

    const isContract = kind === "contrato" || format === "contrato";

    if (isContract) {
      // Se for contrato, garante que o menu de formato (A4/Mobile) feche e abre o preview full
      setPdfMenuOpen(false);
      setPdfPreviewDocKind("contrato");
      setPdfPreview(null);
      setPdfPreviewOpen(true);
    } else {
      // Se NÃO for contrato e o menu de formatos estiver fechado, abre ele primeiro
      if (!pdfMenuOpen) {
        setPdfMenuOpen(true);
        return;
      }
      // Se o menu já estava aberto (o usuário clicou em A4 ou Mobile), abre o preview real
      setPdfPreviewDocKind(kind);
      setPdfPreview(null);
      setPdfPreviewOpen(true);
    }

    try {
      const { exportBudgetPDF, buildWhatsappMessage } = await import("@/features/orcamento/exporters");
      const b: Budget = isContract ? { ...buildBudget(), kind: "contrato" } : buildBudget();
      
      const actualFormat = isContract ? "contrato" : format;
      const result = await exportBudgetPDF(b, company, actualFormat);
      
      saveToHistory(b);
      setCounter((c) => c + 1);

      let docLabel = "Documento";
      if (b.kind === "pedido") docLabel = "Cobrança";
      if (b.kind === "orcamento") docLabel = "Orçamento";
      if (b.kind === "contrato") docLabel = "Contrato";

      setPdfPreviewDocKind(b.kind);
      setPdfPreview(result);
      setPdfPreviewMsg(buildWhatsappMessage(b, company));
      setPdfPreviewPhone(b.client.phone ?? "");
      setPdfPreviewTitle(`${docLabel} Nº ${String(b.number).padStart(4, "0")}`);
    } catch (error) {
      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) {
      
      return;
    }
    setNewBudgetConfirmOpen(true);
  };

  const confirmNewBudget = () => {
    setItems([]);
    setClient(emptyClient);
    setLaborCost(0);
    setLaborCostRaw("");
    setMaterialCost(0);
    setMaterialCostRaw("");
    setDiscountValue(0);
    setDiscountRaw("");
    setDiscountType("fixed");
    setObservations("");
    setMaterials("");
    setMaterialProvidedByClient(false);
    setExecution(emptyExecution);
    setPaymentConditions("");
    setBudgetNumber(null);
    setStartDate("");
    setEndDate("");
    setCityOverride("");
    setClauses(DEFAULT_CLAUSES);
    setNewBudgetConfirmOpen(false);
    // toast.success("Novo documento iniciado");
  };

  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));
  };

  // Material catalog management
  const addNewCatalogMaterial = () => {
    const m: Material = { id: uid(), name: "Novo material", unit: "un" };
    setCatalogMaterials((prev) => [m, ...prev]);
    setEditingCatalogMaterial(m.id);
  };

  const updateCatalogMaterial = (id: string, patch: Partial<Material>) => {
    setCatalogMaterials((prev) => prev.map((m) => (m.id === id ? { ...m, ...patch } : m)));
  };

  const removeCatalogMaterial = (id: string) => {
    if (!confirm("Remover este material do catálogo?")) return;
    setCatalogMaterials((prev) => prev.filter((m) => m.id !== id));
  };

  const filteredCatalogMaterials = useMemo(() => {
    const q = materialSearch.trim().toLowerCase();
    if (!q) return catalogMaterials;
    return catalogMaterials.filter((m) => m.name.toLowerCase().includes(q));
  }, [catalogMaterials, materialSearch]);

  const addMaterialToBudget = (m: Material, qtyOverride?: number) => {
    // Se o material não tem preço no catálogo, pergunta de forma opcional
    if (!m.price || m.price <= 0) {
      setMaterialForPricePrompt(m);
      setPromptedMaterialPrice("");
      setMaterialPricePromptOpen(true);
      return;
    }
    
    executeAddMaterial(m, qtyOverride);
  };

  const executeAddMaterial = (m: Material, qtyOverride?: number, customPrice?: number) => {
    const qty = qtyOverride !== undefined ? qtyOverride : m.defaultQty;
    const qtyStr = qty ? `${qty} ` : "";
    const obsStr = m.observation ? ` (${m.observation})` : "";
    const newLine = `${qtyStr}${m.unit} ${m.name}${obsStr}`;
    
    setMaterials((prev) => {
      const current = prev.trim();
      if (!current) return newLine;
      return current + "\n" + newLine;
    });

    const finalPrice = customPrice !== undefined ? customPrice : (m.price || 0);

    // Se o material tem preço (ou recebeu um agora), soma ao total
    if (finalPrice > 0) {
      const totalMaterialPrice = (qty || 1) * finalPrice;
      setMaterialCost(prev => prev + totalMaterialPrice);
      setMaterialCostRaw(String(materialCost + totalMaterialPrice).replace(".", ","));
    }
    
    setPulseId(m.id);
    window.setTimeout(() => setPulseId((cur) => (cur === m.id ? null : cur)), 350);
    setSelectedMaterialForQty(null);
    setTempMaterialQty("");
  };

  const handlePromptedPriceSave = () => {
    if (!materialForPricePrompt) return;
    
    const priceVal = parseFloat(promptedMaterialPrice.replace(/\./g, "").replace(",", "."));
    const finalPrice = Number.isFinite(priceVal) && priceVal > 0 ? priceVal : 0;
    
    // Se o usuário digitou um preço, salva no catálogo para o futuro
    if (finalPrice > 0) {
      updateCatalogMaterial(materialForPricePrompt.id, { price: finalPrice });
    }
    
    executeAddMaterial(materialForPricePrompt, undefined, finalPrice);
    setMaterialPricePromptOpen(false);
    setMaterialForPricePrompt(null);
  };

  const handleMaterialClick = (m: Material) => {
    setSelectedMaterialForQty(m);
    setTempMaterialQty(m.defaultQty ? String(m.defaultQty) : "1");
  };

  // 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 padrão desativado para permitir navegação nativa fluida
  }, [onboardingDone]);

  return (
    <div 
      className="flex min-h-dvh flex-col bg-background text-foreground overflow-hidden selection:bg-primary/20"
      onTouchStart={onTouchStart}
      onTouchMove={onTouchMove}
      onTouchEnd={onTouchEnd}
    >
      {!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>
            <div className="flex items-center gap-1.5">
              <span className="font-display text-sm uppercase tracking-wide text-muted-foreground whitespace-nowrap">
                {company.numberPrefix?.trim() ? `${company.numberPrefix.trim()} · ` : ""}
              </span>
              {editingBudgetNumber ? (
                <Input
                  type="number"
                  autoFocus
                  className="h-7 w-20 px-1 py-0 text-xs font-bold"
                  value={budgetNumber ?? counter}
                  onChange={(e) => setBudgetNumber(parseInt(e.target.value) || 0)}
                  onBlur={() => setEditingBudgetNumber(false)}
                  onKeyDown={(e) => e.key === "Enter" && setEditingBudgetNumber(false)}
                />
              ) : (
                <button
                  type="button"
                  onClick={() => setEditingBudgetNumber(true)}
                  className="flex items-center gap-1 group font-display text-sm uppercase tracking-wide text-muted-foreground hover:text-foreground transition-colors"
                >
                  <span className="font-bold">
                    Nº {String(budgetNumber ?? counter).padStart(4, "0")}
                  </span>
                  <Pencil className="h-3 w-3 opacity-0 group-hover:opacity-100 transition-opacity" />
                </button>
              )}
            </div>
          </div>
          <div className="flex items-center gap-1">
            <Button
              variant="ghost"
              size="sm"
              onClick={() => navigate("/wa-scripts")}
              className="h-8 gap-1.5 text-primary hover:text-primary hover:bg-primary/5 transition-colors font-semibold"
              aria-label="Scripts WhatsApp"
              title="Scripts WhatsApp"
            >
              <MessageCircle className="h-4 w-4" />
              <span className="text-xs">Scripts</span>
            </Button>
            <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 w-full px-3 pb-44 pt-3 sm:px-4 sm:pt-4 overflow-hidden">
        <Tabs value={tab} onValueChange={setTab} className="w-full">
          <div className="flex flex-col gap-2 mb-4">
            <TabsList className="grid w-full grid-cols-4 bg-secondary h-auto p-1 gap-1">
              <TabsTrigger value="budget" className="flex items-center justify-center gap-1 py-2 px-1">
                <Receipt className="h-3.5 w-3.5 shrink-0" />
                <span className="text-[9px] xs:text-[10px] font-bold uppercase tracking-tight sm:tracking-wider">Inicio</span>
              </TabsTrigger>
              <TabsTrigger value="services" className="flex items-center justify-center gap-1 py-2 px-1">
                <ListChecks className="h-3.5 w-3.5 shrink-0" />
                <span className="text-[9px] xs:text-[10px] font-bold uppercase tracking-tight sm:tracking-wider">Serviços</span>
              </TabsTrigger>
              <TabsTrigger value="materials" className="flex items-center justify-center gap-1 py-2 px-1">
                <Package className="h-3.5 w-3.5 shrink-0" />
                <span className="text-[9px] xs:text-[10px] font-bold uppercase tracking-tight sm:tracking-wider">Materiais</span>
              </TabsTrigger>
              <TabsTrigger value="company" className="flex items-center justify-center gap-1 py-2 px-1">
                <Building2 className="h-3.5 w-3.5 shrink-0" />
                <span className="text-[9px] xs:text-[10px] font-bold uppercase tracking-tight sm:tracking-wider">Empresa</span>
              </TabsTrigger>
            </TabsList>

            {/* Sub-abas ocultas conforme solicitado. Para reverter, basta remover o comentário ou a condição false */}
            {false && (
              <div className="grid w-full grid-cols-3 bg-secondary rounded-lg h-auto p-1 gap-1">
                <button
                  onClick={() => navigate("/wa-scripts")}
                  className="flex items-center justify-center gap-1 py-2 px-1 rounded-md text-muted-foreground hover:text-foreground hover:bg-background/50 transition-all border border-primary/20 bg-primary/5 shadow-[0_0_10px_-2px_rgba(var(--primary),0.2)]"
                >
                  <MessageCircle className="h-3.5 w-3.5 shrink-0 text-primary" />
                  <span className="text-[9px] xs:text-[10px] font-bold uppercase tracking-tight sm:tracking-wider text-primary">Scripts</span>
                </button>
                <button
                  onClick={() => {
                    setUpsellSubject("contrato");
                    setUpsellOpen(true);
                  }}
                  className="relative flex items-center justify-center gap-1 py-2 px-1 rounded-md text-muted-foreground/40 hover:text-foreground/60 hover:bg-background/30 transition-all border border-border/20 group scale-95 origin-center"
                >
                  <FileText className="h-3 w-3 shrink-0 opacity-40 group-hover:opacity-60" />
                  <span className="text-[8px] xs:text-[9px] font-bold uppercase tracking-tight sm:tracking-wider">Contratos</span>
                  <Lock className="absolute right-0.5 top-0.5 h-2 w-2 text-primary/30 group-hover:text-primary/50" />
                </button>
                <button
                  onClick={() => {
                    setUpsellSubject("arquivos");
                    setUpsellOpen(true);
                  }}
                  className="relative flex items-center justify-center gap-1 py-2 px-1 rounded-md text-muted-foreground/40 hover:text-foreground/60 hover:bg-background/30 transition-all border border-border/20 group scale-95 origin-center"
                >
                  <Files className="h-3 w-3 shrink-0 opacity-40 group-hover:opacity-60" />
                  <span className="text-[8px] xs:text-[9px] font-bold uppercase tracking-tight sm:tracking-wider">Packs</span>
                  <Lock className="absolute right-0.5 top-0.5 h-2 w-2 text-primary/30 group-hover:text-primary/50" />
                </button>
              </div>
            )}
          </div>

          {/* ======================== 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={() => handleDocumentKindChange(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 })}
                />
                <div className="grid grid-cols-2 gap-2">
                  <Input
                    placeholder="Documento (Opcional)"
                    value={client.document ?? ""}
                    onChange={(e) => setClient({ ...client, document: e.target.value })}
                  />
                  <div className="flex bg-secondary/50 p-0.5 rounded-lg border border-border/40">
                    <button
                      type="button"
                      onClick={() => setClient({ ...client, documentType: "CPF" })}
                      className={`flex-1 rounded-md text-[10px] font-medium transition-all ${
                        client.documentType === "CPF" || !client.documentType
                          ? "bg-background text-foreground shadow-sm"
                          : "text-muted-foreground hover:text-foreground"
                      }`}
                    >
                      CPF
                    </button>
                    <button
                      type="button"
                      onClick={() => setClient({ ...client, documentType: "CNPJ" })}
                      className={`flex-1 rounded-md text-[10px] font-medium transition-all ${
                        client.documentType === "CNPJ"
                          ? "bg-background text-foreground shadow-sm"
                          : "text-muted-foreground hover:text-foreground"
                      }`}
                    >
                      CNPJ
                    </button>
                  </div>
                </div>
                <Input
                  placeholder="(11) 91234-5678"
                  inputMode="tel"
                  value={client.phone}
                  onChange={(e) =>
                    setClient({ ...client, phone: formatPhoneBR(e.target.value) })
                  }
                  maxLength={16}
                />
                <div className="grid grid-cols-[1fr_80px] gap-2">
                  <Input
                    placeholder="Rua / Logradouro"
                    value={client.address}
                    onChange={(e) =>
                      setClient({ ...client, address: e.target.value })
                    }
                  />
                  <Input
                    placeholder="Nº"
                    value={client.addressNumber ?? ""}
                    onChange={(e) =>
                      setClient({ ...client, addressNumber: e.target.value })
                    }
                  />
                </div>
                <Input
                  placeholder="Bairro"
                  value={client.addressNeighborhood ?? ""}
                  onChange={(e) =>
                    setClient({ ...client, addressNeighborhood: 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>
                          <MoneyInput
                            value={it.price}
                            onValueChange={(v) =>
                              updateItem(it.id, { price: 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>

            {/* Discount section */}
            <section className="space-y-4 rounded-xl border border-border/60 bg-card p-4 shadow-sm">
              <div className="flex items-center justify-between">
                <h2 className="text-[11px] font-semibold uppercase tracking-wider text-muted-foreground flex items-center gap-1.5">
                  <Receipt className="h-3 w-3" /> Desconto Opcional
                </h2>
                <div className="flex gap-1 bg-secondary p-0.5 rounded-lg border border-border/40">
                  <button
                    type="button"
                    onClick={() => setDiscountType("fixed")}
                    className={`px-2 py-1 text-[10px] font-bold rounded-md transition-all ${
                      discountType === "fixed" 
                        ? "bg-background text-foreground shadow-sm" 
                        : "text-muted-foreground hover:text-foreground"
                    }`}
                  >
                    R$
                  </button>
                  <button
                    type="button"
                    onClick={() => setDiscountType("percentage")}
                    className={`px-2 py-1 text-[10px] font-bold rounded-md transition-all ${
                      discountType === "percentage" 
                        ? "bg-background text-foreground shadow-sm" 
                        : "text-muted-foreground hover:text-foreground"
                    }`}
                  >
                    %
                  </button>
                </div>
              </div>
              
              <div className="relative">
                <Input
                  type="text"
                  inputMode="decimal"
                  placeholder={discountType === "fixed" ? "0,00" : "0"}
                  className="pl-9 h-11 text-base font-medium"
                  value={discountRaw}
                  onChange={(e) => {
                    const val = e.target.value;
                    setDiscountRaw(val);
                    const numeric = parseFloat(val.replace(/\./g, "").replace(",", "."));
                    setDiscountValue(Number.isFinite(numeric) ? numeric : 0);
                  }}
                />
                <div className="absolute left-3 top-1/2 -translate-y-1/2 flex items-center justify-center pointer-events-none">
                  {discountType === "fixed" ? (
                    <span className="text-sm font-bold text-muted-foreground">R$</span>
                  ) : (
                    <span className="text-sm font-bold text-muted-foreground">%</span>
                  )}
                </div>
                {discountValue > 0 && discountType === "percentage" && (
                  <div className="absolute right-3 top-1/2 -translate-y-1/2 text-xs font-semibold text-success bg-success/10 px-2 py-1 rounded-md">
                    - {formatBRL(discountAmount)}
                  </div>
                )}
              </div>
            </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>
                    <div className="flex items-center gap-2">
                      {(company.hourlyRate! > 0 || company.dailyRate! > 0) && (
                        <Dialog>
                          <DialogTrigger asChild>
                            <button
                              type="button"
                              className="text-[10px] text-primary hover:underline"
                            >
                              calcular
                            </button>
                          </DialogTrigger>
                          <DialogContent className="max-w-[320px] rounded-2xl p-6">
                            <DialogHeader>
                              <DialogTitle className="text-base">Calcular Mão de Obra</DialogTitle>
                              <DialogDescription className="text-xs">
                                Use seus valores base definidos na tela Empresa.
                              </DialogDescription>
                            </DialogHeader>
                            <div className="space-y-4 py-4">
                              {company.hourlyRate! > 0 && (
                                <div className="space-y-2">
                                  <label className="text-[11px] font-semibold uppercase tracking-wider text-muted-foreground">
                                    Por Horas (R$ {formatBRL(company.hourlyRate!).replace("R$", "").trim()}/h)
                                  </label>
                                  <div className="flex gap-2">
                                    <Input
                                      type="number"
                                      placeholder="Qtd horas"
                                      className="h-10"
                                      onChange={(e) => {
                                        const qty = parseFloat(e.target.value);
                                        if (qty > 0) {
                                          const total = qty * company.hourlyRate!;
                                          setLaborCost(total);
                                          setLaborCostRaw(String(total).replace(".", ","));
                                        }
                                      }}
                                    />
                                  </div>
                                </div>
                              )}
                              {company.dailyRate! > 0 && (
                                <div className="space-y-2">
                                  <label className="text-[11px] font-semibold uppercase tracking-wider text-muted-foreground">
                                    Por Dias (R$ {formatBRL(company.dailyRate!).replace("R$", "").trim()}/dia)
                                  </label>
                                  <div className="flex gap-2">
                                    <Input
                                      type="number"
                                      placeholder="Qtd dias"
                                      className="h-10"
                                      onChange={(e) => {
                                        const qty = parseFloat(e.target.value);
                                        if (qty > 0) {
                                          const total = qty * company.dailyRate!;
                                          setLaborCost(total);
                                          setLaborCostRaw(String(total).replace(".", ","));
                                        }
                                      }}
                                    />
                                  </div>
                                </div>
                              )}
                            </div>
                            <DialogTrigger asChild>
                              <Button className="w-full" variant="secondary">
                                Pronto
                              </Button>
                            </DialogTrigger>
                          </DialogContent>
                        </Dialog>
                      )}
                      {laborCost > 0 && (
                        <button
                          type="button"
                          onClick={() => { setLaborCost(0); setLaborCostRaw(""); }}
                          className="text-[10px] text-muted-foreground hover:text-destructive"
                        >
                          limpar
                        </button>
                      )}
                    </div>
                  </div>
                  <div className="relative mt-3">
                    <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={laborCostRaw || (laborCost > 0 ? String(laborCost).replace(".", ",") : "")}
                      onChange={(e) => {
                        const val = e.target.value;
                        setLaborCostRaw(val);
                        const v = parseFloat(val.replace(/\./g, "").replace(",", "."));
                        setLaborCost(Number.isFinite(v) && v > 0 ? v : 0);
                      }}
                      onBlur={() => {
                        setLaborCostRaw(laborCost > 0 ? String(laborCost).replace(".", ",") : "");
                      }}
                      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); setMaterialCostRaw(""); }}
                        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={materialCostRaw || (materialCost > 0 ? String(materialCost).replace(".", ",") : "")}
                      onChange={(e) => {
                        const val = e.target.value;
                        setMaterialCostRaw(val);
                        const v = parseFloat(val.replace(/\./g, "").replace(",", "."));
                        setMaterialCost(Number.isFinite(v) && v > 0 ? v : 0);
                      }}
                      onBlur={() => {
                        setMaterialCostRaw(materialCost > 0 ? String(materialCost).replace(".", ",") : "");
                      }}
                      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>
            {/* ABA 1 — ORÇAMENTO (Continuação) */}
            
            {/* Materiais */}
            <section className="space-y-3">
              <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2">
                <h2 className="text-[11px] font-semibold uppercase tracking-wider text-muted-foreground">
                  Materiais utilizados
                </h2>
                <div className="flex items-center gap-2">
                  <Button
                    variant="electric"
                    size="sm"
                    onClick={() => setMaterialPickerOpen(true)}
                    className="h-8 gap-1.5 px-3 text-xs font-semibold shadow-sm"
                  >
                    <Package className="h-3.5 w-3.5" /> Catálogo
                  </Button>
                  <span className="text-xs text-muted-foreground">Fornecido pelo cliente</span>
                  <ToggleSwitch 
                    checked={materialProvidedByClient} 
                    onChange={() => setMaterialProvidedByClient(!materialProvidedByClient)} 
                    label="Material fornecido pelo cliente" 
                  />
                </div>
              </div>
              <Textarea
                placeholder="Ex: Cabo 2,5mm, conduíte, disjuntor..."
                value={materials}
                onChange={(e) => setMaterials(e.target.value)}
                className="min-h-[100px] bg-secondary/30 border-transparent focus-visible:bg-background"
              />
              <div className="flex flex-wrap gap-2">
                <Button 
                  variant="outline" 
                  size="sm" 
                  onClick={() => setMaterials(prev => prev ? prev + "\nMaterial por conta do cliente" : "Material por conta do cliente")}
                  className="h-7 text-[10px]"
                >
                  + Material p/ conta cliente
                </Button>
              </div>
            </section>

            {/* Observações da obra */}
            <section className="space-y-3">
              <h2 className="text-[11px] font-semibold uppercase tracking-wider text-muted-foreground">
                Observações da obra
              </h2>
              <Textarea
                placeholder="Ex: Material fornecido pelo cliente, Necessário desligamento geral..."
                value={observations}
                onChange={(e) => setObservations(e.target.value)}
                className="min-h-[100px] bg-secondary/30 border-transparent focus-visible:bg-background"
              />
              <div className="flex flex-wrap gap-2">
                {[
                  "Material fornecido pelo cliente",
                  "Necessário desligamento geral",
                  "Serviço sujeito à avaliação no local",
                  "Não incluso reparos civis",
                  "Garantia de 90 dias",
                  "Não incluso alvenaria"
                ].map(txt => (
                  <Button 
                    key={txt}
                    variant="outline" 
                    size="sm" 
                    onClick={() => setObservations(prev => prev ? prev + "\n" + txt : txt)}
                    className="h-7 text-[10px]"
                  >
                    + {txt}
                  </Button>
                ))}
              </div>
            </section>

            {/* ABA 2 — COBRANÇA (Execução e Condições) */}
            <section className="space-y-6 pt-4 border-t border-border/60">
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
                <div className="space-y-4">
                  <h2 className="flex items-center gap-2 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground">
                    <CalendarClock className="h-3.5 w-3.5" /> Execução
                  </h2>
                  <div className="space-y-3">
                    <div className="space-y-1.5">
                      <label className="text-xs font-medium text-muted-foreground">Validade (dias)</label>
                      <Input 
                        type="number"
                        value={execution.validityDays}
                        onChange={(e) => setExecution({...execution, validityDays: parseInt(e.target.value) || 0})}
                        className="h-9"
                      />
                    </div>
                    <div className="space-y-1.5">
                      <label className="text-xs font-medium text-muted-foreground">Prazo estimado</label>
                      <Input 
                        placeholder="Ex: 2 dias úteis"
                        value={execution.estimatedDeadline}
                        onChange={(e) => setExecution({...execution, estimatedDeadline: e.target.value})}
                        className="h-9"
                      />
                    </div>
                    <div className="space-y-1.5">
                      <label className="text-xs font-medium text-muted-foreground">Duração estimada</label>
                      <Input 
                        placeholder="Ex: 16 horas"
                        value={execution.estimatedDuration}
                        onChange={(e) => setExecution({...execution, estimatedDuration: e.target.value})}
                        className="h-9"
                      />
                    </div>
                  </div>
                </div>

                <div className="space-y-4">
                  <h2 className="flex items-center gap-2 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground">
                    <Receipt className="h-3.5 w-3.5" /> Pagamento
                  </h2>
                  <div className="space-y-3">
                    <div className="space-y-1.5">
                      <label className="text-xs font-medium text-muted-foreground">Condições de pagamento</label>
                      <Textarea 
                        placeholder="Ex: 50% entrada + 50% conclusão, PIX, Cartão..."
                        value={paymentConditions}
                        onChange={(e) => setPaymentConditions(e.target.value)}
                        className="min-h-[135px] text-sm"
                      />
                    </div>
                  </div>
                </div>
              </div>
            </section>
          </TabsContent>
          <TabsContent value="services" className="mt-4 space-y-3 w-full max-w-full overflow-hidden">
            <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 w-full max-w-full overflow-hidden">
              {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-2.5 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>
                            <MoneyInput
                              value={s.price}
                              onValueChange={(v) =>
                                updateService(s.id, { price: 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-2">
                        <button
                          type="button"
                          onClick={() => addServiceToBudget(s)}
                          className="flex flex-1 items-center justify-between text-left active:scale-[0.98] transition-transform overflow-hidden"
                        >
                          <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 flex-1">
                              <p className="truncate text-[13px] font-medium leading-tight">
                                {s.name}
                              </p>
                              <p className="text-[11px] text-muted-foreground truncate leading-tight">
                                {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-1.5 flex h-7 w-7 shrink-0 items-center justify-center rounded-full transition-colors ${
                              isSelected
                                ? "bg-primary text-primary-foreground"
                                : "bg-primary/10 text-primary"
                            }`}
                          >
                            <Plus className="h-4 w-4" />
                          </span>
                        </button>
                        <Button
                          size="icon"
                          variant="ghost"
                          onClick={(e) => {
                            e.stopPropagation();
                            setEditingService(s.id);
                          }}
                          className="h-7 w-7 shrink-0 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>

          <TabsContent value="materials" className="mt-4 space-y-3 w-full max-w-full overflow-hidden">
            <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 material no catálogo…"
                  value={materialSearch}
                  onChange={(e) => setMaterialSearch(e.target.value)}
                  className="pl-9"
                />
              </div>
              <Button onClick={addNewCatalogMaterial} size="icon" variant="electric">
                <Plus className="h-4 w-4" />
              </Button>
            </div>

            <ul className="space-y-2 w-full max-w-full overflow-hidden pb-4">
              {filteredCatalogMaterials.map((m) => {
                const isEditing = editingCatalogMaterial === m.id;
                const isPulsing = pulseId === m.id;
                return (
                  <li
                    key={m.id}
                    className={`rounded-xl border bg-card p-2.5 transition-all border-border/60 ${
                      isPulsing ? "scale-[1.015] ring-2 ring-primary/50" : ""
                    }`}
                  >
                    {isEditing ? (
                      <div className="space-y-2">
                        <Input
                          value={m.name}
                          onChange={(e) =>
                            updateCatalogMaterial(m.id, { name: e.target.value })
                          }
                          placeholder="Nome do material"
                        />
                        <div className="flex gap-2">
                          <Input
                            value={m.unit}
                            onChange={(e) =>
                              updateCatalogMaterial(m.id, { unit: e.target.value })
                            }
                            placeholder="Unidade"
                            className="flex-1"
                          />
                          <div className="relative w-24">
                            <Input
                              type="number"
                              value={m.defaultQty ?? ""}
                              onChange={(e) =>
                                updateCatalogMaterial(m.id, { 
                                  defaultQty: e.target.value ? parseInt(e.target.value) : undefined 
                                })
                              }
                              placeholder="Qtd"
                              className="pl-8"
                            />
                            <span className="pointer-events-none absolute left-2 top-1/2 -translate-y-1/2 text-[10px] font-bold text-muted-foreground uppercase">
                              Qtd
                            </span>
                          </div>
                          <div className="relative flex-1">
                            <MoneyInput
                              allowUndefined
                              value={m.price}
                              onValueChange={(v) =>
                                updateCatalogMaterial(m.id, { price: v })
                              }
                              placeholder="0,00"
                              className="pl-8"
                            />
                            <span className="pointer-events-none absolute left-2 top-1/2 -translate-y-1/2 text-[10px] font-bold text-muted-foreground uppercase">
                              R$
                            </span>
                          </div>
                        </div>
                        <Input
                          value={m.observation ?? ""}
                          onChange={(e) =>
                            updateCatalogMaterial(m.id, { observation: e.target.value })
                          }
                          placeholder="Observação (opcional)"
                        />
                        <div className="flex gap-2 pt-1">
                          <Button
                            size="sm"
                            variant="electric"
                            onClick={() => setEditingCatalogMaterial(null)}
                            className="flex-1 gap-1"
                          >
                            <Check className="h-4 w-4" /> Salvar
                          </Button>
                          <Button
                            size="sm"
                            variant="ghost"
                            onClick={() => removeCatalogMaterial(m.id)}
                            className="text-destructive"
                          >
                            <Trash2 className="h-4 w-4" />
                          </Button>
                        </div>
                      </div>
                    ) : (
                      <div className="flex items-center gap-2">
                        <button
                          type="button"
                          onClick={() => addMaterialToBudget(m)}
                          className="flex flex-1 items-center justify-between text-left active:scale-[0.98] transition-transform overflow-hidden"
                        >
                        <div className="min-w-0 flex items-center gap-2">
                            <div className="min-w-0 flex-1">
                              <p className="truncate text-[13px] font-medium leading-tight">
                                {m.name}
                              </p>
                              <p className="text-[11px] text-muted-foreground truncate leading-tight">
                                {m.unit}
                                {m.defaultQty ? ` • Padrão: ${m.defaultQty}` : ""}
                                {m.price ? ` • ${formatBRL(m.price)}` : ""}
                                {m.observation ? ` • ${m.observation}` : ""}
                              </p>
                            </div>
                          </div>
                          <span className="ml-1.5 flex h-7 w-7 shrink-0 items-center justify-center rounded-full bg-primary/10 text-primary transition-colors hover:bg-primary hover:text-primary-foreground">
                            <Plus className="h-4 w-4" />
                          </span>
                        </button>
                        <Button
                          size="icon"
                          variant="ghost"
                          onClick={(e) => {
                            e.stopPropagation();
                            setEditingCatalogMaterial(m.id);
                          }}
                          className="h-7 w-7 shrink-0 text-muted-foreground"
                          aria-label="Editar"
                        >
                          <Pencil className="h-3.5 w-3.5" />
                        </Button>
                      </div>
                    )}
                  </li>
                );
              })}
              {filteredCatalogMaterials.length === 0 && (
                <li className="rounded-lg border border-dashed border-border/60 p-6 text-center text-sm text-muted-foreground">
                  Nenhum material encontrado no catálogo.
                </li>
              )}
            </ul>
          </TabsContent>


          {/* ======================== COMPANY ======================== */}
          <TabsContent value="company" className="mt-6 space-y-8 w-full max-w-full overflow-hidden">
            {/* 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-4">
                <h2 className="text-[11px] font-semibold uppercase tracking-wider text-muted-foreground">
                  Cores da marca
                </h2>
                <div className="grid gap-3">
                  {[
                    {
                      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 rounded-xl border border-border/60 bg-secondary/10 p-2.5 transition-all"
                    >
                      <input
                        type="color"
                        value={c.value}
                        onChange={(e) => c.onChange(e.target.value)}
                        className="h-10 w-10 shrink-0 cursor-pointer overflow-hidden rounded-lg border-none bg-transparent"
                        aria-label={c.label}
                      />
                      <div className="min-w-0 flex-1">
                        <p className="text-sm font-medium">{c.label}</p>
                        <p className="font-mono text-[10px] text-muted-foreground">
                          {c.value.toUpperCase()}
                        </p>
                      </div>
                      <button
                        type="button"
                        onClick={() => setEyedropperFor(c.key)}
                        className="flex items-center gap-1.5 rounded-md px-2 py-1 text-[11px] font-medium text-primary hover:bg-primary/10"
                      >
                        <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="w-fit text-[11px] font-medium text-muted-foreground transition-colors hover:text-destructive"
                    >
                      Redefinir para cores automáticas
                    </button>
                  )}
                </div>
              </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 })}
              />
              <div className="space-y-1.5">
                <Input
                  placeholder="CPF ou CNPJ"
                  value={company.document}
                  onChange={(e) =>
                    setCompany({ ...company, document: formatDocumentBR(e.target.value) })
                  }
                  maxLength={18}
                />
                <div className="flex items-center justify-between px-1">
                  <span className="text-[11px] text-muted-foreground">Exibir registro no:</span>
                  <div className="flex bg-secondary/50 p-0.5 rounded-lg border border-border/40">
                    <button
                      type="button"
                      onClick={() => setCompany({ ...company, documentPosition: "header" })}
                      className={`px-2 py-0.5 rounded-md text-[10px] font-medium transition-all ${
                        company.documentPosition === "header"
                          ? "bg-background text-foreground shadow-sm"
                          : "text-muted-foreground hover:text-foreground"
                      }`}
                    >
                      Topo
                    </button>
                    <button
                      type="button"
                      onClick={() => setCompany({ ...company, documentPosition: "footer" })}
                      className={`px-2 py-0.5 rounded-md text-[10px] font-medium transition-all ${
                        (company.documentPosition === "footer" || !company.documentPosition)
                          ? "bg-background text-foreground shadow-sm"
                          : "text-muted-foreground hover:text-foreground"
                      }`}
                    >
                      Rodapé
                    </button>
                    <button
                      type="button"
                      onClick={() => setCompany({ ...company, documentPosition: "none" })}
                      className={`px-2 py-0.5 rounded-md text-[10px] font-medium transition-all ${
                        company.documentPosition === "none"
                          ? "bg-background text-foreground shadow-sm"
                          : "text-muted-foreground hover:text-foreground"
                      }`}
                    >
                      Nenhum
                    </button>
                  </div>
                </div>
              </div>
              <Input
                placeholder="E-mail (Opcional)"
                type="email"
                value={company.email ?? ""}
                onChange={(e) => setCompany({ ...company, email: e.target.value })}
              />
              <div className="grid grid-cols-2 gap-2">
                <Input
                  placeholder="Cidade"
                  value={company.city ?? ""}
                  onChange={(e) => setCompany({ ...company, city: e.target.value })}
                />
                <Input
                  placeholder="UF"
                  maxLength={2}
                  value={company.state ?? ""}
                  onChange={(e) => setCompany({ ...company, state: e.target.value.toUpperCase() })}
                />
              </div>
              <Input
                placeholder="Telefone de contato"
                value={company.contact}
                onChange={(e) => {
                  const val = e.target.value;
                  const formatted = val.replace(/\D/g, "").length <= 11 && !val.includes("@") 
                    ? formatPhoneBR(val) 
                    : val;
                  setCompany({ ...company, contact: formatted });
                }}
              />
            </div>
            
            {/* Assinatura */}
            <div className="space-y-4">
              <h2 className="text-[11px] font-semibold uppercase tracking-wider text-muted-foreground flex items-center gap-2">
                <Pencil className="h-3.5 w-3.5" /> Assinatura Digital
              </h2>
              <div 
                className={`relative flex flex-col items-center justify-center gap-3 rounded-2xl border-2 border-dashed transition-all p-6 ${
                  company.signatureDataUrl 
                    ? "border-primary/20 bg-primary/5" 
                    : "border-border bg-secondary/30 hover:bg-secondary/50"
                }`}
              >
                {company.signatureDataUrl ? (
                  <div className="flex flex-col items-center gap-4 w-full">
                    <div className="bg-white p-4 rounded-xl shadow-sm border border-border/20 max-w-[200px]">
                      <img 
                        src={company.signatureDataUrl} 
                        alt="Assinatura" 
                        className="max-h-24 w-auto object-contain grayscale"
                      />
                    </div>
                    <div className="flex gap-2">
                      <Button
                        type="button"
                        variant="outline"
                        size="sm"
                        className="h-8 rounded-lg text-xs"
                        onClick={() => setCropperOpen(true)}
                      >
                        Refazer Assinatura
                      </Button>

                      <Button
                        type="button"
                        variant="ghost"
                        size="sm"
                        className="h-8 rounded-lg text-xs text-destructive hover:bg-destructive/10"
                        onClick={() => {
                          setCompany({ ...company, signatureDataUrl: undefined });
                          
                        }}
                      >
                        Remover
                      </Button>
                    </div>
                  </div>
                ) : (
                  <>
                    <div className="h-12 w-12 rounded-full bg-background flex items-center justify-center shadow-sm">
                      <Plus className="h-6 w-6 text-muted-foreground" />
                    </div>
                    <div className="text-center">
                      <p className="text-sm font-bold">Assinar Digitalmente</p>
                      <p className="text-[11px] text-muted-foreground mt-1">
                        Assine diretamente na tela do seu celular ou computador.
                      </p>
                    </div>
                    <Button
                      type="button"
                      variant="electric"
                      size="sm"
                      className="mt-2 rounded-xl h-10 px-6 font-bold uppercase tracking-widest text-[10px]"
                      onClick={() => setCropperOpen(true)}
                    >
                      Abrir Tela de Assinatura
                    </Button>

                  </>
                )}
              </div>
            </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);
                    } catch {
                    }
                  }}
                  aria-label="Copiar chave PIX"
                  className="shrink-0"
                >
                  <Copy className="h-4 w-4" />
                </Button>
              </div>
            </div>

            {/* Valor da Hora/Dia — opcional */}
            <div className="space-y-4">
              <h2 className="text-[11px] font-semibold uppercase tracking-wider text-muted-foreground">
                Valor do Trabalho <span className="font-normal normal-case text-muted-foreground/70">(opcional)</span>
              </h2>
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <label className="text-[10px] font-bold uppercase text-muted-foreground/70 ml-1 flex items-center gap-1">
                    <Clock className="w-3 h-3" /> Valor da Hora
                  </label>
                  <div className="relative">
                    <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"
                      placeholder="0,00"
                      value={company.hourlyRate ? String(company.hourlyRate).replace(".", ",") : ""}
                      onChange={(e) => {
                        const v = parseFloat(e.target.value.replace(",", "."));
                        setCompany({ ...company, hourlyRate: Number.isFinite(v) ? v : 0 });
                      }}
                      className="pl-8"
                    />
                  </div>
                </div>
                <div className="space-y-2">
                  <label className="text-[10px] font-bold uppercase text-muted-foreground/70 ml-1 flex items-center gap-1">
                    <CalendarClock className="w-3 h-3" /> Valor do Dia
                  </label>
                  <div className="relative">
                    <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"
                      placeholder="0,00"
                      value={company.dailyRate ? String(company.dailyRate).replace(".", ",") : ""}
                      onChange={(e) => {
                        const v = parseFloat(e.target.value.replace(",", "."));
                        setCompany({ ...company, dailyRate: Number.isFinite(v) ? v : 0 });
                      }}
                      className="pl-8"
                    />
                  </div>
                </div>
              </div>
              <p className="text-[11px] leading-relaxed text-muted-foreground">
                Estes valores servem de base para o cálculo automático de mão de obra na tela do orçamento.
              </p>
            </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}
              />
              
              <div className="flex items-center justify-between gap-3 pt-1">
                <div className="min-w-0 flex-1">
                  <p className="text-sm font-medium">Próximo número automático</p>
                  <p className="text-[11px] leading-relaxed text-muted-foreground">
                    Define o número que será usado no próximo orçamento criado.
                  </p>
                </div>
                {editingCounter ? (
                  <div className="flex items-center gap-1">
                    <Input
                      type="number"
                      autoFocus
                      className="h-9 w-24 text-center font-mono font-bold"
                      value={counter}
                      onChange={(e) => setCounter(parseInt(e.target.value) || 0)}
                      onBlur={() => setEditingCounter(false)}
                      onKeyDown={(e) => e.key === "Enter" && setEditingCounter(false)}
                    />
                    <Button size="icon" variant="ghost" className="h-8 w-8" onClick={() => setEditingCounter(false)}>
                      <Check className="h-4 w-4 text-primary" />
                    </Button>
                  </div>
                ) : (
                  <button
                    type="button"
                    onClick={() => setEditingCounter(true)}
                    className="flex items-center gap-2 rounded-md border border-border/60 bg-secondary/20 px-3 py-1.5 hover:bg-secondary/40 transition-colors"
                  >
                    <span className="font-mono font-bold text-primary">
                      {String(counter).padStart(4, "0")}
                    </span>
                    <Pencil className="h-3.5 w-3.5 text-muted-foreground" />
                  </button>
                )}
              </div>

              <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>

            {/* Títulos do PDF */}
            <div className="space-y-4">
              <h2 className="text-[11px] font-semibold uppercase tracking-wider text-muted-foreground">
                Títulos no PDF
              </h2>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div className="space-y-2">
                  <label className="text-[10px] font-bold uppercase text-muted-foreground/70 ml-1">Para Orçamentos</label>
                  <Input
                    placeholder="Ex: ORÇAMENTO"
                    value={company.budgetTitle ?? ""}
                    onChange={(e) => setCompany({ ...company, budgetTitle: e.target.value })}
                  />
                  <Input
                    placeholder="Ex: DE SERVIÇO ELÉTRICO"
                    value={company.budgetSubtitle ?? ""}
                    onChange={(e) => setCompany({ ...company, budgetSubtitle: e.target.value })}
                  />
                </div>
                <div className="space-y-2">
                  <label className="text-[10px] font-bold uppercase text-muted-foreground/70 ml-1">Para Cobranças</label>
                  <Input
                    placeholder="Ex: COBRANÇA"
                    value={company.pedidoTitle ?? ""}
                    onChange={(e) => setCompany({ ...company, pedidoTitle: e.target.value })}
                  />
                  <Input
                    placeholder="Ex: DE SERVIÇO EXECUTADO"
                    value={company.pedidoSubtitle ?? ""}
                    onChange={(e) => setCompany({ ...company, pedidoSubtitle: e.target.value })}
                  />
                </div>
              </div>
              <p className="text-[11px] leading-relaxed text-muted-foreground">
                Personalize como o cabeçalho do documento aparece para o cliente. Se deixar vazio, os nomes padrão serão usados.
              </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>

            <TabsContent value="contract" className="mt-0 focus-visible:outline-none">
              <div className="space-y-4 animate-in fade-in slide-in-from-bottom-2 duration-300 pb-10">
                <div className="rounded-2xl border border-border/60 bg-card/30 p-4 space-y-6">
                  {/* Período do Contrato */}
                  <div className="space-y-4">
                    <div className="flex items-center gap-2 mb-1">
                      <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-primary/10 text-primary border border-primary/20">
                        <Calendar className="h-4 w-4" />
                      </div>
                      <h2 className="text-sm font-bold uppercase tracking-wider text-foreground">Período de Execução</h2>
                    </div>
                    
                    <div className="grid grid-cols-2 gap-3">
                      <div className="space-y-1.5">
                        <label className="text-[10px] font-bold uppercase text-muted-foreground/70 ml-1">Data de Início</label>
                        <Input
                          type="date"
                          value={startDate}
                          onChange={(e) => setStartDate(e.target.value)}
                          className="h-10 text-sm"
                        />
                      </div>
                      <div className="space-y-1.5">
                        <label className="text-[10px] font-bold uppercase text-muted-foreground/70 ml-1">Data de Término</label>
                        <Input
                          type="date"
                          value={endDate}
                          onChange={(e) => setEndDate(e.target.value)}
                          className="h-10 text-sm"
                        />
                      </div>
                    </div>
                  </div>

                  {/* Local da Assinatura */}
                  <div className="space-y-4 pt-4 border-t border-border/40">
                    <div className="flex items-center gap-2 mb-1">
                      <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-primary/10 text-primary border border-primary/20">
                        <Building2 className="h-4 w-4" />
                      </div>
                      <h2 className="text-sm font-bold uppercase tracking-wider text-foreground">Local da Assinatura</h2>
                    </div>
                    
                    <div className="space-y-1.5">
                      <label className="text-[10px] font-bold uppercase text-muted-foreground/70 ml-1">Cidade (Opcional)</label>
                      <Input
                        placeholder={company.city || "Cidade onde o contrato será assinado"}
                        value={cityOverride}
                        onChange={(e) => setCityOverride(e.target.value)}
                        className="h-10 text-sm"
                      />
                    </div>
                  </div>

                  {/* Cláusulas Contratuais */}
                  <div className="space-y-4 pt-4 border-t border-border/40">
                    <div className="flex items-center justify-between mb-1">
                      <div className="flex items-center gap-2">
                        <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-primary/10 text-primary border border-primary/20">
                          <FileText className="h-4 w-4" />
                        </div>
                        <h2 className="text-sm font-bold uppercase tracking-wider text-foreground">Cláusulas</h2>
                      </div>
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => {
                          const newClause: ContractClause = {
                            id: uid(),
                            title: `CLÁUSULA ${clauses.length + 1}`,
                            content: ""
                          };
                          setClauses([...clauses, newClause]);
                        }}
                        className="h-8 gap-1.5 text-xs text-primary hover:text-primary hover:bg-primary/5"
                      >
                        <PlusCircle className="h-3.5 w-3.5" /> Adicionar
                      </Button>
                    </div>

                    <div className="space-y-4">
                      {clauses.map((clause, index) => (
                        <div key={clause.id} className="group relative rounded-xl border border-border/60 bg-background/50 p-3.5 space-y-2.5 transition-all hover:border-primary/30">
                          <div className="flex items-center justify-between gap-3">
                            <Input
                              value={clause.title}
                              onChange={(e) => {
                                const newClauses = [...clauses];
                                newClauses[index].title = e.target.value;
                                setClauses(newClauses);
                              }}
                              className="h-8 border-none bg-transparent p-0 text-sm font-bold focus-visible:ring-0 uppercase tracking-tight"
                            />
                            <div className="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
                              <Button
                                variant="ghost"
                                size="icon"
                                className="h-7 w-7 text-muted-foreground hover:text-destructive"
                                onClick={() => setClauses(clauses.filter(c => c.id !== clause.id))}
                              >
                                <Trash2 className="h-3.5 w-3.5" />
                              </Button>
                            </div>
                          </div>
                          <Textarea
                            value={clause.content}
                            onChange={(e) => {
                              const newClauses = [...clauses];
                              newClauses[index].content = e.target.value;
                              setClauses(newClauses);
                            }}
                            className="min-h-[100px] text-[11px] leading-relaxed border-none bg-transparent p-0 focus-visible:ring-0 resize-none"
                            placeholder="Conteúdo da cláusula..."
                          />
                          {clause.content.includes('{') && (
                            <div className="flex flex-wrap gap-1 mt-1">
                              {['{valor_total}', '{condicoes_pagamento}', '{garantia_dias}', '{cidade_assinatura}', '{observacoes}'].map(tag => (
                                clause.content.includes(tag) && (
                                  <span key={tag} className="px-1.5 py-0.5 bg-primary/10 text-primary text-[9px] rounded font-mono">
                                    {tag}
                                  </span>
                                )
                              ))}
                            </div>
                          )}
                        </div>
                      ))}
                    </div>

                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => setClauses(DEFAULT_CLAUSES)}
                      className="w-full h-9 gap-1.5 text-xs border-dashed"
                    >
                      <RotateCcw className="h-3.5 w-3.5" /> Restaurar Cláusulas Padrão
                    </Button>
                  </div>
                </div>

                {/* Observações do Contrato */}
                <div className="rounded-2xl border border-border/60 bg-card/30 p-4 space-y-4">
                  <div className="flex items-center gap-2 mb-1">
                    <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-primary/10 text-primary border border-primary/20">
                      <StickyNote className="h-4 w-4" />
                    </div>
                    <h2 className="text-sm font-bold uppercase tracking-wider text-foreground">Observações do Contrato</h2>
                  </div>
                  <Textarea
                    placeholder="Ex: Prazo de validade da proposta, observações técnicas específicas, etc."
                    value={observations}
                    onChange={(e) => setObservations(e.target.value)}
                    rows={4}
                    className="text-sm resize-none bg-background/50"
                  />
                  <p className="text-[10px] text-muted-foreground">
                    Estas observações serão incluídas no corpo do contrato conforme configurado nas cláusulas.
                  </p>
                </div>


                <div className="p-1">
                  <Button
                    onClick={() => {
                      // Garante que o tipo é contrato antes de chamar a geração
                      setUpsellSubject("contrato");
                      setUpsellOpen(true);

                    }}
                    variant="electric"
                    className="w-full h-12 gap-2 text-sm shadow-lg shadow-primary/20"
                  >
                    <FileDown className="h-4 w-4" /> Gerar Contrato PDF
                  </Button>
                </div>
              </div>
            </TabsContent>
        </Tabs>
        {tab === "budget" && <div className="h-32" />} {/* Espaço só quando o rodapé fixo do orçamento existe */}
      </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 (Simplified Initial Step) */}
      <Dialog open={pdfMenuOpen} onOpenChange={setPdfMenuOpen}>
        <DialogContent
          className="max-w-md p-0 overflow-hidden"
          onOpenAutoFocus={(e) => e.preventDefault()}
        >
          <DialogHeader className="px-5 pt-5 pb-3">
            <DialogTitle className="flex items-center gap-2 text-base">
              <FileDown className="h-5 w-5 text-primary" />
              Exportar PDF
            </DialogTitle>
            <DialogDescription className="text-xs">
              Escolha entre o cupom WhatsApp ou o formato folha A4.
            </DialogDescription>
          </DialogHeader>

          <div className="px-5 pb-5 space-y-4">
            <button
              type="button"
              onClick={() => handlePDF("a4")}
              className="flex w-full items-center gap-4 rounded-2xl border-2 border-border bg-card p-4 text-left transition-all hover:border-primary hover:bg-primary/5 active:scale-[0.99]"
            >
              <div className="flex h-12 w-12 shrink-0 items-center justify-center rounded-xl bg-primary text-primary-foreground shadow-lg">
                <FileText className="h-6 w-6" />
              </div>
              <div className="min-w-0 flex-1">
                <p className="text-sm font-bold text-foreground">Folha A4 (Padrão)</p>
                <p className="text-[11px] leading-tight text-muted-foreground">
                  Documento formal para imprimir ou enviar via e-mail.
                </p>
              </div>
            </button>


            <button
              type="button"
              onClick={() => handlePDF("mobile")}
              className="flex w-full items-center gap-4 rounded-2xl border-2 border-border bg-card p-4 text-left transition-all hover:border-primary hover:bg-primary/5 active:scale-[0.99]"
            >
              <div className="flex h-12 w-12 shrink-0 items-center justify-center rounded-xl bg-slate-900 text-white shadow-lg">
                <Smartphone className="h-6 w-6" />
              </div>
              <div className="min-w-0 flex-1">
                <p className="text-sm font-bold text-foreground">Cupom Mobile (WhatsApp)</p>
                <p className="text-[11px] leading-tight text-muted-foreground">
                  Cupom estreito otimizado para celulares.
                </p>
              </div>
            </button>
          </div>
        </DialogContent>
      </Dialog>

      {/* PDF full preview with variations - Mobile First Design */}
      <Dialog open={pdfPreviewOpen} onOpenChange={setPdfPreviewOpen}>
        <DialogContent
          className="max-w-4xl max-h-[96dvh] p-0 overflow-hidden flex flex-col sm:rounded-2xl border-none sm:border bg-background"
          onOpenAutoFocus={(e) => e.preventDefault()}
        >
          <DialogHeader className="px-4 py-3 border-b bg-background shrink-0 flex flex-row items-center justify-between space-y-0 h-14">
            <div className="flex items-center gap-3">
              <Button 
                variant="ghost" 
                size="icon" 
                className="h-9 w-9 rounded-full hover:bg-muted" 
                onClick={() => {
                  setPdfPreviewOpen(false);
                  if (pdfPreviewDocKind !== "contrato") {
                    setPdfMenuOpen(true);
                  }
                }}
              >
                <ArrowLeft className="h-5 w-5" />
              </Button>
              <div className="flex flex-col">
                <DialogTitle className="text-sm font-black leading-tight tracking-tight">{pdfPreviewTitle}</DialogTitle>
                <span className="text-[10px] font-medium text-muted-foreground uppercase tracking-widest">
                  {pdfPreviewDocKind === "contrato" ? "Contrato de Serviço" : "Orçamento Digital"}
                </span>
              </div>
            </div>
            <div className="flex items-center gap-1">
               {pdfPreview && (
                  <Button 
                    variant="ghost" 
                    size="icon" 
                    className="h-10 w-10 text-primary hover:bg-primary/5 active:scale-90"
                    onClick={async () => {
                      const { downloadPdfResult } = await import("@/features/orcamento/exporters");
                      downloadPdfResult(pdfPreview);
                    }}
                  >
                    <FileDown className="h-5 w-5" />
                  </Button>
               )}
            </div>
          </DialogHeader>

          <div className="flex-1 overflow-hidden flex flex-col bg-muted/40">
            {/* Main Preview Area */}
            <div className="flex-1 min-h-0 overflow-hidden">
              <PdfCanvasPreview
                pdf={pdfPreview}
                mode={pdfPreviewDocKind === "contrato" ? "swipe" : "stack"}
                loadingLabel={pdfPreviewDocKind === "contrato" ? "Renderizando contrato..." : "Renderizando PDF..."}
              />
            </div>

            {/* Layout Picker Bottom Bar (Floating Style) */}
            {!pdfPreview?.filename.includes('mobile') && pdfPreviewDocKind !== "contrato" && (
              <div className="px-3 py-2 bg-background/95 backdrop-blur-sm border-t shrink-0 flex items-center justify-center">
                <div className="flex items-center gap-1.5 p-1 bg-muted/30 rounded-full border border-border/40 overflow-x-auto no-scrollbar">
                  {[
                    { id: 'a4', label: 'Padrão', color: 'bg-primary' },
                    { id: 'corporate', label: 'Corporativo', color: 'bg-[#0D2E5E]' },
                    { id: 'classic', label: 'Executivo', color: 'bg-green-700' },
                    { id: 'mono', label: 'Essencial', color: 'bg-slate-200' },
                    { id: 'modern', label: 'Premium', color: 'bg-blue-600' },
                  ].map((tpl) => {
                    const isActive = pdfPreview && (tpl.id === 'a4' 
                      ? (!pdfPreview.url.includes('classic') && !pdfPreview.url.includes('mono') && !pdfPreview.url.includes('modern')) 
                      : pdfPreview.url.includes(tpl.id));
                    
                    return (
                      <button
                        key={tpl.id}
                        onClick={() => handlePDF(tpl.id as PdfFormat)}
                        className={`flex items-center gap-1.5 px-3 py-1 rounded-full transition-all active:scale-95 shrink-0 ${
                          isActive
                            ? 'bg-background text-primary shadow-sm border border-border/20' 
                            : 'text-muted-foreground hover:text-foreground'
                        }`}
                      >
                        <div className={`h-2 w-2 rounded-full ${tpl.color}`} />
                        <span className="text-[10px] font-black uppercase tracking-tight">
                          {tpl.label}
                        </span>
                      </button>
                    );
                  })}
                </div>
              </div>
            )}

            {/* Action Bar */}
            <div className="p-4 bg-background border-t grid grid-cols-2 gap-3 shrink-0 pb-[max(1rem,env(safe-area-inset-bottom))]">
              <Button 
                onClick={async () => {
                  if (pdfPreview) {
                    const { downloadPdfResult } = await import("@/features/orcamento/exporters");
                    downloadPdfResult(pdfPreview);
                  }
                }}
                disabled={!pdfPreview}
                className="h-12 bg-slate-900 text-white font-black uppercase tracking-widest text-[10px] rounded-xl shadow-lg active:scale-95 transition-all"
              >
                <FileDown className="mr-2 h-4 w-4" /> Baixar PDF
              </Button>
              <Button 
                variant="outline"
                onClick={() => {
                  setPdfPreviewOpen(false);
                  handleWhatsapp();
                }}
                disabled={!pdfPreview}
                className="h-12 border-2 border-success text-success hover:bg-success/5 font-black uppercase tracking-widest text-[10px] rounded-xl active:scale-95 transition-all"
              >
                {pdfPreviewDocKind === "contrato" ? (
                  <Share2 className="mr-2 h-4 w-4" />
                ) : (
                  <MessageCircle className="mr-2 h-4 w-4" />
                )}
                {pdfPreviewDocKind === "contrato" ? "Compartilhar" : "Enviar Whats"}
              </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(/\./g, "").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" });
                    
                  }}
                >
                  <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");
                    
                  }}
                  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!);
                  
                } catch {
                  
                }
              }}
              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);
                          setDiscountValue(b.discountValue ?? 0);
                          setDiscountRaw(b.discountValue ? String(b.discountValue).replace(".", ",") : "");
                          setDiscountType(b.discountType ?? "fixed");
                          setTab("budget");
                          setHistoryOpen(false);
                          
                        }}
                        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);
                            
                          }
                        }}
                        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([]);
                    
                  }
                }}
                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 });
            }
            
          }}
        />
      )}

      <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>

      <Dialog open={materialPickerOpen} onOpenChange={setMaterialPickerOpen}>
        <DialogContent className="flex max-h-[90dvh] flex-col overflow-hidden p-0 sm:max-w-md">
          <DialogHeader className="p-4 pb-2">
            <DialogTitle className="flex items-center gap-2">
              <Package className="h-5 w-5 text-primary" />
              Catálogo de Materiais
            </DialogTitle>
            <DialogDescription>Toque para adicionar itens rapidamente ao orçamento</DialogDescription>
          </DialogHeader>
          <div className="px-4 py-2">
            <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 material…"
                autoFocus
                value={materialSearch}
                onChange={(e) => setMaterialSearch(e.target.value)}
                className="pl-9"
              />
            </div>
          </div>
          <div className="flex-1 overflow-y-auto px-4 pb-4">
            <ul className="space-y-1.5 pt-2">
              {filteredCatalogMaterials.map((m) => (
                <li key={m.id}>
                  <button
                    type="button"
                    onClick={() => handleMaterialClick(m)}
                    className="group flex w-full items-center justify-between rounded-lg border border-border/60 bg-card p-2.5 text-left transition-colors hover:border-primary/40 hover:bg-primary/5 active:bg-primary/10"
                  >
                    <div className="min-w-0 flex-1">
                      <p className="truncate text-sm font-semibold text-foreground">{m.name}</p>
                      <div className="flex items-center gap-1.5 mt-0.5">
                        <span className="inline-flex items-center rounded-md bg-secondary px-1.5 py-0.5 text-[10px] font-medium text-secondary-foreground">
                          {m.unit}
                        </span>
                        {m.defaultQty && (
                          <span className="text-[10px] text-muted-foreground">
                            Padrão: <span className="font-bold text-foreground">{m.defaultQty}</span>
                          </span>
                        )}
                      </div>
                    </div>
                    <div className="ml-3 flex h-8 w-8 items-center justify-center rounded-full bg-primary/10 text-primary transition-colors group-hover:bg-primary group-hover:text-primary-foreground">
                      <Plus className="h-4 w-4" />
                    </div>
                  </button>
                </li>
              ))}
              {filteredCatalogMaterials.length === 0 && (
                <div className="py-8 text-center text-sm text-muted-foreground">
                  Nenhum material encontrado.
                </div>
              )}
            </ul>
          </div>
          <div className="flex items-center justify-between border-t p-4">
            <Button
              variant="ghost"
              size="sm"
              onClick={() => {
                setMaterialPickerOpen(false);
                setTab("materials");
              }}
            >
              Gerenciar catálogo
            </Button>
            <Button variant="outline" size="sm" onClick={() => setMaterialPickerOpen(false)}>
              Fechar
            </Button>
          </div>
        </DialogContent>
      </Dialog>

      {/* Modal de Quantidade de Material */}
      <Dialog open={!!selectedMaterialForQty} onOpenChange={(open) => !open && setSelectedMaterialForQty(null)}>
        <DialogContent className="p-0 sm:max-w-[320px]">
          <DialogHeader className="p-4 pb-2">
            <DialogTitle className="text-base">Quantidade utilizada</DialogTitle>
            <DialogDescription className="text-xs">
              {selectedMaterialForQty?.name}
            </DialogDescription>
          </DialogHeader>
          <div className="px-6 py-4">
            <div className="flex items-center justify-center gap-4">
              <Button
                variant="outline"
                size="icon"
                className="h-12 w-12 rounded-full text-xl"
                onClick={() => setTempMaterialQty(q => {
                  const val = parseFloat(q.replace(",", ".")) || 0;
                  return String(Math.max(1, val - 1)).replace(".", ",");
                })}
              >
                −
              </Button>
              <div className="flex flex-col items-center">
                <Input
                  type="number"
                  inputMode="numeric"
                  autoFocus
                  className="h-16 w-24 text-center text-3xl font-bold"
                  value={tempMaterialQty}
                  onChange={(e) => setTempMaterialQty(e.target.value)}
                  onKeyDown={(e) => {
                    if (e.key === "Enter" && selectedMaterialForQty) {
                      const val = parseFloat(tempMaterialQty.replace(",", ".")) || 0;
                      addMaterialToBudget(selectedMaterialForQty, val);
                    }
                  }}
                />
                <span className="mt-1 text-xs font-medium text-muted-foreground uppercase tracking-wider">
                  {selectedMaterialForQty?.unit}
                </span>
              </div>
              <Button
                variant="outline"
                size="icon"
                className="h-12 w-12 rounded-full text-xl"
                onClick={() => setTempMaterialQty(q => {
                  const val = parseFloat(q.replace(",", ".")) || 0;
                  return String(val + 1).replace(".", ",");
                })}
              >
                +
              </Button>
            </div>
          </div>
          <div className="flex gap-2 p-4 pt-2">
            <Button 
              variant="ghost" 
              className="flex-1"
              onClick={() => setSelectedMaterialForQty(null)}
            >
              Cancelar
            </Button>
            <Button 
              variant="electric" 
              className="flex-1 font-bold"
              onClick={() => {
                if (selectedMaterialForQty) {
                  const val = parseFloat(tempMaterialQty.replace(",", ".")) || 0;
                  addMaterialToBudget(selectedMaterialForQty, val);
                }
              }}
            >
              Adicionar
            </Button>
          </div>
        </DialogContent>
      </Dialog>

      {tab !== "budget" && (
        <footer className="mt-auto border-t border-border/40 bg-card/30 py-6 px-4 mb-[env(safe-area-inset-bottom)]">
          <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>
      )}
      <UpsellModal 
        open={upsellOpen} 
        onOpenChange={setUpsellOpen}
        onAcceptUpgrade={() => {
          const msg = encodeURIComponent(`Olá! Tenho interesse no sistema de ${upsellSubject === "contrato" ? "contratos" : "arquivos"} por R$ 27,90.`);
          window.open(`https://wa.me/5511910620310?text=${msg}`, "_blank");
        }}
        onContinueBasic={() => setUpsellOpen(false)}
        subject={upsellSubject}
      />

      <SignaturePad
        open={cropperOpen}
        onClose={() => {
          setCropperOpen(false);
        }}
        onComplete={(processed) => {
          setCompany((prev) => ({ ...prev, signatureDataUrl: processed }));
          setCropperOpen(false);
          
        }}
      />
      <Dialog open={materialPricePromptOpen} onOpenChange={setMaterialPricePromptOpen}>
        <DialogContent className="max-w-[320px] rounded-2xl p-6">
          <DialogHeader>
            <DialogTitle className="text-base">Preço do Material</DialogTitle>
            <DialogDescription className="text-xs">
              {materialForPricePrompt?.name} não tem preço definido. Deseja informar o valor unitário agora? (Opcional)
            </DialogDescription>
          </DialogHeader>
          <div className="py-4">
            <div className="relative">
              <span className="pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-xs text-muted-foreground font-bold">
                R$
              </span>
              <Input
                inputMode="decimal"
                placeholder="0,00"
                value={promptedMaterialPrice}
                onChange={(e) => setPromptedMaterialPrice(e.target.value)}
                className="h-11 pl-9 text-sm font-semibold"
                autoFocus
                onKeyDown={(e) => {
                  if (e.key === 'Enter') handlePromptedPriceSave();
                }}
              />
            </div>
          </div>
          <div className="flex flex-col gap-2">
            <Button onClick={handlePromptedPriceSave} variant="electric" className="w-full">
              {promptedMaterialPrice ? "Adicionar com preço" : "Adicionar sem preço"}
            </Button>
            <Button onClick={() => setMaterialPricePromptOpen(false)} variant="ghost" className="w-full text-xs">
              Cancelar
            </Button>
          </div>
        </DialogContent>
      </Dialog>
    </div>
  );
};


export default App;

