"use client";

import { useEffect, useMemo, useRef, useState } from "react";
import { useParams } from "next/navigation";
import Image from "next/image";
import { CheckCircle, ChevronDown, Loader2 } from "lucide-react";
import { getSupabaseClient } from "@/lib/supabase";

type ProfileInfo = {
  id: string;
  slug: string | null;
  catalog_name: string | null;
  store_name: string | null;
  catalog_logo_url: string | null;
  logo_url: string | null;
  primary_color: string | null;
  whatsapp: string | null;
  phone: string | null;
  company_whatsapp: string | null;
  company_phone: string | null;
};

type FormState = {
  name: string;
  company_name: string;
  type: "pf" | "pj";
  document: string;
  email: string;
  phone: string;
  whatsapp: string;
  address_zip: string;
  address_street: string;
  address_number: string;
  address_complement: string;
  address_neighborhood: string;
  address_city: string;
  address_state: string;
  notes: string;
  tags: string;
};

const initialForm: FormState = {
  name: "",
  company_name: "",
  type: "pf",
  document: "",
  email: "",
  phone: "",
  whatsapp: "",
  address_zip: "",
  address_street: "",
  address_number: "",
  address_complement: "",
  address_neighborhood: "",
  address_city: "",
  address_state: "",
  notes: "",
  tags: "",
};

const onlyDigits = (value: string) => value.replace(/\D/g, "");

const parseTags = (value: string) =>
  value
    .split(",")
    .map((tag) => tag.trim())
    .filter(Boolean);

const maskCPF = (value: string) => {
  return value
    .replace(/\D/g, "")
    .replace(/^(\d{3})(\d)/, "$1.$2")
    .replace(/^(\d{3})\.(\d{3})(\d)/, "$1.$2.$3")
    .replace(/\.(\d{3})(\d)/, ".$1-$2")
    .slice(0, 14);
};

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

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

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

const isValidCPF = (value: string) => {
  const cpf = onlyDigits(value);
  if (cpf.length !== 11) return false;
  if (/^(\d)\1+$/.test(cpf)) return false;
  let sum = 0;
  for (let i = 0; i < 9; i += 1) {
    sum += parseInt(cpf.charAt(i), 10) * (10 - i);
  }
  let check = (sum * 10) % 11;
  if (check === 10 || check === 11) check = 0;
  if (check !== parseInt(cpf.charAt(9), 10)) return false;
  sum = 0;
  for (let i = 0; i < 10; i += 1) {
    sum += parseInt(cpf.charAt(i), 10) * (11 - i);
  }
  check = (sum * 10) % 11;
  if (check === 10 || check === 11) check = 0;
  return check === parseInt(cpf.charAt(10), 10);
};

const isValidCNPJ = (value: string) => {
  const cnpj = onlyDigits(value);
  if (cnpj.length !== 14) return false;
  if (/^(\d)\1+$/.test(cnpj)) return false;
  const weights1 = [5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2];
  const weights2 = [6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2];
  let sum = 0;
  for (let i = 0; i < 12; i += 1) {
    sum += parseInt(cnpj.charAt(i), 10) * weights1[i];
  }
  let check = sum % 11;
  check = check < 2 ? 0 : 11 - check;
  if (check !== parseInt(cnpj.charAt(12), 10)) return false;
  sum = 0;
  for (let i = 0; i < 13; i += 1) {
    sum += parseInt(cnpj.charAt(i), 10) * weights2[i];
  }
  check = sum % 11;
  check = check < 2 ? 0 : 11 - check;
  return check === parseInt(cnpj.charAt(13), 10);
};

const maskDocument = (value: string, type: "pf" | "pj") => {
  return type === "pj" ? maskCNPJ(value) : maskCPF(value);
};

type CnpjResponse = {
  razao_social?: string | null;
  nome_fantasia?: string | null;
  cep?: string | null;
  logradouro?: string | null;
  numero?: string | null;
  complemento?: string | null;
  bairro?: string | null;
  municipio?: string | null;
  uf?: string | null;
};

type CepResponse = {
  cep?: string | null;
  street?: string | null;
  neighborhood?: string | null;
  city?: string | null;
  state?: string | null;
};

type CityResponse = {
  nome: string;
};

type SelectOption = {
  value: string;
  label: string;
};

const BRAZIL_STATES = [
  { value: "AC", label: "Acre" },
  { value: "AL", label: "Alagoas" },
  { value: "AP", label: "Amapá" },
  { value: "AM", label: "Amazonas" },
  { value: "BA", label: "Bahia" },
  { value: "CE", label: "Ceará" },
  { value: "DF", label: "Distrito Federal" },
  { value: "ES", label: "Espírito Santo" },
  { value: "GO", label: "Goiás" },
  { value: "MA", label: "Maranhão" },
  { value: "MT", label: "Mato Grosso" },
  { value: "MS", label: "Mato Grosso do Sul" },
  { value: "MG", label: "Minas Gerais" },
  { value: "PA", label: "Pará" },
  { value: "PB", label: "Paraíba" },
  { value: "PR", label: "Paraná" },
  { value: "PE", label: "Pernambuco" },
  { value: "PI", label: "Piauí" },
  { value: "RJ", label: "Rio de Janeiro" },
  { value: "RN", label: "Rio Grande do Norte" },
  { value: "RS", label: "Rio Grande do Sul" },
  { value: "RO", label: "Rondônia" },
  { value: "RR", label: "Roraima" },
  { value: "SC", label: "Santa Catarina" },
  { value: "SP", label: "São Paulo" },
  { value: "SE", label: "Sergipe" },
  { value: "TO", label: "Tocantins" },
];

const CLIENT_TYPE_OPTIONS: SelectOption[] = [
  { value: "pf", label: "Pessoa Física" },
  { value: "pj", label: "Pessoa Jurídica" },
];

const normalizeText = (value: string) =>
  value
    .normalize("NFD")
    .replace(/\p{Diacritic}/gu, "")
    .toLowerCase()
    .trim();

function SimpleSelect({
  value,
  onChange,
  options,
  placeholder = "Selecione",
  disabled = false,
  className = "",
}: {
  value: string;
  onChange: (value: string) => void;
  options: SelectOption[];
  placeholder?: string;
  disabled?: boolean;
  className?: string;
}) {
  const [isOpen, setIsOpen] = useState(false);
  const containerRef = useRef<HTMLDivElement | null>(null);

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (containerRef.current && !containerRef.current.contains(event.target as Node)) {
        setIsOpen(false);
      }
    };
    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, []);

  const selectedOption = options.find((opt) => opt.value === value);

  return (
    <div className={`relative ${className}`} ref={containerRef}>
      <button
        type="button"
        disabled={disabled}
        onClick={() => {
          if (disabled) return;
          setIsOpen((prev) => !prev);
        }}
        className="w-full appearance-none px-3.5 py-2.5 rounded-full border border-[var(--ks-color-border-subtle)] text-sm outline-none bg-[var(--ks-color-bg-elevated)] text-[var(--ks-color-text-primary)] focus:ring-2 focus:ring-[var(--ks-color-primary)]/20 focus:border-[var(--ks-color-primary)] disabled:opacity-60 disabled:cursor-not-allowed flex items-center justify-between gap-3"
      >
        <span className={selectedOption ? "text-[var(--ks-color-text-primary)]" : "text-[var(--ks-color-text-soft)]"}>
          {selectedOption?.label || placeholder}
        </span>
        <ChevronDown
          className={`h-4 w-4 text-[var(--ks-color-text-soft)] transition-transform ${isOpen ? "rotate-180" : ""}`}
        />
      </button>
      {isOpen && (
        <div className="absolute left-0 right-0 z-30 mt-2 max-h-64 overflow-auto rounded-2xl border border-[var(--ks-color-border-subtle)] bg-white shadow-lg">
          {options.length === 0 ? (
            <div className="px-3.5 py-2.5 text-sm text-[var(--ks-color-text-soft)]">Nenhuma opção</div>
          ) : (
            options.map((opt) => (
              <button
                key={opt.value}
                type="button"
                onClick={() => {
                  onChange(opt.value);
                  setIsOpen(false);
                }}
                className={`w-full text-left px-3.5 py-2.5 text-sm transition-colors ${
                  opt.value === value
                    ? "bg-[var(--ks-color-primary-soft)] text-[var(--ks-color-text-primary)]"
                    : "text-[var(--ks-color-text-primary)] hover:bg-[var(--ks-color-bg-soft)]"
                }`}
              >
                {opt.label}
              </button>
            ))
          )}
        </div>
      )}
    </div>
  );
}

export default function PublicClientRegistrationPage() {
  const params = useParams<{ slug: string }>();
  const slug = params?.slug;
  const [profile, setProfile] = useState<ProfileInfo | null>(null);
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [form, setForm] = useState<FormState>(initialForm);
  const [error, setError] = useState("");
  const [success, setSuccess] = useState(false);
  const [loadingCnpj, setLoadingCnpj] = useState(false);
  const [loadingCep, setLoadingCep] = useState(false);
  const [cities, setCities] = useState<string[]>([]);
  const [loadingCities, setLoadingCities] = useState(false);
  const [pendingCity, setPendingCity] = useState("");

  useEffect(() => {
    let active = true;
    async function fetchProfile() {
      if (!slug) return;
      setLoading(true);
      setError("");
      try {
        const supabase = getSupabaseClient();
        const { data, error } = await supabase
          .from("profiles")
          .select(
            "id,slug,catalog_name,store_name,catalog_logo_url,logo_url,primary_color,whatsapp,phone,company_whatsapp,company_phone"
          )
          .eq("slug", slug)
          .single();
        if (!active) return;
        if (error) throw error;
        setProfile(data as ProfileInfo);
      } catch {
        if (!active) return;
        setProfile(null);
        setError("Não foi possível carregar os dados da loja.");
      } finally {
        if (active) setLoading(false);
      }
    }
    fetchProfile();
    return () => {
      active = false;
    };
  }, [slug]);

  useEffect(() => {
    const state = form.address_state;
    if (!state) {
      setCities([]);
      return;
    }
    const controller = new AbortController();
    let active = true;
    async function fetchCities() {
      setLoadingCities(true);
      try {
        const response = await fetch(
          `https://brasilapi.com.br/api/ibge/municipios/v1/${state}?providers=dados-abertos-br,gov,wikipedia`,
          { signal: controller.signal }
        );
        if (!response.ok) throw new Error("Falha ao carregar cidades");
        const data = (await response.json()) as CityResponse[];
        if (!active) return;
        let list = Array.isArray(data) ? data.map((city) => city.nome).filter(Boolean) : [];
        if (pendingCity) {
          const normalizedPending = normalizeText(pendingCity);
          const match = list.find((city) => normalizeText(city) === normalizedPending);
          const resolvedCity = match || pendingCity;
          if (resolvedCity && !list.includes(resolvedCity)) {
            list = [resolvedCity, ...list];
          }
          setForm((prev) => (prev.address_city === resolvedCity ? prev : { ...prev, address_city: resolvedCity }));
          setPendingCity("");
        }
        setCities(list);
      } catch {
        if (!active) return;
        setCities([]);
      } finally {
        if (active) setLoadingCities(false);
      }
    }
    fetchCities();
    return () => {
      active = false;
      controller.abort();
    };
  }, [form.address_state, pendingCity]);

  const storeName = useMemo(() => {
    return profile?.catalog_name || profile?.store_name || "Loja";
  }, [profile]);

  const logoUrl = profile?.catalog_logo_url || profile?.logo_url || "";
  function updateField<K extends keyof FormState>(key: K, value: FormState[K]) {
    setForm((prev) => ({ ...prev, [key]: value }));
  }

  async function fetchCnpjData(value: string) {
    const clean = onlyDigits(value);
    if (clean.length !== 14) return;
    setLoadingCnpj(true);
    try {
      const response = await fetch(`https://brasilapi.com.br/api/cnpj/v1/${clean}`);
      if (!response.ok) throw new Error("CNPJ inválido");
      const data = (await response.json()) as CnpjResponse;
      setForm((prev) => ({
        ...prev,
        company_name: data.razao_social || data.nome_fantasia || prev.company_name,
        address_zip: data.cep ? maskCEP(data.cep) : prev.address_zip,
        address_street: data.logradouro || prev.address_street,
        address_number: data.numero || prev.address_number,
        address_complement: data.complemento || prev.address_complement,
        address_neighborhood: data.bairro || prev.address_neighborhood,
        address_state: data.uf || prev.address_state,
      }));
      if (data.municipio) setPendingCity(data.municipio);
    } finally {
      setLoadingCnpj(false);
    }
  }

  async function fetchCepData(value: string) {
    const clean = onlyDigits(value);
    if (clean.length !== 8) return;
    setLoadingCep(true);
    try {
      const response = await fetch(`https://brasilapi.com.br/api/cep/v1/${clean}`);
      if (!response.ok) throw new Error("CEP inválido");
      const data = (await response.json()) as CepResponse;
      setForm((prev) => ({
        ...prev,
        address_zip: data.cep ? maskCEP(data.cep) : prev.address_zip,
        address_street: data.street || prev.address_street,
        address_neighborhood: data.neighborhood || prev.address_neighborhood,
        address_state: data.state || prev.address_state,
      }));
      if (data.city) setPendingCity(data.city);
    } finally {
      setLoadingCep(false);
    }
  }

  async function handleDocumentBlur() {
    if (form.type !== "pj") return;
    const cleanDocument = onlyDigits(form.document);
    if (!cleanDocument) return;
    if (!isValidCNPJ(cleanDocument)) {
      setError("CNPJ inválido.");
      return;
    }
    await fetchCnpjData(cleanDocument);
  }

  async function handleCepBlur() {
    const cleanCep = onlyDigits(form.address_zip);
    if (cleanCep && cleanCep.length !== 8) {
      setError("CEP inválido.");
      return;
    }
    await fetchCepData(form.address_zip);
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (!slug) return;
    setError("");
    if (!form.name.trim()) {
      setError("Nome do cliente é obrigatório.");
      return;
    }
    const cleanDocument = onlyDigits(form.document);
    if (cleanDocument) {
      if (form.type === "pf" && !isValidCPF(cleanDocument)) {
        setError("CPF inválido.");
        return;
      }
      if (form.type === "pj" && !isValidCNPJ(cleanDocument)) {
        setError("CNPJ inválido.");
        return;
      }
    }
    const cleanCep = onlyDigits(form.address_zip);
    if (cleanCep && cleanCep.length !== 8) {
      setError("CEP inválido.");
      return;
    }
    setSubmitting(true);
    try {
      const supabase = getSupabaseClient();
      const { data, error } = await supabase.rpc("create_public_client", {
        p_slug: slug,
        p_name: form.name,
        p_company_name: form.company_name,
        p_type: form.type,
        p_document: form.document,
        p_email: form.email,
        p_phone: form.phone,
        p_whatsapp: form.whatsapp,
        p_address_zip: form.address_zip,
        p_address_street: form.address_street,
        p_address_number: form.address_number,
        p_address_complement: form.address_complement,
        p_address_neighborhood: form.address_neighborhood,
        p_address_city: form.address_city,
        p_address_state: form.address_state,
        p_notes: form.notes,
        p_tags: parseTags(form.tags),
      });
      if (error && error.code === "PGRST202") {
        throw new Error(
          "Função de cadastro público não está disponível. Execute o SQL apps/admin/update_schema.sql no Supabase."
        );
      }
      if (error) throw error;
      if (!data?.id) {
        throw new Error("Não foi possível finalizar o cadastro.");
      }
      setSuccess(true);
      setForm(initialForm);
    } catch (err) {
      const message =
        typeof err === "object" && err && "message" in err && typeof err.message === "string"
          ? err.message
          : "Não foi possível enviar o cadastro.";
      setError(message);
    } finally {
      setSubmitting(false);
    }
  }

  return (
    <div className="min-h-screen bg-[var(--ks-color-bg-body)]">
      <div className="max-w-3xl mx-auto px-4 py-10">
        <div className="mb-8 flex flex-col items-center text-center">
          {logoUrl ? (
            <Image
              src={logoUrl}
              alt={storeName}
              className="h-24 w-auto object-contain"
              width={120}
              height={96}
              unoptimized
            />
          ) : (
            <div className="text-sm font-semibold text-[var(--ks-color-text-muted)]">Sem logo</div>
          )}
          <h1 className="mt-3 text-2xl font-bold text-[var(--ks-color-text-primary)]">{storeName}</h1>
        </div>

        <div className="rounded-2xl border border-[var(--ks-color-border-subtle)] bg-[var(--ks-color-bg-elevated)] shadow-sm p-6">
          <div className="mb-6 border-b border-[var(--ks-color-border-subtle)] pb-4">
            <div className="text-lg font-semibold text-[var(--ks-color-text-primary)]">Cadastro de cliente</div>
          </div>
          {loading ? (
            <div className="flex items-center justify-center py-12 text-[var(--ks-color-text-muted)]">
              <Loader2 className="h-6 w-6 animate-spin" />
            </div>
          ) : !profile ? (
            <div className="space-y-3 text-center">
              <div className="text-base font-semibold text-[var(--ks-color-text-primary)]">Loja não encontrada</div>
              <div className="text-sm text-[var(--ks-color-text-muted)]">
                Verifique o link enviado e tente novamente.
              </div>
            </div>
          ) : success ? (
            <div className="space-y-4 text-center">
              <div className="inline-flex items-center justify-center h-12 w-12 rounded-full bg-[var(--ks-color-success-light)] text-[var(--ks-color-success)] mx-auto">
                <CheckCircle className="h-6 w-6" />
              </div>
              <div className="text-lg font-semibold text-[var(--ks-color-text-primary)]">Cadastro enviado com sucesso</div>
              <div className="text-sm text-[var(--ks-color-text-muted)]">
                Obrigado! Seus dados já foram enviados para a loja.
              </div>
              <div>
                <button
                  type="button"
                  onClick={() => setSuccess(false)}
                  className="inline-flex items-center justify-center rounded-xl border border-[var(--ks-color-border-subtle)] px-4 py-2 text-sm font-semibold text-[var(--ks-color-text-primary)] hover:bg-[var(--ks-color-bg-soft)]"
                >
                  Enviar outro cadastro
                </button>
              </div>
            </div>
          ) : (
            <form onSubmit={handleSubmit} className="space-y-6">
              {error && (
                <div className="rounded-xl border border-[var(--ks-color-status-danger)]/20 bg-[var(--ks-color-status-danger)]/10 px-4 py-3 text-sm text-[var(--ks-color-status-danger)]">
                  {error}
                </div>
              )}

              <div className="space-y-4">
                <div className="space-y-1.5">
                  <label className="text-xs font-medium text-[var(--ks-color-text-soft)] uppercase tracking-[0.16em]">
                    Documento (CPF/CNPJ) (opcional)
                  </label>
                  <div className="grid grid-cols-1 sm:grid-cols-[minmax(0,1.3fr)_minmax(0,1fr)] gap-4">
                    <input
                      value={form.document}
                      onChange={(e) => {
                        setError("");
                        updateField("document", maskDocument(e.target.value, form.type));
                      }}
                      onBlur={handleDocumentBlur}
                      className="w-full px-3.5 py-2.5 rounded-full border border-[rgba(198,203,224,0.9)] text-sm outline-none bg-white focus:ring-2 focus:ring-[rgba(10,192,214,0.16)] focus:border-[rgba(10,192,214,0.9)]"
                      placeholder={form.type === "pj" ? "00.000.000/0000-00" : "000.000.000-00"}
                      maxLength={form.type === "pj" ? 18 : 14}
                    />
                    <SimpleSelect
                      value={form.type}
                      options={CLIENT_TYPE_OPTIONS}
                      onChange={(value) =>
                        setForm((prev) => {
                          const nextType = value === "pj" ? "pj" : "pf";
                          return {
                            ...prev,
                            type: nextType,
                            document: maskDocument(prev.document, nextType),
                          };
                        })
                      }
                    />
                  </div>
                  {loadingCnpj && (
                    <div className="text-xs text-[var(--ks-color-text-soft)]">
                      Buscando dados do CNPJ...
                    </div>
                  )}
                </div>

                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                  <div className="space-y-1.5">
                    <label className="text-xs font-medium text-[var(--ks-color-text-soft)] uppercase tracking-[0.16em]">
                      Nome do contato
                    </label>
                    <input
                      value={form.name}
                      onChange={(e) => updateField("name", e.target.value)}
                      className="w-full px-3.5 py-2.5 rounded-full border border-[rgba(198,203,224,0.9)] text-sm outline-none bg-white focus:ring-2 focus:ring-[rgba(10,192,214,0.16)] focus:border-[rgba(10,192,214,0.9)]"
                      placeholder="Ex: João Silva"
                      required
                    />
                  </div>
                  <div className="space-y-1.5">
                    <label className="text-xs font-medium text-[var(--ks-color-text-soft)] uppercase tracking-[0.16em]">
                      Empresa (opcional)
                    </label>
                    <input
                      value={form.company_name}
                      onChange={(e) => updateField("company_name", e.target.value)}
                      className="w-full px-3.5 py-2.5 rounded-full border border-[rgba(198,203,224,0.9)] text-sm outline-none bg-white focus:ring-2 focus:ring-[rgba(10,192,214,0.16)] focus:border-[rgba(10,192,214,0.9)]"
                      placeholder="Ex: Agência Criativa"
                    />
                  </div>
                </div>
              </div>

              <div className="space-y-4">
                <div className="text-sm font-semibold text-[var(--ks-color-text-primary)]">Contato</div>
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                  <div className="space-y-1.5">
                    <label className="text-xs font-medium text-[var(--ks-color-text-soft)] uppercase tracking-[0.16em]">
                      Email
                    </label>
                    <input
                      value={form.email}
                      onChange={(e) => updateField("email", e.target.value)}
                      className="w-full px-3.5 py-2.5 rounded-full border border-[rgba(198,203,224,0.9)] text-sm outline-none bg-white focus:ring-2 focus:ring-[rgba(10,192,214,0.16)] focus:border-[rgba(10,192,214,0.9)]"
                      placeholder="nome@email.com"
                      type="email"
                    />
                  </div>
                  <div className="space-y-1.5">
                    <label className="text-xs font-medium text-[var(--ks-color-text-soft)] uppercase tracking-[0.16em]">
                      Telefone
                    </label>
                    <input
                      value={form.phone}
                      onChange={(e) => updateField("phone", maskPhone(e.target.value))}
                      className="w-full px-3.5 py-2.5 rounded-full border border-[rgba(198,203,224,0.9)] text-sm outline-none bg-white focus:ring-2 focus:ring-[rgba(10,192,214,0.16)] focus:border-[rgba(10,192,214,0.9)]"
                      placeholder="(11) 99999-9999"
                      maxLength={15}
                    />
                  </div>
                  <div className="space-y-1.5">
                    <label className="text-xs font-medium text-[var(--ks-color-text-soft)] uppercase tracking-[0.16em]">
                      WhatsApp
                    </label>
                    <input
                      value={form.whatsapp}
                      onChange={(e) => updateField("whatsapp", maskPhone(e.target.value))}
                      className="w-full px-3.5 py-2.5 rounded-full border border-[rgba(198,203,224,0.9)] text-sm outline-none bg-white focus:ring-2 focus:ring-[rgba(10,192,214,0.16)] focus:border-[rgba(10,192,214,0.9)]"
                      placeholder="(11) 99999-9999"
                      maxLength={15}
                    />
                  </div>
                </div>
              </div>

              <div className="space-y-4">
                <div className="text-sm font-semibold text-[var(--ks-color-text-primary)]">Endereço</div>
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                  <div className="space-y-1.5">
                    <label className="text-xs font-medium text-[var(--ks-color-text-soft)] uppercase tracking-[0.16em]">
                      CEP
                    </label>
                    <input
                      value={form.address_zip}
                      onChange={(e) => updateField("address_zip", maskCEP(e.target.value))}
                      onBlur={handleCepBlur}
                      className="w-full px-3.5 py-2.5 rounded-full border border-[rgba(198,203,224,0.9)] text-sm outline-none bg-white focus:ring-2 focus:ring-[rgba(10,192,214,0.16)] focus:border-[rgba(10,192,214,0.9)]"
                      placeholder="00000-000"
                      maxLength={9}
                    />
                  </div>
                  <div className="space-y-1.5">
                    <label className="text-xs font-medium text-[var(--ks-color-text-soft)] uppercase tracking-[0.16em]">
                      Rua
                    </label>
                    <input
                      value={form.address_street}
                      onChange={(e) => updateField("address_street", e.target.value)}
                      className="w-full px-3.5 py-2.5 rounded-full border border-[rgba(198,203,224,0.9)] text-sm outline-none bg-white focus:ring-2 focus:ring-[rgba(10,192,214,0.16)] focus:border-[rgba(10,192,214,0.9)]"
                      placeholder="Rua, avenida, etc."
                    />
                  </div>
                  <div className="space-y-1.5">
                    <label className="text-xs font-medium text-[var(--ks-color-text-soft)] uppercase tracking-[0.16em]">
                      Número
                    </label>
                    <input
                      value={form.address_number}
                      onChange={(e) => updateField("address_number", e.target.value)}
                      className="w-full px-3.5 py-2.5 rounded-full border border-[rgba(198,203,224,0.9)] text-sm outline-none bg-white focus:ring-2 focus:ring-[rgba(10,192,214,0.16)] focus:border-[rgba(10,192,214,0.9)]"
                      placeholder="123"
                    />
                  </div>
                  <div className="space-y-1.5">
                    <label className="text-xs font-medium text-[var(--ks-color-text-soft)] uppercase tracking-[0.16em]">
                      Complemento
                    </label>
                    <input
                      value={form.address_complement}
                      onChange={(e) => updateField("address_complement", e.target.value)}
                      className="w-full px-3.5 py-2.5 rounded-full border border-[rgba(198,203,224,0.9)] text-sm outline-none bg-white focus:ring-2 focus:ring-[rgba(10,192,214,0.16)] focus:border-[rgba(10,192,214,0.9)]"
                      placeholder="Apto, sala, etc."
                    />
                  </div>
                  <div className="space-y-1.5">
                    <label className="text-xs font-medium text-[var(--ks-color-text-soft)] uppercase tracking-[0.16em]">
                      Bairro
                    </label>
                    <input
                      value={form.address_neighborhood}
                      onChange={(e) => updateField("address_neighborhood", e.target.value)}
                      className="w-full px-3.5 py-2.5 rounded-full border border-[rgba(198,203,224,0.9)] text-sm outline-none bg-white focus:ring-2 focus:ring-[rgba(10,192,214,0.16)] focus:border-[rgba(10,192,214,0.9)]"
                      placeholder="Bairro"
                    />
                  </div>
                  <div className="space-y-1.5">
                    <label className="text-xs font-medium text-[var(--ks-color-text-soft)] uppercase tracking-[0.16em]">
                      Estado
                    </label>
                    <SimpleSelect
                      value={form.address_state}
                      options={BRAZIL_STATES}
                      placeholder="Selecione o estado"
                      onChange={(value) => {
                        setPendingCity("");
                        setForm((prev) => ({
                          ...prev,
                          address_state: value,
                          address_city: "",
                        }));
                      }}
                      className=""
                    />
                  </div>
                  <div className="space-y-1.5">
                    <label className="text-xs font-medium text-[var(--ks-color-text-soft)] uppercase tracking-[0.16em]">
                      Cidade
                    </label>
                    <SimpleSelect
                      value={form.address_city}
                      options={cities.map((city) => ({ value: city, label: city }))}
                      placeholder={loadingCities ? "Carregando cidades..." : "Selecione a cidade"}
                      disabled={!form.address_state || loadingCities}
                      onChange={(value) => updateField("address_city", value)}
                    />
                  </div>
                  {loadingCep && (
                    <div className="col-span-1 sm:col-span-2 text-xs text-[var(--ks-color-text-soft)]">
                      Buscando endereço pelo CEP...
                    </div>
                  )}
                </div>
              </div>

              <div className="space-y-1.5">
                <label className="text-xs font-medium text-[var(--ks-color-text-soft)] uppercase tracking-[0.16em]">
                  Observações
                </label>
                <textarea
                  value={form.notes}
                  onChange={(e) => updateField("notes", e.target.value)}
                  className="w-full px-3.5 py-2.5 rounded-2xl border border-[rgba(198,203,224,0.9)] text-sm outline-none bg-white focus:ring-2 focus:ring-[rgba(10,192,214,0.16)] focus:border-[rgba(10,192,214,0.9)] min-h-[110px]"
                  placeholder="Informações adicionais"
                />
              </div>

              <div className="space-y-1.5">
                <label className="text-xs font-medium text-[var(--ks-color-text-soft)] uppercase tracking-[0.16em]">
                  Tags
                </label>
                <input
                  value={form.tags}
                  onChange={(e) => updateField("tags", e.target.value)}
                  className="w-full px-3.5 py-2.5 rounded-full border border-[rgba(198,203,224,0.9)] text-sm outline-none bg-white focus:ring-2 focus:ring-[rgba(10,192,214,0.16)] focus:border-[rgba(10,192,214,0.9)]"
                  placeholder="Ex: VIP, Revenda, Indicação"
                />
                <p className="text-[0.7rem] text-[var(--ks-color-text-soft)]">
                  Separe por vírgulas. As tags ajudam a identificar clientes com mais rapidez.
                </p>
              </div>

              <div className="flex justify-end">
                <button
                  type="submit"
                  disabled={submitting}
                  className="inline-flex items-center justify-center rounded-xl px-6 py-3 text-sm font-semibold text-white shadow-sm disabled:opacity-50 hover:opacity-90"
                  style={{ backgroundColor: "var(--ks-color-brand-dark)" }}
                >
                  {submitting ? "Enviando..." : "Enviar cadastro"}
                </button>
              </div>
            </form>
          )}
        </div>
      </div>
    </div>
  );
}


