"use client";

import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import type { LucideIcon } from "lucide-react";
import {
  ArrowLeft,
  ArrowRight,
  Building2,
  CheckCircle2,
  Loader2,
  MapPin,
  MessageCircle,
  Phone,
  Save,
  Sparkles,
} from "lucide-react";
import { motion, AnimatePresence } from "framer-motion";
import { CustomSelect } from "@/components/ui/custom-select";
import { BR_STATES, fetchCities, fetchCnpj, fetchCep } from "@/utils/locations";
import { canCompany, getCompanyContext, resolveCompanyPublicProfileId } from "@/lib/company-context";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import ImageUpload from "@/components/image-upload";
import { getSupabaseClient } from "@/lib/supabase";

type CompanyProfileFormProps = {
  onSaved?: () => void;
  requireComplete?: boolean;
  compact?: boolean;
  submitLabel?: string;
  variant?: "default" | "onboarding";
};

type FormMessage = {
  type: "success" | "error";
  text: string;
};

type OnboardingStep = {
  id: "welcome" | "identity" | "contact" | "address" | "review";
  title: string;
  eyebrow: string;
  description: string;
  icon: LucideIcon;
  label: string;
};

const ONBOARDING_STEPS: OnboardingStep[] = [
  {
    id: "welcome",
    eyebrow: "Primeiro acesso",
    title: "Bem-vindo a Ktalogu",
    description: "Vamos configurar sua empresa em poucos passos.",
    icon: Sparkles,
    label: "Início",
  },
  {
    id: "identity",
    eyebrow: "Dados da empresa",
    title: "Qual o nome da sua empresa?",
    description: "Preencha os dados principais do cadastro.",
    icon: Building2,
    label: "Empresa",
  },
  {
    id: "contact",
    eyebrow: "Contato",
    title: "Como falar com sua empresa?",
    description: "Defina os números principais.",
    icon: Phone,
    label: "Contato",
  },
  {
    id: "address",
    eyebrow: "Endereço",
    title: "Onde sua empresa está localizada?",
    description: "Informe o endereço principal do cadastro.",
    icon: MapPin,
    label: "Endereço",
  },
  {
    id: "review",
    eyebrow: "Revisão final",
    title: "Confira os dados antes de entrar",
    description: "Se estiver tudo certo, finalize para acessar o sistema.",
    icon: CheckCircle2,
    label: "Concluir",
  },
];

function maskCNPJ(value: string) {
  return value
    .replace(/\D/g, "")
    .replace(/^(\d{2})(\d)/, "$1.$2")
    .replace(/^(\d{2})\.(\d{3})(\d)/, "$1.$2.$3")
    .replace(/\.(\d{3})(\d)/, ".$1/$2")
    .replace(/(\d{4})(\d)/, "$1-$2")
    .slice(0, 18);
}

function maskCPF(value: string) {
  return value
    .replace(/\D/g, "")
    .replace(/(\d{3})(\d)/, "$1.$2")
    .replace(/(\d{3})(\d)/, "$1.$2")
    .replace(/(\d{3})(\d{1,2})/, "$1-$2")
    .replace(/(-\d{2})\d+?$/, "$1")
    .slice(0, 14);
}

function maskPhone(value: string) {
  return value
    .replace(/\D/g, "")
    .replace(/^(\d{2})(\d)/, "($1) $2")
    .replace(/(\d)(\d{4})$/, "$1-$2")
    .slice(0, 15);
}

function maskCEP(value: string) {
  return value
    .replace(/\D/g, "")
    .replace(/^(\d{5})(\d)/, "$1-$2")
    .slice(0, 9);
}

function formatDocumentValue(value: string, type: "CNPJ" | "CPF") {
  return type === "CNPJ" ? maskCNPJ(value) : maskCPF(value);
}

function OnboardingDots({ currentStep }: { currentStep: number }) {
  return (
    <div className="flex items-center gap-2">
      {ONBOARDING_STEPS.map((step, index) => (
        <span
          key={step.id}
          className={[
            "h-1.5 rounded-full transition-all duration-300",
            index === currentStep ? "w-8 bg-[var(--ks-color-primary)]" : "w-1.5 bg-[color:rgba(109,40,217,0.22)]",
          ].join(" ")}
        />
      ))}
    </div>
  );
}

function FloatingBackdropOrbs() {
  return (
    <>
      <motion.div
        animate={{ y: [0, -20, 8, 0], x: [0, 18, -10, 0], scale: [1, 1.08, 0.96, 1] }}
        transition={{ duration: 16, repeat: Infinity, ease: "easeInOut" }}
        className="absolute left-[10%] top-[12%] h-52 w-52 rounded-full bg-[color:rgba(109,40,217,0.12)] blur-3xl"
      />
      <motion.div
        animate={{ y: [0, 26, -8, 0], x: [0, -20, 12, 0], scale: [1, 0.94, 1.06, 1] }}
        transition={{ duration: 18, repeat: Infinity, ease: "easeInOut" }}
        className="absolute right-[12%] top-[18%] h-64 w-64 rounded-full bg-[color:rgba(139,92,246,0.1)] blur-3xl"
      />
      <motion.div
        animate={{ y: [0, -16, 12, 0], x: [0, 16, -8, 0], scale: [1, 1.04, 0.98, 1] }}
        transition={{ duration: 15, repeat: Infinity, ease: "easeInOut" }}
        className="absolute bottom-[18%] left-[28%] hidden h-48 w-48 rounded-full bg-[color:rgba(10,192,214,0.07)] blur-3xl md:block"
      />
    </>
  );
}

function OnboardingSuccessScreen() {
  return (
    <motion.div
      initial={{ opacity: 0, scale: 0.96 }}
      animate={{ opacity: 1, scale: 1 }}
      exit={{ opacity: 0, scale: 0.98 }}
      className="flex h-[100svh] items-center justify-center px-6 text-center"
    >
      <div className="w-full max-w-3xl">
        <p className="text-xs font-semibold uppercase tracking-[0.26em] text-[var(--ks-color-primary)]/70">Tudo pronto</p>
        <h2 className="mt-4 text-4xl font-semibold tracking-[-0.06em] text-[var(--ks-color-brand-dark)] sm:text-6xl">
          Ambiente liberado
        </h2>
        <p className="mx-auto mt-5 max-w-xl text-base leading-7 text-slate-600 sm:text-lg">
          Estamos abrindo o sistema com o cadastro inicial da sua empresa.
        </p>
      </div>
    </motion.div>
  );
}

function OnboardingRail({ currentStep }: { currentStep: number }) {
  return (
    <div className="pointer-events-none mt-1 hidden lg:block">
      <div className="relative mx-auto h-16 max-w-5xl">
        <svg className="absolute inset-x-0 top-5 h-8 w-full" viewBox="0 0 1200 120" fill="none" preserveAspectRatio="none">
          <path d="M40 62C174 32 308 32 442 62C576 92 710 92 844 62C978 32 1088 32 1160 54" stroke="rgba(109,40,217,0.22)" strokeWidth="2" strokeLinecap="round" />
        </svg>
        {ONBOARDING_STEPS.map((step, index) => {
          const Icon = step.icon;
          const left = 8 + index * 21.5;
          const active = currentStep === index;
          return (
            <div key={step.id} className="absolute top-5 -translate-x-1/2 -translate-y-1/2" style={{ left: `${left}%` }}>
              <motion.div
                animate={{
                  scale: active ? 1.08 : 1,
                  y: active ? -2 : 0,
                }}
                className={[
                  "flex h-12 w-12 items-center justify-center rounded-full border shadow-[0_12px_30px_rgba(109,40,217,0.12)]",
                  active
                    ? "border-[color:rgba(109,40,217,0.28)] bg-white text-[var(--ks-color-primary)] ring-8 ring-[color:rgba(109,40,217,0.08)]"
                    : "border-[color:rgba(109,40,217,0.14)] bg-white/90 text-[color:rgba(109,40,217,0.68)]",
                ].join(" ")}
              >
                <Icon size={18} />
              </motion.div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

export function CompanyProfileForm({
  onSaved,
  requireComplete = false,
  compact = false,
  submitLabel,
  variant = "default",
}: CompanyProfileFormProps) {
  const isOnboarding = variant === "onboarding";
  const [loading, setLoading] = useState(true);
  const [resolvingLookup, setResolvingLookup] = useState(false);
  const [saving, setSaving] = useState(false);
  /*
    Os dados da empresa moram na linha de `profiles` do dono, nao na do
    usuario logado. Um funcionario tem linha propria e vazia, entao
    consultar por `user.id` devolvia o formulario em branco.
  */
  const [companyProfileId, setCompanyProfileId] = useState<string | null>(null);
  const [canEditCompany, setCanEditCompany] = useState(true);
  const [currentStep, setCurrentStep] = useState(0);
  const [logoUrl, setLogoUrl] = useState("");
  const [storeName, setStoreName] = useState("");
  const [docType, setDocType] = useState<"CNPJ" | "CPF">("CNPJ");
  const [cnpj, setCnpj] = useState("");
  const [phone, setPhone] = useState("");
  const [companyWhatsapp, setCompanyWhatsapp] = useState("");
  const [cep, setCep] = useState("");
  const [street, setStreet] = useState("");
  const [number, setNumber] = useState("");
  const [complement, setComplement] = useState("");
  const [neighborhood, setNeighborhood] = useState("");
  const [city, setCity] = useState("");
  const [state, setState] = useState("");
  const [cities, setCities] = useState<{ value: string; label: string }[]>([]);
  const [message, setMessage] = useState<FormMessage | null>(null);
  const [completionState, setCompletionState] = useState<"idle" | "success">("idle");
  const completionTimerRef = useRef<number | null>(null);

  const cleanDoc = useMemo(() => cnpj.replace(/\D/g, ""), [cnpj]);
  const isValidDocument = useMemo(
    () => (docType === "CNPJ" ? cleanDoc.length === 14 : cleanDoc.length === 11),
    [cleanDoc, docType]
  );

  const loadCities = useCallback(async (uf: string) => {
    const cityList = await fetchCities(uf);
    setCities(cityList);
    return cityList;
  }, []);

  const fetchProfile = useCallback(async () => {
    try {
      const supabase = getSupabaseClient();
      const {
        data: { user },
      } = await supabase.auth.getUser();

      if (!user) return;

      const ctx = await getCompanyContext(supabase, user);
      const profileId = resolveCompanyPublicProfileId(ctx, user.id);
      setCompanyProfileId(profileId);
      setCanEditCompany(canCompany(ctx, user.id, "company.data.write"));

      const { data, error } = await supabase.from("profiles").select("*").eq("id", profileId).single();

      if (error && error.code !== "PGRST116") throw error;

      if (data) {
        setLogoUrl(data.logo_url || "");
        setStoreName(data.store_name || "");

        const document = String(data.cnpj || "");
        const normalizedDocument = document.replace(/\D/g, "");
        if (normalizedDocument.length > 0 && normalizedDocument.length <= 11) {
          setDocType("CPF");
          setCnpj(maskCPF(document));
        } else {
          setDocType("CNPJ");
          setCnpj(maskCNPJ(document));
        }

        setPhone(data.phone || "");
        setCompanyWhatsapp(data.company_whatsapp || "");
        setCep(data.address_zip || "");
        setStreet(data.address_street || "");
        setNumber(data.address_number || "");
        setComplement(data.address_complement || "");
        setNeighborhood(data.address_neighborhood || "");
        setState(data.address_state || "");

        if (data.address_state) {
          await loadCities(data.address_state);
          setCity(data.address_city || "");
        } else {
          setCity(data.address_city || "");
        }
      }
    } catch (error) {
      console.error("Error fetching profile:", error);
      setMessage({ type: "error", text: "Erro ao carregar os dados da empresa." });
    } finally {
      setLoading(false);
    }
  }, [loadCities]);

  useEffect(() => {
    void fetchProfile();
  }, [fetchProfile]);

  useEffect(() => {
    if (!state) return;
    void loadCities(state);
  }, [loadCities, state]);

  useEffect(() => {
    return () => {
      if (completionTimerRef.current) {
        window.clearTimeout(completionTimerRef.current);
      }
    };
  }, []);

  const handleDocBlur = async () => {
    if (docType !== "CNPJ") return;
    if (cleanDoc.length !== 14) return;

    setResolvingLookup(true);
    try {
      const data = await fetchCnpj(cleanDoc);
      if (!data) {
        setMessage({ type: "error", text: "CNPJ não encontrado na base de dados." });
        return;
      }

      setStoreName((current) => data.razao_social || data.nome_fantasia || current);
      const cnpjCep = data.cep ? maskCEP(data.cep) : "";

      if (cnpjCep) setCep(cnpjCep);
      if (data.logradouro) setStreet(data.logradouro);
      if (data.numero) setNumber(data.numero);
      if (data.complemento) setComplement(data.complemento);
      if (data.bairro) setNeighborhood(data.bairro);

      if (data.uf) {
        setState(data.uf);
        const cityList = await fetchCities(data.uf);
        setCities(cityList);
        if (data.municipio) {
          const apiCity = data.municipio.trim().toLowerCase();
          const foundCity = cityList.find((item) => item.value.toLowerCase() === apiCity);
          if (foundCity) {
            setCity(foundCity.value);
          } else {
            const titleCaseCity = data.municipio
              .toLowerCase()
              .split(" ")
              .map((word: string) => word.charAt(0).toUpperCase() + word.slice(1))
              .join(" ");
            setCity(titleCaseCity);
          }
        }
      }

      const primaryPhone = data.ddd_telefone_1 || data.ddd_telefone_2 || "";
      if (primaryPhone) {
        const maskedPhone = maskPhone(primaryPhone);
        setPhone(maskedPhone);
        setCompanyWhatsapp((current) => current || maskedPhone);
      }

      if (cnpjCep.replace(/\D/g, "").length === 8) {
        const cepData = await fetchCep(cnpjCep);
        if (cepData) {
          setStreet((current) => current || cepData.street || "");
          setNeighborhood((current) => current || cepData.neighborhood || "");
          setState((current) => current || cepData.state || "");

          if (cepData.state) {
            const cityList = await fetchCities(cepData.state);
            setCities(cityList);
          }

          setCity((current) => current || cepData.city || "");
        }
      }

      setMessage({ type: "success", text: "CNPJ localizado e cadastro preenchido automaticamente." });
    } finally {
      setResolvingLookup(false);
    }
  };

  const handleCepBlur = async () => {
    const normalizedCep = cep.replace(/\D/g, "");
    if (normalizedCep.length !== 8) return;

    setResolvingLookup(true);
    try {
      const data = await fetchCep(normalizedCep);
      if (!data) return;
      setStreet(data.street);
      setNeighborhood(data.neighborhood);
      setState(data.state);
      await loadCities(data.state);
      setCity(data.city);
      document.getElementById("number")?.focus();
    } finally {
      setResolvingLookup(false);
    }
  };

  const validateIdentity = useCallback(() => {
    if (!storeName.trim()) return "Preencha o nome da empresa.";
    if (!cleanDoc || !isValidDocument) return `Informe um ${docType} válido.`;
    return null;
  }, [cleanDoc, docType, isValidDocument, storeName]);

  const validateContact = useCallback(() => {
    if (!phone.trim()) return "Informe o telefone principal.";
    return null;
  }, [phone]);

  const validateAddress = useCallback(() => {
    if (!cep.trim() || !street.trim() || !number.trim() || !neighborhood.trim() || !city.trim() || !state.trim()) {
      return "Complete o endereço da empresa.";
    }
    return null;
  }, [cep, city, neighborhood, number, state, street]);

  const validateBeforeSave = useCallback(() => {
    if (requireComplete) {
      return validateIdentity() || validateContact() || validateAddress();
    }
    if (cleanDoc && !isValidDocument) return `${docType} inválido.`;
    return null;
  }, [cleanDoc, docType, isValidDocument, requireComplete, validateAddress, validateContact, validateIdentity]);

  const validateCurrentStep = useCallback(() => {
    const step = ONBOARDING_STEPS[currentStep]?.id;
    if (step === "identity") return validateIdentity();
    if (step === "contact") return validateContact();
    if (step === "address") return validateAddress();
    if (step === "review") return validateBeforeSave();
    return null;
  }, [currentStep, validateAddress, validateBeforeSave, validateContact, validateIdentity]);

  const saveProfile = useCallback(async () => {
    const validationError = validateBeforeSave();
    if (validationError) {
      setMessage({ type: "error", text: validationError });
      return false;
    }

    setSaving(true);
    setMessage(null);

    try {
      const supabase = getSupabaseClient();
      const {
        data: { user },
      } = await supabase.auth.getUser();

      if (!user) throw new Error("Usuário não autenticado");

      const updates = {
        // Grava onde leu. Sem isto o funcionario salvaria os dados da empresa
        // na propria linha: o formulario diria "salvo" e nada mudaria.
        id: companyProfileId ?? user.id,
        logo_url: logoUrl,
        store_name: storeName,
        cnpj,
        phone,
        company_whatsapp: companyWhatsapp,
        address_zip: cep,
        address_street: street,
        address_number: number,
        address_complement: complement,
        address_neighborhood: neighborhood,
        address_city: city,
        address_state: state,
        address: `${street}, ${number} - ${neighborhood}, ${city} - ${state}`,
        updated_at: new Date().toISOString(),
      };

      const { error } = await supabase.from("profiles").upsert(updates);
      if (error) throw error;

      setMessage({ type: "success", text: "Dados da empresa salvos com sucesso." });
      if (isOnboarding) {
        setCompletionState("success");
        completionTimerRef.current = window.setTimeout(() => {
          onSaved?.();
        }, 1400);
      } else {
        onSaved?.();
      }
      return true;
    } catch (error) {
      console.error("Error saving profile:", error);
      setMessage({ type: "error", text: "Erro ao salvar os dados da empresa." });
      return false;
    } finally {
      setSaving(false);
    }
  }, [cep, city, cnpj, companyWhatsapp, complement, isOnboarding, neighborhood, number, onSaved, phone, state, storeName, street, validateBeforeSave, logoUrl]);

  const handleNextStep = useCallback(() => {
    const validationError = validateCurrentStep();
    if (validationError) {
      setMessage({ type: "error", text: validationError });
      return;
    }
    setMessage(null);
    setCurrentStep((value) => Math.min(value + 1, ONBOARDING_STEPS.length - 1));
  }, [validateCurrentStep]);

  const handleSubmit = async (event: React.FormEvent) => {
    event.preventDefault();
    if (!isOnboarding) {
      await saveProfile();
      return;
    }

    if (currentStep < ONBOARDING_STEPS.length - 1) {
      handleNextStep();
      return;
    }

    await saveProfile();
  };

  const renderIdentityFields = (centered = false) => (
    <div className={centered ? "grid gap-5" : "grid grid-cols-1 gap-6 md:grid-cols-2"}>
      <div className={centered ? "space-y-3" : "space-y-2 md:col-span-2"}>
        <span className={centered ? "block text-xs font-semibold uppercase tracking-[0.22em] text-slate-500" : "block text-sm font-medium text-[var(--ks-color-text-muted)]"}>
          Logo
        </span>
        <div className={centered ? "flex flex-col items-start gap-4" : "flex flex-col items-start gap-4 sm:flex-row"}>
          <ImageUpload bucket="products" folder="logos" value={logoUrl} onChange={setLogoUrl} className={centered ? "text-[var(--ks-color-brand-dark)]" : ""} />
        </div>
      </div>

      <div className={centered ? "space-y-3" : "space-y-2"}>
        <div className={centered ? "grid gap-4 md:grid-cols-[140px_minmax(0,1fr)] md:items-start" : "flex gap-2"}>
          <div className={centered ? "space-y-3" : "w-24 shrink-0"}>
            <label className={centered ? "block text-sm font-medium text-slate-700" : "mb-1 block text-sm font-medium text-[var(--ks-color-text-primary)]"}>
              Tipo
            </label>
            <CustomSelect
              options={[
                { label: "CNPJ", value: "CNPJ" },
                { label: "CPF", value: "CPF" },
              ]}
              value={docType}
              onChange={(value) => {
                setDocType(value as "CNPJ" | "CPF");
                setCnpj("");
                setMessage(null);
              }}
              className={centered ? "[&_button]:h-14 sm:[&_button]:h-16 [&_button]:rounded-2xl [&_button]:border-slate-200 [&_button]:bg-white [&_button]:px-5 [&_button]:text-base [&_button]:text-[var(--ks-color-brand-dark)] [&_button]:hover:border-[color:rgba(109,40,217,0.25)] [&_button_svg]:text-slate-400 [&_label]:text-slate-700" : undefined}
            />
          </div>
          <div className={centered ? "space-y-3" : "flex-1"}>
            <Input
              id="document"
              label={docType}
              placeholder={docType === "CNPJ" ? "00.000.000/0000-00" : "000.000.000-00"}
              value={cnpj}
              onChange={(event) => setCnpj(formatDocumentValue(event.target.value, docType))}
              onBlur={handleDocBlur}
              maxLength={docType === "CNPJ" ? 18 : 14}
              className={centered ? "!h-14 sm:!h-16 !rounded-2xl !border-slate-200 !bg-white !px-5 !text-base !text-[var(--ks-color-brand-dark)] placeholder:!text-slate-400 focus:!border-[color:rgba(109,40,217,0.25)]" : undefined}
            />
          </div>
        </div>
        <p className={centered ? "text-sm leading-6 text-slate-500 md:pl-[156px]" : "text-xs text-[var(--ks-color-text-soft)]"}>
          {docType === "CNPJ" ? "Ao informar o CNPJ, os dados podem ser preenchidos automaticamente." : "Informe o CPF do titular do cadastro."}
        </p>
      </div>

      <div className={centered ? "space-y-3" : "space-y-2"}>
        <Input
          id="name"
          label="Nome fantasia / razão social"
          placeholder="Ex: Minha Loja Ltda"
          value={storeName}
          onChange={(event) => setStoreName(event.target.value)}
          className={centered ? "!h-14 sm:!h-16 !rounded-2xl !border-slate-200 !bg-white !px-5 !text-base !text-[var(--ks-color-brand-dark)] placeholder:!text-slate-400 focus:!border-[color:rgba(109,40,217,0.25)]" : undefined}
        />
      </div>
    </div>
  );

  const renderContactFields = (centered = false) => (
    <div className={centered ? "grid gap-5 md:grid-cols-2" : "grid grid-cols-1 gap-6 md:grid-cols-2"}>
      <div className={centered ? "space-y-3" : "space-y-2"}>
        <Input
          id="phone"
          label="Telefone principal"
          placeholder="(00) 0000-0000"
          value={phone}
          onChange={(event) => setPhone(maskPhone(event.target.value))}
          maxLength={15}
          icon={<Phone className="h-4 w-4" />}
          className={centered ? "!h-14 sm:!h-16 !rounded-2xl !border-slate-200 !bg-white !px-5 !text-base !text-[var(--ks-color-brand-dark)] placeholder:!text-slate-400 focus:!border-[color:rgba(109,40,217,0.25)]" : undefined}
        />
      </div>
      <div className={centered ? "space-y-3" : "space-y-2"}>
        <Input
          id="whatsapp"
          label="WhatsApp da empresa"
          placeholder="(00) 90000-0000"
          value={companyWhatsapp}
          onChange={(event) => setCompanyWhatsapp(maskPhone(event.target.value))}
          maxLength={15}
          icon={<MessageCircle className="h-4 w-4" />}
          className={centered ? "!h-14 sm:!h-16 !rounded-2xl !border-slate-200 !bg-white !px-5 !text-base !text-[var(--ks-color-brand-dark)] placeholder:!text-slate-400 focus:!border-[color:rgba(109,40,217,0.25)]" : undefined}
        />
      </div>
    </div>
  );

  const renderAddressFields = (centered = false) => (
    <div className={centered ? "grid gap-5 md:grid-cols-6" : "grid grid-cols-1 gap-6 md:grid-cols-6"}>
      <div className={centered ? "space-y-3 md:col-span-2" : "space-y-2 md:col-span-2"}>
        <Input
          id="cep"
          label="CEP"
          placeholder="00000-000"
          value={cep}
          onChange={(event) => setCep(maskCEP(event.target.value))}
          onBlur={handleCepBlur}
          maxLength={9}
          className={centered ? "!h-14 sm:!h-16 !rounded-2xl !border-slate-200 !bg-white !px-5 !text-base !text-[var(--ks-color-brand-dark)] placeholder:!text-slate-400 focus:!border-[color:rgba(109,40,217,0.25)]" : undefined}
        />
      </div>
      <div className={centered ? "space-y-3 md:col-span-4" : "space-y-2 md:col-span-4"}>
        <Input
          id="street"
          label="Logradouro"
          placeholder="Rua, avenida..."
          value={street}
          onChange={(event) => setStreet(event.target.value)}
          className={centered ? "!h-14 sm:!h-16 !rounded-2xl !border-slate-200 !bg-white !px-5 !text-base !text-[var(--ks-color-brand-dark)] placeholder:!text-slate-400 focus:!border-[color:rgba(109,40,217,0.25)]" : undefined}
        />
      </div>
      <div className={centered ? "space-y-3 md:col-span-2" : "space-y-2 md:col-span-2"}>
        <Input
          id="number"
          label="Número"
          placeholder="123"
          value={number}
          onChange={(event) => setNumber(event.target.value)}
          className={centered ? "!h-14 sm:!h-16 !rounded-2xl !border-slate-200 !bg-white !px-5 !text-base !text-[var(--ks-color-brand-dark)] placeholder:!text-slate-400 focus:!border-[color:rgba(109,40,217,0.25)]" : undefined}
        />
      </div>
      <div className={centered ? "space-y-3 md:col-span-2" : "space-y-2 md:col-span-2"}>
        <Input
          id="complement"
          label="Complemento"
          placeholder="Sala, bloco, apto..."
          value={complement}
          onChange={(event) => setComplement(event.target.value)}
          className={centered ? "!h-14 sm:!h-16 !rounded-2xl !border-slate-200 !bg-white !px-5 !text-base !text-[var(--ks-color-brand-dark)] placeholder:!text-slate-400 focus:!border-[color:rgba(109,40,217,0.25)]" : undefined}
        />
      </div>
      <div className={centered ? "space-y-3 md:col-span-2" : "space-y-2 md:col-span-2"}>
        <Input
          id="neighborhood"
          label="Bairro"
          placeholder="Centro"
          value={neighborhood}
          onChange={(event) => setNeighborhood(event.target.value)}
          className={centered ? "!h-14 sm:!h-16 !rounded-2xl !border-slate-200 !bg-white !px-5 !text-base !text-[var(--ks-color-brand-dark)] placeholder:!text-slate-400 focus:!border-[color:rgba(109,40,217,0.25)]" : undefined}
        />
      </div>
      <div className={centered ? "space-y-3 md:col-span-2" : "space-y-2 md:col-span-2"}>
        <CustomSelect
          label="Estado"
          placeholder="UF"
          options={BR_STATES}
          value={state}
          onChange={setState}
          searchable
          className={centered ? "[&_button]:h-14 sm:[&_button]:h-16 [&_button]:rounded-2xl [&_button]:border-slate-200 [&_button]:bg-white [&_button]:px-5 [&_button]:text-base [&_button]:text-[var(--ks-color-brand-dark)] [&_button]:hover:border-[color:rgba(109,40,217,0.25)] [&_button_svg]:text-slate-400 [&_label]:text-slate-700" : undefined}
        />
      </div>
      <div className={centered ? "space-y-3 md:col-span-4" : "space-y-2 md:col-span-4"}>
        <CustomSelect
          label="Cidade"
          placeholder={state ? "Selecione a cidade..." : "Selecione o estado primeiro"}
          options={cities}
          value={city}
          onChange={setCity}
          searchable
          disabled={!state}
          className={centered ? "[&_button]:h-14 sm:[&_button]:h-16 [&_button]:rounded-2xl [&_button]:border-slate-200 [&_button]:bg-white [&_button]:px-5 [&_button]:text-base [&_button]:text-[var(--ks-color-brand-dark)] [&_button]:hover:border-[color:rgba(109,40,217,0.25)] [&_button_svg]:text-slate-400 [&_label]:text-slate-700" : undefined}
        />
      </div>
    </div>
  );

  const renderMessageBanner = (light = false) =>
    message ? (
      <motion.div
        initial={{ opacity: 0, y: 8 }}
        animate={{ opacity: 1, y: 0 }}
        className={[
          light ? "rounded-2xl px-4 py-3 text-sm" : "text-sm",
          message.type === "success"
            ? light
              ? "border border-emerald-200 bg-emerald-50 text-emerald-700"
              : "text-emerald-700"
            : light
              ? "border border-red-200 bg-red-50 text-red-700"
              : "text-rose-600",
        ].join(" ")}
      >
        {message.text}
      </motion.div>
    ) : null;

  const reviewItems = [
    { label: "Empresa", value: storeName || "Não informado" },
    { label: docType, value: cnpj || "Não informado" },
    { label: "Telefone principal", value: phone || "Não informado" },
    { label: "WhatsApp", value: companyWhatsapp || "Não informado" },
    { label: "CEP", value: cep || "Não informado" },
    { label: "Endereço", value: street && number ? `${street}, ${number}` : "Não informado" },
    { label: "Bairro", value: neighborhood || "Não informado" },
    { label: "Cidade / Estado", value: city && state ? `${city} - ${state}` : "Não informado" },
  ];

  if (loading) {
    if (isOnboarding) {
      return (
        <div
          className="relative flex h-[100svh] items-center justify-center overflow-hidden bg-white px-6 text-[var(--ks-color-brand-dark)]"
        >
          <div className="absolute inset-0 bg-[radial-gradient(circle_at_top,rgba(109,40,217,0.08),transparent_46%)]" />
          <FloatingBackdropOrbs />
          <div className="relative z-10 flex flex-col items-center gap-5 text-center">
            <Loader2 className="h-10 w-10 animate-spin" />
            <div>
              <p className="text-xs font-semibold uppercase tracking-[0.28em] text-[var(--ks-color-primary)]/68">Primeiro acesso</p>
              <h2 className="mt-2 text-4xl font-semibold tracking-[-0.04em] md:text-5xl">Preparando sua configuração</h2>
            </div>
          </div>
        </div>
      );
    }

    return (
      <div className="ks-surface flex min-h-[50vh] items-center justify-center">
        <Loader2 className="h-8 w-8 animate-spin text-[var(--ks-color-primary)]" />
      </div>
    );
  }

  if (!isOnboarding) {
    return (
      <motion.form
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        onSubmit={handleSubmit}
        className={compact ? "space-y-6" : "mx-auto max-w-4xl space-y-6 pb-20"}
      >
        <div className="ks-surface p-6">
          <h2 className="mb-4 flex items-center gap-2 text-lg font-semibold text-[var(--ks-color-text-primary)]">
            <Building2 className="h-5 w-5 text-[var(--ks-color-primary)]" />
            Informações cadastrais
          </h2>
          {renderIdentityFields()}
        </div>

        <div className="ks-surface p-6">
          <h2 className="mb-4 flex items-center gap-2 text-lg font-semibold text-[var(--ks-color-text-primary)]">
            <Phone className="h-5 w-5 text-[var(--ks-color-primary)]" />
            Contato
          </h2>
          {renderContactFields()}
        </div>

        <div className="ks-surface p-6">
          <h2 className="mb-4 flex items-center gap-2 text-lg font-semibold text-[var(--ks-color-text-primary)]">
            <MapPin className="h-5 w-5 text-[var(--ks-color-primary)]" />
            Endereço completo
          </h2>
          {renderAddressFields()}
        </div>

        <div className="flex items-center justify-between gap-4 pt-4">
          <div className="min-h-[52px] flex-1">
            {canEditCompany ? (
              renderMessageBanner(true)
            ) : (
              <p className="text-sm text-[var(--ks-color-text-muted)]">
                Somente quem tem permissao para configuracoes da empresa pode alterar estes dados.
              </p>
            )}
          </div>
          <Button
            type="submit"
            disabled={saving || resolvingLookup || !canEditCompany}
            icon={saving ? <Loader2 className="h-4 w-4 animate-spin" /> : <Save className="h-4 w-4" />}
          >
            {saving ? "Salvando..." : submitLabel ?? "Salvar alterações"}
          </Button>
        </div>
      </motion.form>
    );
  }

  const activeStep = ONBOARDING_STEPS[currentStep];

  if (completionState === "success") {
    return (
      <div className="relative h-[100svh] overflow-hidden text-white">
        <div className="absolute inset-0 bg-white" />
        <FloatingBackdropOrbs />
        <OnboardingSuccessScreen />
      </div>
    );
  }

  return (
    <form onSubmit={handleSubmit} className="relative h-[100svh] overflow-y-auto overflow-x-hidden text-white md:overflow-hidden">
      <div className="absolute inset-0 bg-white" />
      <div className="absolute inset-0 bg-[radial-gradient(circle_at_top,rgba(109,40,217,0.08),transparent_46%)]" />
      <div className="absolute inset-x-0 bottom-0 h-[42svh] bg-white md:hidden" />
      <FloatingBackdropOrbs />

      <div className="relative z-10 flex min-h-[100svh] flex-col px-5 py-4 sm:px-8 sm:py-6 lg:h-[100svh] lg:overflow-hidden lg:px-14">
        <div className="flex items-center justify-end gap-3 sm:gap-4">
            <OnboardingDots currentStep={currentStep} />
            <span className="text-xs font-semibold uppercase tracking-[0.2em] text-slate-400">
              {String(currentStep + 1).padStart(2, "0")} / {String(ONBOARDING_STEPS.length).padStart(2, "0")}
            </span>
        </div>

        <div className="relative z-10 flex flex-1 items-start justify-center py-6 sm:py-8 lg:min-h-0 lg:items-center lg:py-1">
          <div className="mx-auto flex w-full max-w-4xl flex-col items-center text-center lg:min-h-0">
            <AnimatePresence mode="wait">
              <motion.div
                key={activeStep.id}
                initial={{ opacity: 0, y: 18 }}
                animate={{ opacity: 1, y: 0 }}
                exit={{ opacity: 0, y: -18 }}
                transition={{ duration: 0.24, ease: "easeOut" }}
                className="flex w-full flex-col justify-start lg:min-h-0 lg:flex-1 lg:justify-center"
              >
                <h1 className="mx-auto max-w-[10ch] text-[clamp(2.1rem,13vw,4.25rem)] font-semibold leading-[0.92] tracking-[-0.07em] text-[var(--ks-color-brand-dark)] sm:max-w-[12ch]">
                  {activeStep.title}
                </h1>

                {resolvingLookup ? (
                  <div className="mt-4 inline-flex items-center gap-2 text-sm text-slate-500">
                    <Loader2 className="h-4 w-4 animate-spin" />
                    Buscando dados automaticamente...
                  </div>
                ) : null}

                <div className="mx-auto mt-5 w-full max-w-3xl text-left sm:mt-6">
                  {activeStep.id === "welcome" ? (
                    <div className="h-8" />
                  ) : null}

                  {activeStep.id === "identity" ? renderIdentityFields(true) : null}
                  {activeStep.id === "contact" ? renderContactFields(true) : null}
                  {activeStep.id === "address" ? renderAddressFields(true) : null}
                  {activeStep.id === "review" ? (
                    <div className="grid gap-4 md:grid-cols-2">
                      {reviewItems.map((item) => (
                        <div key={item.label} className="border-b border-slate-200 pb-3">
                          <p className="text-xs font-semibold uppercase tracking-[0.16em] text-slate-400">{item.label}</p>
                          <p className="mt-2 text-lg font-medium tracking-[-0.03em] text-[var(--ks-color-brand-dark)]">{item.value}</p>
                        </div>
                      ))}
                    </div>
                  ) : null}
                </div>

                <div className="mx-auto mt-6 flex w-full max-w-3xl flex-col items-center gap-3 pb-6 sm:pb-8 lg:pb-0">
                  {renderMessageBanner(false)}
                  <div className="flex w-full max-w-xl flex-col gap-4 sm:flex-row sm:items-center sm:justify-center">
                    {currentStep > 0 ? (
                      <button
                        type="button"
                        onClick={() => {
                          setMessage(null);
                          setCurrentStep((value) => Math.max(0, value - 1));
                        }}
                        disabled={saving}
                        className="inline-flex h-14 items-center justify-center gap-2 rounded-2xl border border-slate-200 bg-white px-8 text-base font-semibold text-slate-700 transition hover:border-[color:rgba(109,40,217,0.22)] hover:text-[var(--ks-color-primary)] disabled:cursor-not-allowed disabled:opacity-40 sm:min-w-[180px]"
                      >
                        <ArrowLeft className="h-4 w-4" />
                        Voltar
                      </button>
                    ) : null}

                    <button
                      type="submit"
                      disabled={saving || resolvingLookup}
                      className="inline-flex h-14 items-center justify-center gap-3 rounded-2xl bg-[var(--ks-color-primary)] px-10 text-base font-semibold tracking-[-0.02em] text-white shadow-[0_16px_34px_rgba(109,40,217,0.2)] transition hover:brightness-110 disabled:cursor-not-allowed disabled:opacity-60 sm:min-w-[280px]"
                    >
                      {saving ? <Loader2 className="h-5 w-5 animate-spin" /> : currentStep === ONBOARDING_STEPS.length - 1 ? <Save className="h-5 w-5" /> : <ArrowRight className="h-5 w-5" />}
                      {saving
                        ? "Salvando..."
                        : currentStep === ONBOARDING_STEPS.length - 1
                          ? submitLabel ?? "Salvar e entrar"
                          : "Continuar"}
                    </button>
                  </div>
                </div>
              </motion.div>
            </AnimatePresence>
          </div>
        </div>

        <div className="flex-shrink-0">
          <OnboardingRail currentStep={currentStep} />
        </div>
      </div>
    </form>
  );
}
