"use client";

import { useEffect, useMemo, useState } from "react";
import { useRouter } from "next/navigation";
import { PaymentSelector } from "./components/PaymentSelector";
import { Turnstile } from "./components/Turnstile";
import { userMessage } from "./lib/messages";

type IconName =
  | "arrow-right"
  | "building"
  | "car"
  | "check"
  | "check-circle"
  | "clock"
  | "document"
  | "file"
  | "house"
  | "lock"
  | "menu"
  | "plane"
  | "search"
  | "shield"
  | "upload"
  | "users";

function Icon({
  name,
  size = 22,
  strokeWidth = 1.9,
  className = "",
}: {
  name: IconName;
  size?: number;
  strokeWidth?: number;
  className?: string;
}) {
  const common = {
    width: size,
    height: size,
    viewBox: "0 0 24 24",
    fill: "none",
    stroke: "currentColor",
    strokeWidth,
    strokeLinecap: "round" as const,
    strokeLinejoin: "round" as const,
    className,
    "aria-hidden": true,
  };
  switch (name) {
    case "arrow-right":
      return (
        <svg {...common}>
          <path d="M5 12h13" />
          <path d="m13 6 6 6-6 6" />
        </svg>
      );
    case "building":
      return (
        <svg {...common}>
          <path d="M4 21h16" />
          <path d="M6 21V5l6-2 6 2v16" />
          <path d="M9 8h1M14 8h1M9 12h1M14 12h1M9 16h1M14 16h1" />
        </svg>
      );
    case "car":
      return (
        <svg {...common}>
          <path d="m5 17-1.2-4.3a2 2 0 0 1 1.9-2.5h12.6a2 2 0 0 1 1.9 2.5L19 17" />
          <path d="M6 17h12v3H6z" />
          <path d="M7 10.2 8.6 6h6.8l1.6 4.2" />
          <path d="M8 17h.01M16 17h.01" />
        </svg>
      );
    case "check":
      return (
        <svg {...common}>
          <path d="m5 12 4 4L19 6" />
        </svg>
      );
    case "check-circle":
      return (
        <svg {...common}>
          <circle cx="12" cy="12" r="9" />
          <path d="m8 12 2.6 2.6L16.5 9" />
        </svg>
      );
    case "clock":
      return (
        <svg {...common}>
          <circle cx="12" cy="12" r="9" />
          <path d="M12 7v5l3 2" />
        </svg>
      );
    case "document":
      return (
        <svg {...common}>
          <path d="M6 3.5h8l4 4V20.5H6z" />
          <path d="M14 3.5v4h4M9 12h6M9 16h6" />
        </svg>
      );
    case "file":
      return (
        <svg {...common}>
          <path d="M6 3.5h8l4 4V20.5H6z" />
          <path d="M14 3.5v4h4M9 12h6M9 16h4" />
        </svg>
      );
    case "house":
      return (
        <svg {...common}>
          <path d="m4 11 8-7 8 7" />
          <path d="M6 10v10h12V10M10 20v-5h4v5" />
        </svg>
      );
    case "lock":
      return (
        <svg {...common}>
          <rect x="5" y="10" width="14" height="10" rx="2" />
          <path d="M8 10V7a4 4 0 0 1 8 0v3M12 14v2" />
        </svg>
      );
    case "menu":
      return (
        <svg {...common}>
          <path d="M4 7h16M4 12h16M4 17h16" />
        </svg>
      );
    case "plane":
      return (
        <svg {...common}>
          <path d="m3 12 18-7-5.5 14-3.2-5-5.3-2z" />
          <path d="m12.3 14 2.4-2.2" />
        </svg>
      );
    case "search":
      return (
        <svg {...common}>
          <circle cx="10.8" cy="10.8" r="6.3" />
          <path d="m16 16 4 4" />
        </svg>
      );
    case "shield":
      return (
        <svg {...common}>
          <path d="M12 3 19 6v5c0 4.5-2.9 8-7 10-4.1-2-7-5.5-7-10V6z" />
          <path d="m8.5 12 2.2 2.2 4.8-5" />
        </svg>
      );
    case "upload":
      return (
        <svg {...common}>
          <path d="M12 15V4" />
          <path d="m8 8 4-4 4 4" />
          <path d="M5 14v5h14v-5" />
        </svg>
      );
    case "users":
      return (
        <svg {...common}>
          <path d="M16 20v-1.5a4 4 0 0 0-4-4H7a4 4 0 0 0-4 4V20" />
          <circle cx="9.5" cy="7.5" r="3.5" />
          <path d="M17 11a3 3 0 1 0-1.2-5.8M21 20v-1.5a4 4 0 0 0-2.7-3.8" />
        </svg>
      );
    default:
      return null;
  }
}

type Service = {
  id: string;
  name: string;
  category: string;
  icon: IconName;
  description: string;
  capabilities: string[];
};
const serviceCatalog: Service[] = [
  {
    id: "poder-simple",
    name: "Poder simple",
    category: "Personas",
    icon: "file" as IconName,
    description: "Otorga facultades específicas a otra persona.",
    capabilities: ["NOTARIA"],
  },
  {
    id: "declaracion-jurada",
    name: "Declaración jurada",
    category: "Personas",
    icon: "document" as IconName,
    description: "Prepara los hechos que necesitas declarar.",
    capabilities: ["NOTARIA"],
  },
  {
    id: "compraventa-vehiculo",
    name: "Compraventa de vehículo",
    category: "Vehículos",
    icon: "car" as IconName,
    description: "Llega con los antecedentes del vehículo revisados.",
    capabilities: ["NOTARIA"],
  },
  {
    id: "contrato-arriendo",
    name: "Contrato de arriendo",
    category: "Inmuebles",
    icon: "house" as IconName,
    description: "Adelanta los datos principales del contrato.",
    capabilities: ["NOTARIA"],
  },
  {
    id: "autorizacion-viaje",
    name: "Autorización de viaje",
    category: "Personas",
    icon: "plane" as IconName,
    description: "Prepara la autorización para viajar con menores.",
    capabilities: ["NOTARIA"],
  },
  {
    id: "copia-escritura",
    name: "Copia de escritura",
    category: "Inmuebles",
    icon: "building" as IconName,
    description: "Solicita y ordena tus antecedentes inmobiliarios.",
    capabilities: ["NOTARIA", "CONSERVADOR", "ARCHIVERO"],
  },
  {
    id: "finiquito",
    name: "Finiquito",
    category: "Laboral",
    icon: "document" as IconName,
    description: "Adelanta la revisión del término laboral.",
    capabilities: ["NOTARIA"],
  },
  {
    id: "poder-bancario",
    name: "Poder bancario simple",
    category: "Personas",
    icon: "lock" as IconName,
    description: "Autoriza operaciones bancarias específicas.",
    capabilities: ["NOTARIA"],
  },
];

const steps: { number: string; title: string; text: string; icon: IconName }[] =
  [
    {
      number: "01",
      title: "Completa",
      text: "Cuéntanos qué trámite necesitas y completa tus datos básicos.",
      icon: "document",
    },
    {
      number: "02",
      title: "Adjunta",
      text: "Sube tus antecedentes de forma segura y ordenada.",
      icon: "upload",
    },
    {
      number: "03",
      title: "Revisión",
      text: "La notaría revisa la información y te avisa si falta algo.",
      icon: "check-circle",
    },
    {
      number: "04",
      title: "Firma",
      text: "Asiste solo para firmar o retirar cuando todo esté listo.",
      icon: "check",
    },
  ];

const highQuality = "/media/high-quality";
const apiBase = process.env.NEXT_PUBLIC_API_BASE_URL || "/api/v1";
type NotaryOffer = {
  directorio_id: number;
  nombre_fantasia: string;
  direccion: string;
  comuna: string;
  precio: number;
  moneda: string;
  medios_pago: string[];
};
type SaleResult = {
  folio: string;
  access_token: string;
  estado: string;
  total: number;
  vence_en: string;
};
type MatterField = {
  id: number;
  codigo: string;
  etiqueta: string;
  ayuda?: string;
  placeholder?: string;
  requerido: boolean;
  tipo_dato: string;
  opciones_json?: string | null;
  largo_minimo?: number | null;
  largo_maximo?: number | null;
  valor_minimo?: number | null;
  valor_maximo?: number | null;
  patron_regex?: string | null;
};
type Requirement = {
  id: number;
  nombre: string;
  descripcion?: string;
  requerido: boolean;
  tipo: string;
};
type MatterDetail = {
  nombre: string;
  descripcion?: string;
  campos: MatterField[];
  requisitos: Requirement[];
  comunas?: { codigo: number; nombre: string; region: string }[];
};
type CustomerDraft = {
  name: string;
  email: string;
  rut: string;
  phone: string;
};
const SYSTEM_CUSTOMER_FIELDS = new Set([
  "cliente_nombre_completo",
  "cliente_email",
  "cliente_rut",
  "cliente_telefono",
]);
const documentFields = (detail: MatterDetail | null) =>
  (detail?.campos || []).filter((field) => !SYSTEM_CUSTOMER_FIELDS.has(field.codigo));

function formatRutInput(value: string) {
  const clean = value.replace(/[^0-9kK]/g, "").toUpperCase();
  if (clean.length < 2) return clean;
  return `${clean.slice(0, -1).replace(/\B(?=(\d{3})+(?!\d))/g, ".")}-${clean.slice(-1)}`;
}
function validRut(value: string) {
  const clean = value.replace(/[^0-9kK]/g, "").toUpperCase();
  if (clean.length < 2 || !/^[0-9]+[0-9K]$/.test(clean)) return false;
  let sum = 0,
    factor = 2;
  for (let index = clean.length - 2; index >= 0; index--) {
    sum += Number(clean[index]) * factor;
    factor = factor === 7 ? 2 : factor + 1;
  }
  const result = 11 - (sum % 11);
  const expected = result === 11 ? "0" : result === 10 ? "K" : String(result);
  return expected === clean.at(-1);
}
function isRutFieldType(value: string) {
  return ["RUT", "RUT_CHILENO", "RUT CHILENO"].includes(value.trim().toUpperCase());
}
function validateConfiguredField(field: MatterField, value: string) {
  if (!value && !field.requerido) return "";
  if (field.largo_minimo != null && value.length < field.largo_minimo)
    return `${field.etiqueta}: mínimo ${field.largo_minimo} caracteres.`;
  if (field.largo_maximo != null && value.length > field.largo_maximo)
    return `${field.etiqueta}: máximo ${field.largo_maximo} caracteres.`;
  if (field.patron_regex) {
    try {
      if (!new RegExp(`^(?:${field.patron_regex})$`).test(value))
        return `${field.etiqueta}: formato inválido.`;
    } catch {
      return `${field.etiqueta}: validación mal configurada.`;
    }
  }
  if (isRutFieldType(field.tipo_dato) && !validRut(value))
    return `${field.etiqueta}: RUT inválido.`;
  if (["ENTERO", "DECIMAL"].includes(field.tipo_dato)) {
    const number = Number(value);
    if (
      !Number.isFinite(number) ||
      (field.tipo_dato === "ENTERO" && !Number.isInteger(number))
    )
      return `${field.etiqueta}: número inválido.`;
    if (field.valor_minimo != null && number < field.valor_minimo)
      return `${field.etiqueta}: valor mínimo ${field.valor_minimo}.`;
    if (field.valor_maximo != null && number > field.valor_maximo)
      return `${field.etiqueta}: valor máximo ${field.valor_maximo}.`;
  }
  return "";
}

export default function Home() {
  const router = useRouter();
  const [menuOpen, setMenuOpen] = useState(false);
  const [query, setQuery] = useState("");
  const [category, setCategory] = useState("Todos");
  const [entityType, setEntityType] = useState("TODAS");
  const [services, setServices] = useState<Service[]>(serviceCatalog);
  const [wizardOpen, setWizardOpen] = useState(false);
  const [wizardStep, setWizardStep] = useState(1);
  const [selectedService, setSelectedService] = useState<Service>(
    serviceCatalog[0],
  );
  const [submitted, setSubmitted] = useState(false);
  const [notaries, setNotaries] = useState<NotaryOffer[]>([]);
  const [notaryAvailability, setNotaryAvailability] = useState("");
  const [selectedDirectory, setSelectedDirectory] = useState<number | null>(
    null,
  );
  const [paymentProvider, setPaymentProvider] = useState("");
  const [submitting, setSubmitting] = useState(false);
  const [submitError, setSubmitError] = useState("");
  const [saleResult, setSaleResult] = useState<SaleResult | null>(null);
  const [matterDetail, setMatterDetail] = useState<MatterDetail | null>(null);
  const [customerDraft, setCustomerDraft] = useState<CustomerDraft>({
    name: "",
    email: "",
    rut: "",
    phone: "",
  });
  const [fieldAnswers, setFieldAnswers] = useState<Record<number, string>>({});
  const [acceptedTerms, setAcceptedTerms] = useState(false);
  const [captchaToken, setCaptchaToken] = useState("");
  const [loadingMatter, setLoadingMatter] = useState(false);
  const [accountOpen, setAccountOpen] = useState(false);
  const [accountError, setAccountError] = useState("");

  const filteredServices = useMemo(() => {
    const normalized = query.trim().toLocaleLowerCase("es");
    return services.filter((service) => {
      const matchesCategory =
        category === "Todos" || service.category === category;
      const matchesEntity =
        entityType === "TODAS" || service.capabilities.includes(entityType);
      const matchesQuery =
        !normalized ||
        `${service.name} ${service.description}`
          .toLocaleLowerCase("es")
          .includes(normalized);
      return matchesCategory && matchesEntity && matchesQuery;
    });
  }, [category, entityType, query, services]);

  useEffect(() => {
    fetch(`${apiBase}/materias`)
      .then(async (response) => {
        if (!response.ok) throw new Error("catalogo");
        const data = await response.json();
        const iconFor = (slug: string, categoryName: string): IconName =>
          slug.includes("vehiculo")
            ? "car"
            : slug.includes("viaje")
              ? "plane"
              : categoryName === "Inmuebles"
                ? "house"
                : categoryName === "Laboral"
                  ? "document"
                  : "file";
        setServices(
          (data.items || []).map(
            (item: {
              slug: string;
              nombre: string;
              categoria: string;
              descripcion_corta: string;
              capacidades?: string[];
            }) => ({
              id: item.slug,
              name: item.nombre,
              category: item.categoria,
              description: item.descripcion_corta,
              icon: iconFor(item.slug, item.categoria),
              capabilities: Array.isArray(item.capacidades) && item.capacidades.length
                ? item.capacidades.map(String)
                : ["NOTARIA"],
            }),
          ),
        );
      })
      .catch(() => {
        /* El catalogo visual de respaldo permanece disponible. */
      });
  }, []);

  useEffect(() => {
    const closeOnEscape = (event: KeyboardEvent) => {
      if (event.key === "Escape") {
        setMenuOpen(false);
        setWizardOpen(false);
      }
    };
    window.addEventListener("keydown", closeOnEscape);
    return () => window.removeEventListener("keydown", closeOnEscape);
  }, []);

  useEffect(() => {
    document.body.style.overflow = wizardOpen ? "hidden" : "";
    return () => {
      document.body.style.overflow = "";
    };
  }, [wizardOpen]);

  useEffect(() => {
    const root = document.documentElement;
    const targets = Array.from(
      document.querySelectorAll<HTMLElement>("[data-reveal]"),
    );
    root.classList.add("motion-ready");

    if (!("IntersectionObserver" in window)) {
      targets.forEach((target) => target.classList.add("is-visible"));
      return () => root.classList.remove("motion-ready");
    }

    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting) {
            entry.target.classList.add("is-visible");
            observer.unobserve(entry.target);
          }
        });
      },
      { threshold: 0.13, rootMargin: "0px 0px -8% 0px" },
    );

    targets.forEach((target) => observer.observe(target));
    return () => {
      observer.disconnect();
      root.classList.remove("motion-ready");
    };
  }, []);

  const openWizardLegacy = async (service: Service = selectedService) => {
    setSelectedService(service);
    setSubmitted(false);
    setSaleResult(null);
    setSubmitError("");
    setWizardStep(1);
    setMatterDetail(null);
    setFieldAnswers({});
    setAccountOpen(false);
    setAccountError("");
    setNotaries([]);
    setNotaryAvailability("");
    setSelectedDirectory(null);
    setPaymentProvider("");
    setAcceptedTerms(false);
    setWizardOpen(true);
    setMenuOpen(false);
    setLoadingMatter(true);
    try {
      const [matterResponse, notariesResponse] = await Promise.all([
        fetch(`${apiBase}/materias/${encodeURIComponent(service.id)}`, {
          cache: "no-store",
        }),
        fetch(`${apiBase}/notarias?materia=${encodeURIComponent(service.id)}`, {
          cache: "no-store",
        }),
      ]);
      if (!matterResponse.ok)
        throw new Error(
          "No fue posible cargar los campos y requisitos del trámite.",
        );
      if (!notariesResponse.ok)
        throw new Error("No fue posible consultar notarías.");
      setMatterDetail(await matterResponse.json());
      const notaryData = await notariesResponse.json();
      setNotaries(notaryData.items || []);
      setNotaryAvailability(notaryData.message || "");
    } catch (error) {
      setSubmitError(
        userMessage(error, "No fue posible cargar el trámite."),
      );
    } finally {
      setLoadingMatter(false);
    }
  };
  const openWizard = (service: Service = selectedService) => {
    router.push(`/tramite/${encodeURIComponent(service.id)}`);
  };
  const startSelection = () => {
    setMenuOpen(false);
    document.getElementById("tramites")?.scrollIntoView({ behavior: "smooth" });
    window.setTimeout(
      () => document.getElementById("service-search")?.focus(),
      450,
    );
  };

  const advanceToNotary = (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    setSubmitError("");
    const form = new FormData(event.currentTarget);
    const draft = {
      name: String(form.get("name") || "").trim(),
      email: String(form.get("email") || "").trim(),
      rut: String(form.get("rut") || "").trim(),
      phone: String(form.get("phone") || "").trim(),
    };
    if (draft.name.split(/\s+/).length < 2) {
      setSubmitError("Ingresa al menos un nombre y un apellido.");
      return;
    }
    if (!validRut(draft.rut)) {
      setSubmitError("Ingresa un RUT chileno válido.");
      return;
    }
    draft.rut = formatRutInput(draft.rut);
    const answers: Record<number, string> = {};
    for (const field of documentFields(matterDetail)) {
      const value = String(form.get(`field-${field.id}`) || "").trim();
      answers[field.id] = isRutFieldType(field.tipo_dato) && value
        ? formatRutInput(value)
        : value;
    }
    const missing = documentFields(matterDetail).find(
      (field) => field.requerido && !answers[field.id],
    );
    if (missing) {
      setSubmitError(`Completa el campo: ${missing.etiqueta}.`);
      return;
    }
    const invalid = documentFields(matterDetail)
      .map((field) => validateConfiguredField(field, answers[field.id] || ""))
      .find(Boolean);
    if (invalid) {
      setSubmitError(invalid);
      return;
    }
    setCustomerDraft(draft);
    setFieldAnswers(answers);
    setWizardStep(3);
  };

  const createSale = async () => {
    setSubmitError("");
    if (!selectedDirectory) {
      setSubmitError("Selecciona una notaría disponible.");
      return;
    }
    if (!acceptedTerms) {
      setSubmitError("Debes aceptar los términos y el tratamiento de datos.");
      return;
    }
    if (!captchaToken) {
      setSubmitError("Completa la verificación de seguridad.");
      return;
    }
    const fullName = customerDraft.name.trim().split(/\s+/);
    const surnameCount = fullName.length >= 3 ? 2 : 1;
    setSubmitting(true);
    try {
      const response = await fetch(`${apiBase}/ventas`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "Idempotency-Key": crypto.randomUUID(),
        },
        body: JSON.stringify({
          directorio_id: selectedDirectory,
          captcha_token: captchaToken,
          consentimientos: [],
          respuestas: Object.entries(fieldAnswers)
            .filter(([, valor]) => valor)
            .map(([campo_id, valor]) => ({
              campo_id: Number(campo_id),
              valor,
            })),
          cliente: {
            nombres: fullName.slice(0, -surnameCount).join(" "),
            apellidos: fullName.slice(-surnameCount).join(" "),
            email: customerDraft.email,
            rut: customerDraft.rut,
            telefono: customerDraft.phone || null,
          },
        }),
      });
      const data = await response.json();
      if (!response.ok)
        throw new Error(data.detail || "No fue posible crear el trámite.");
      localStorage.setItem(`documenta:${data.folio}`, data.access_token);
      setSaleResult(data);
      setSubmitted(true);
      setWizardStep(4);
    } catch (error) {
      setSubmitError(
        userMessage(error, "No fue posible continuar con la solicitud."),
      );
    } finally {
      setSubmitting(false);
    }
  };

  const startPayment = async () => {
    if (!saleResult) return;
    if (!paymentProvider) {
      setSubmitError("Selecciona un medio de pago.");
      return;
    }
    setSubmitting(true);
    setSubmitError("");
    try {
      const response = await fetch(`${apiBase}/pagos`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "Idempotency-Key": crypto.randomUUID(),
        },
        body: JSON.stringify({
          folio: saleResult.folio,
          access_token: saleResult.access_token,
          proveedor: paymentProvider,
        }),
      });
      const data = await response.json();
      if (!response.ok)
        throw new Error(data.detail || "No fue posible iniciar el pago.");
      sessionStorage.setItem(
        "documenta:pending-payment",
        JSON.stringify({
          pago_id: data.pago_id,
          folio: saleResult.folio,
          access_token: saleResult.access_token,
          proveedor: paymentProvider,
        }),
      );
      sessionStorage.removeItem("documenta:completed-payment");
      if (String(data.redirect_method || "GET").toUpperCase() === "POST") {
        const form = document.createElement("form");
        form.method = "POST";
        form.action = String(data.redirect_url);
        const token = document.createElement("input");
        token.type = "hidden";
        token.name = "token_ws";
        token.value = String(data.token || "");
        form.appendChild(token);
        document.body.appendChild(form);
        form.submit();
      } else {
        window.location.href = data.redirect_url;
      }
    } catch (error) {
      setSubmitError(
        userMessage(error, "No fue posible guardar la solicitud."),
      );
      setSubmitting(false);
    }
  };

  const createOptionalAccount = async (
    event: React.FormEvent<HTMLFormElement>,
  ) => {
    event.preventDefault();
    if (!saleResult) return;
    setSubmitting(true);
    setAccountError("");
    const form = new FormData(event.currentTarget);
    if (form.get("password") !== form.get("confirm_password")) {
      setAccountError("Las contraseñas no coinciden.");
      setSubmitting(false);
      return;
    }
    try {
      const response = await fetch(`${apiBase}/auth/register-customer`, {
        method: "POST",
        credentials: "include",
        headers: {
          "Content-Type": "application/json",
          "Idempotency-Key": crypto.randomUUID(),
        },
        body: JSON.stringify({
          folio: saleResult.folio,
          access_token: saleResult.access_token,
          password: form.get("password"),
        }),
      });
      const data = await response.json();
      if (!response.ok)
        throw new Error(data.detail || "No fue posible crear la cuenta.");
      sessionStorage.setItem("documenta:csrf", data.csrf_token);
      setSubmitting(false);
      await startPayment();
    } catch (reason) {
      setAccountError(
        userMessage(reason, "No fue posible iniciar el pago."),
      );
      setSubmitting(false);
    }
  };

  return (
    <>
      <a className="skip-link" href="#contenido">
        Saltar al contenido principal
      </a>
      <header className="site-header">
        <div className="container header-inner">
          <a
            className="brand"
            href="#inicio"
            aria-label="Documenta, volver al inicio"
          >
            <img
              src="/media/brand/logo-original-transparent.png"
              alt="Documenta"
              width="174"
              height="37"
            />
          </a>
          <button
            className="menu-toggle"
            type="button"
            aria-expanded={menuOpen}
            aria-controls="primary-navigation"
            aria-label={menuOpen ? "Cerrar menú" : "Abrir menú"}
            onClick={() => setMenuOpen((value) => !value)}
          >
            <Icon name={menuOpen ? "check" : "menu"} size={23} />
          </button>
          <nav
            className={`primary-navigation ${menuOpen ? "is-open" : ""}`}
            id="primary-navigation"
            aria-label="Navegación principal"
          >
            <a href="#tramites" onClick={() => setMenuOpen(false)}>
              Trámites
            </a>
            <a href="#como-funciona" onClick={() => setMenuOpen(false)}>
              Cómo funciona
            </a>
            <a href="#beneficios" onClick={() => setMenuOpen(false)}>
              Beneficios
            </a>
            <a href="https://documenta.cl/contacto" onClick={() => setMenuOpen(false)}>
              Contacto
            </a>
          </nav>
          <div className="header-actions">
            <a className="header-link" href="/acceso">
              Ingresar
            </a>
            <button
              className="button button-primary button-small"
              type="button"
              onClick={startSelection}
            >
              Iniciar trámite <Icon name="arrow-right" size={18} />
            </button>
          </div>
        </div>
      </header>

      <main id="contenido">
        <section className="hero" id="inicio">
          <div className="container hero-grid">
            <div className="hero-copy" data-reveal="up">
              <span className="eyebrow">
                <span className="eyebrow-dot" /> Adelanta tu trámite
              </span>
              <h1>
                Inicia tu trámite antes de ir a la notaría
                <span className="red-period">.</span>
              </h1>
              <p className="hero-lead">
                Selecciona lo que necesitas, completa tus datos y envía tus
                antecedentes. Llega con todo preparado para firmar o finalizar
                lo necesario.
              </p>
              <div className="hero-actions">
                <button
                  className="button button-primary button-large"
                  type="button"
                  onClick={startSelection}
                >
                  Iniciar trámite <Icon name="arrow-right" size={19} />
                </button>
                <a
                  className="button button-secondary button-large"
                  href="#tramites"
                >
                  Ver trámites
                </a>
              </div>
              <div className="trust-points" aria-label="Ventajas principales">
                <div>
                  <span className="trust-icon">
                    <Icon name="clock" />
                  </span>
                  <span>
                    <strong>Menos espera</strong>
                    <small>Adelanta antes de ir.</small>
                  </span>
                </div>
                <div>
                  <span className="trust-icon">
                    <Icon name="check-circle" />
                  </span>
                  <span>
                    <strong>Revisión previa</strong>
                    <small>Evita documentos faltantes.</small>
                  </span>
                </div>
                <div>
                  <span className="trust-icon">
                    <Icon name="shield" />
                  </span>
                  <span>
                    <strong>Proceso guiado</strong>
                    <small>Sabes qué sigue.</small>
                  </span>
                </div>
              </div>
            </div>
            <div
              className="hero-visual"
              data-reveal="visual"
              aria-label="Persona preparando su trámite en Documenta"
            >
              <div className="hero-photo-frame">
                <img
                  src={`${highQuality}/022_foto_mujer_laptop_tramite_preparado_MEJORADO.png`}
                  alt="Mujer preparando un trámite en su computador"
                />
              </div>
              <div className="hero-phone-float">
                <img
                  src={`${highQuality}/hero-phone-transparent-v2.png`}
                  alt="Formulario de Documenta en un teléfono"
                />
              </div>
              <div className="hero-orbit orbit-one" aria-hidden="true" />
              <div className="hero-orbit orbit-two" aria-hidden="true" />
            </div>
          </div>
        </section>

        <section className="section section-services" id="tramites">
          <div className="container">
            <div className="section-heading" data-reveal="up">
              <div>
                <span className="section-kicker">Comienza en línea</span>
                <h2>¿Qué trámite necesitas?</h2>
                <p>
                  Elige un trámite para conocer sus antecedentes básicos e
                  iniciar el proceso.
                </p>
              </div>
              <label className="service-search" htmlFor="service-search">
                <Icon name="search" size={20} />
                <input
                  id="service-search"
                  type="search"
                  value={query}
                  onChange={(event) => setQuery(event.target.value)}
                  placeholder="Buscar por nombre"
                />
              </label>
            </div>
            <div
              className="filter-tabs"
              data-reveal="up"
              role="group"
              aria-label="Filtrar trámites por categoría"
            >
              {["Todos", "Personas", "Laboral", "Vehículos", "Inmuebles"].map(
                (item) => (
                  <button
                    key={item}
                    className={category === item ? "is-active" : ""}
                    type="button"
                    onClick={() => setCategory(item)}
                  >
                    {item}
                  </button>
                ),
              )}
            </div>
            <div className="entity-type-filter" role="group" aria-label="Filtrar trámites por tipo de entidad">
              <span>Tipo de entidad</span>
              {[
                ["TODAS", "Todas"],
                ["NOTARIA", "Notarías"],
                ["CONSERVADOR", "Conservadores"],
                ["ARCHIVERO", "Archiveros"],
              ].map(([value, label]) => (
                <button key={value} type="button" className={entityType === value ? "is-active" : ""}
                  onClick={() => setEntityType(value)}>{label}</button>
              ))}
            </div>
            <div className="services-grid">
              {filteredServices.map((service) => (
                <button
                  className="service-card"
                  key={service.id}
                  type="button"
                  onClick={() => openWizard(service)}
                >
                  <span className="service-card-top">
                    <span className="service-icon">
                      <Icon name={service.icon} size={24} />
                    </span>
                    <span className="service-arrow">
                      <Icon name="arrow-right" size={18} />
                    </span>
                  </span>
                  <span className="service-entity-badges">
                    {service.capabilities.map((capability) => (
                      <span key={capability} className={`service-entity-badge is-${capability.toLowerCase()}`}>
                        {capability === "NOTARIA" ? "Notaría" : capability === "CONSERVADOR" ? "Conservador" : "Archivero"}
                      </span>
                    ))}
                  </span>
                  <span className="service-category">{service.category}</span>
                  <strong>{service.name}</strong>
                  <span className="service-description">
                    {service.description}
                  </span>
                </button>
              ))}
            </div>
            {filteredServices.length === 0 && (
              <p className="empty-state">
                No encontramos un trámite con ese nombre.
              </p>
            )}
          </div>
        </section>

        <section className="section section-process" id="como-funciona">
          <div className="container">
            <div className="section-heading centered" data-reveal="up">
              <div>
                <span className="section-kicker">Así de simple</span>
                <h2>Tu visita comienza antes de llegar</h2>
                <p>
                  Adelantamos la información y la revisión para que uses tu
                  tiempo presencial solo en lo necesario.
                </p>
              </div>
            </div>
            <ol className="process-grid">
              {steps.map((step, index) => (
                <li
                  className="process-step"
                  data-reveal="card"
                  key={step.number}
                >
                  <span className="step-number">{step.number}</span>
                  <span className="step-icon">
                    <Icon name={step.icon} size={26} />
                  </span>
                  <h3>{step.title}</h3>
                  <p>{step.text}</p>
                  {index < steps.length - 1 && (
                    <span className="step-line" aria-hidden="true" />
                  )}
                </li>
              ))}
            </ol>
            <div className="process-showcase">
              <div data-reveal="left">
                <span className="section-kicker">Requisitos y seguimiento</span>
                <h3>Más claridad en cada paso.</h3>
                <p>
                  Consulta el estado, completa pendientes y llega con el trámite
                  preparado.
                </p>
                <button
                  className="text-link"
                  type="button"
                  onClick={startSelection}
                >
                  Ver cómo funciona <Icon name="arrow-right" size={17} />
                </button>
              </div>
              <div className="process-showcase-visual" data-reveal="right">
                <img
                  src={`${highQuality}/038_mockup_plataforma_completo_MEJORADO.png`}
                  alt="Panel de Documenta con el estado de varios trámites"
                />
              </div>
            </div>
          </div>
        </section>

        <section className="section section-benefits" id="beneficios">
          <div className="container benefits-grid">
            <div className="benefit-copy" data-reveal="left">
              <span className="section-kicker">Menos vueltas</span>
              <h2>Más trámites preparados. Menos tiempo en mesón.</h2>
              <p>
                Documenta organiza la información antes de tu visita para que la
                atención presencial sea breve, ordenada y clara.
              </p>
              <ul className="benefit-list">
                <li>
                  <span>
                    <Icon name="clock" size={21} />
                  </span>
                  <div>
                    <strong>Atención más rápida</strong>
                    <p>
                      Reduce el tiempo dedicado a completar datos en la notaría.
                    </p>
                  </div>
                </li>
                <li>
                  <span>
                    <Icon name="check-circle" size={21} />
                  </span>
                  <div>
                    <strong>Menos errores</strong>
                    <p>
                      Recibe orientación sobre los antecedentes que necesitas.
                    </p>
                  </div>
                </li>
                <li>
                  <span>
                    <Icon name="users" size={21} />
                  </span>
                  <div>
                    <strong>Un proceso humano</strong>
                    <p>
                      La notaría mantiene el control y te acompaña cuando
                      corresponde.
                    </p>
                  </div>
                </li>
              </ul>
            </div>
            <div className="benefit-photo" data-reveal="right">
              <div className="benefit-photo-crop">
                <img
                  src={`${highQuality}/025_foto_atencion_notaria_MEJORADO.png`}
                  alt="Atención clara y eficiente en una notaría"
                />
              </div>
              <div className="benefit-stat">
                <strong>-62%</strong>
                <span>tiempo en notaría</span>
              </div>
            </div>
          </div>
        </section>

        <section className="section section-platform" id="notarias">
          <div className="container platform-grid">
            <div className="platform-visual" data-reveal="left">
              <img
                src={`${highQuality}/039_mockup_laptop_mis_tramites_MEJORADO.png`}
                alt="Panel de mis trámites de Documenta en un laptop y teléfono"
              />
            </div>
            <div className="platform-copy" data-reveal="right">
              <span className="section-kicker">Para personas y notarías</span>
              <h2>Una experiencia preparada para avanzar.</h2>
              <p>
                La plataforma conecta la preparación digital con la atención
                presencial, sin reemplazar el acompañamiento de la notaría.
              </p>
              <div className="platform-points">
                <div>
                  <span>
                    <Icon name="lock" />
                  </span>
                  <strong>Datos protegidos</strong>
                  <small>Información tratada con cuidado y claridad.</small>
                </div>
                <div>
                  <span>
                    <Icon name="check-circle" />
                  </span>
                  <strong>Proceso guiado</strong>
                  <small>Estados visibles y próximos pasos concretos.</small>
                </div>
                <div>
                  <span>
                    <Icon name="building" />
                  </span>
                  <strong>Notarías verificadas</strong>
                  <small>La revisión final sigue en manos de la notaría.</small>
                </div>
              </div>
              <a
                className="button button-dark"
                href="https://documenta.cl/contacto"
              >
                Contactar <Icon name="arrow-right" size={18} />
              </a>
            </div>
          </div>
        </section>

        <section className="section section-security">
          <div className="container security-inner">
            <div className="security-copy" data-reveal="left">
              <span className="section-kicker">Confianza Documenta</span>
              <h2>Tu información, siempre en contexto.</h2>
              <p>
                Explicamos qué necesitas, por qué y en qué estado está tu
                trámite. Sin letra chica ni pasos escondidos.
              </p>
              <div className="security-tags">
                <span>
                  <Icon name="shield" size={18} /> Privacidad
                </span>
                <span>
                  <Icon name="check-circle" size={18} /> Trazabilidad
                </span>
                <span>
                  <Icon name="lock" size={18} /> Control
                </span>
              </div>
            </div>
            <img
              className="security-video-mockup"
              data-reveal="right"
              src="/media/video/documenta-video-placeholder.svg"
              alt="Maqueta del próximo video de presentación de Documenta"
            />
          </div>
        </section>

        <section className="section section-cta">
          <div className="container cta-inner">
            <div data-reveal="left">
              <span className="section-kicker light">
                Tu trámite empieza aquí
              </span>
              <h2>Llega a firmar, no a empezar.</h2>
              <p>Selecciona tu trámite y avanza en pocos minutos.</p>
            </div>
            <button
              className="button button-light button-large"
              data-reveal="right"
              type="button"
              onClick={startSelection}
            >
              Iniciar trámite <Icon name="arrow-right" size={19} />
            </button>
          </div>
        </section>
      </main>

      <footer className="site-footer">
        <div className="container footer-grid" data-reveal="up">
          <div>
            <img
              className="footer-logo"
              src="/media/brand/logo-horizontal-white.svg"
              alt="Documenta"
              width="165"
              height="42"
            />
            <p>Tu trámite comienza antes de llegar a la notaría.</p>
          </div>
          <div>
            <strong>Explora</strong>
            <a href="#tramites">Trámites</a>
            <a href="#como-funciona">Cómo funciona</a>
            <a href="#beneficios">Beneficios</a>
          </div>
          <div>
            <strong>Contacto</strong>
            <a href="mailto:contacto@documenta.cl">contacto@documenta.cl</a>
            <a href="https://documenta.cl/contacto">Página de contacto</a>
            <a href="tel:+562264691551">+56 2 2646 91551</a>
            <span>Huerfanos 1160 OF 909, Santiago Centro</span>
          </div>
        </div>
        <div className="container footer-bottom" data-reveal="up">
          <span>© 2026 Documenta.cl - todos los derechos reservados</span>
          <span>Desarrollado por Undermarket Chile SPA</span>
        </div>
      </footer>

      {wizardOpen && (
        <div
          className="modal-backdrop"
          role="presentation"
          onMouseDown={(event) => {
            if (event.currentTarget === event.target) setWizardOpen(false);
          }}
        >
          <section
            className={`wizard ${wizardStep === 2 || wizardStep === 3 ? "wizard-wide" : ""}`}
            role="dialog"
            aria-modal="true"
            aria-labelledby="wizard-title"
          >
            <button
              className="wizard-close"
              type="button"
              onClick={() => setWizardOpen(false)}
              aria-label="Cerrar"
            >
              <span aria-hidden="true">×</span>
            </button>
            <div className="wizard-header">
              <span className="section-kicker">Paso {wizardStep} de 4</span>
              <h2 id="wizard-title">
                {wizardStep === 1
                  ? selectedService.name
                  : wizardStep === 2
                    ? `Prepara tu ${selectedService.name.toLocaleLowerCase("es")}.`
                    : wizardStep === 3
                      ? "Elige dónde realizarlo."
                      : "Tu trámite está preparado."}
              </h2>
              <p>
                {wizardStep === 1
                  ? "Revisa la descripción y lo que necesitas antes de comenzar."
                  : wizardStep === 2
                    ? "Completa los datos solicitados para este documento."
                    : wizardStep === 3
                      ? "Selecciona una notaría disponible antes de continuar al pago."
                      : "Revisa el folio y continúa al pago seguro de la notaría."}
              </p>
            </div>
            <div
              className="wizard-progress"
              aria-label={`Paso ${wizardStep} de 4`}
            >
              <span className={wizardStep >= 1 ? "is-active" : ""}>
                {wizardStep > 1 ? <Icon name="check" size={14} /> : 1}
              </span>
              <i />
              <span className={wizardStep >= 2 ? "is-active" : ""}>
                {wizardStep > 2 ? <Icon name="check" size={14} /> : 2}
              </span>
              <i />
              <span className={wizardStep >= 3 ? "is-active" : ""}>3</span>
              <i />
              <span className={wizardStep >= 4 ? "is-active" : ""}>4</span>
            </div>
            <div className="wizard-selected">
              <span className="service-icon">
                <Icon name={selectedService.icon} size={22} />
              </span>
              <div>
                <strong>{selectedService.name}</strong>
                <small>{selectedService.category} · preparación guiada</small>
              </div>
              {wizardStep === 1 && (
                <button
                  type="button"
                  onClick={() => {
                    setWizardOpen(false);
                    document
                      .getElementById("tramites")
                      ?.scrollIntoView({ behavior: "smooth" });
                  }}
                >
                  Cambiar
                </button>
              )}
            </div>

            {wizardStep === 1 && (
              <div className="document-intro">
                <div className="document-intro-copy">
                  <span className="section-kicker">
                    Acerca de este documento
                  </span>
                  <p>
                    {matterDetail?.descripcion || selectedService.description}
                  </p>
                </div>
                <div className="requirements-panel intro-requirements">
                  {loadingMatter ? (
                    <p>Cargando información…</p>
                  ) : matterDetail?.requisitos.length ? (
                    <ul>
                      {matterDetail.requisitos.map((requirement) => (
                        <li key={requirement.id}>
                          <Icon name="check-circle" size={20} />
                          <span>
                            <strong>
                              {requirement.nombre}
                              {requirement.requerido ? " *" : ""}
                            </strong>
                            {requirement.descripcion && (
                              <small>{requirement.descripcion}</small>
                            )}
                          </span>
                        </li>
                      ))}
                    </ul>
                  ) : (
                    <p>
                      Este trámite no tiene requisitos adicionales configurados.
                    </p>
                  )}
                </div>
                {submitError && <p className="form-error">{submitError}</p>}
                <button
                  className="button button-primary button-large"
                  disabled={loadingMatter || !matterDetail}
                  onClick={() => {
                    setSubmitError("");
                    setWizardStep(2);
                  }}
                >
                  Entiendo, comenzar <Icon name="arrow-right" size={19} />
                </button>
              </div>
            )}

            {wizardStep === 2 && (
              <form className="wizard-form" onSubmit={advanceToNotary}>
                {loadingMatter && (
                  <p className="wizard-loading">
                    Cargando datos del documento…
                  </p>
                )}
                {!loadingMatter && matterDetail && (
                  <>
                    <div className="form-section-title">Datos de contacto</div>
                    <label>
                      Nombre completo
                      <input
                        required
                        name="name"
                        defaultValue={customerDraft.name}
                        placeholder="Ej. María González"
                        autoComplete="name"
                      />
                    </label>
                    <label>
                      Correo electrónico
                      <input
                        required
                        type="email"
                        name="email"
                        defaultValue={customerDraft.email}
                        placeholder="nombre@correo.cl"
                        autoComplete="email"
                      />
                    </label>
                    <div className="wizard-form-row">
                      <label>
                        RUT
                        <input
                          required
                          name="rut"
                          defaultValue={customerDraft.rut}
                          onChange={(event) =>
                            (event.currentTarget.value = formatRutInput(
                              event.currentTarget.value,
                            ))
                          }
                          placeholder="12.345.678-9"
                        />
                      </label>
                      <label>
                        Teléfono
                        <input
                          name="phone"
                          required
                          defaultValue={customerDraft.phone}
                          placeholder="+56 9 1234 5678"
                          autoComplete="tel"
                        />
                      </label>
                    </div>
                    {!!documentFields(matterDetail).length && (
                      <div className="form-section-title">
                        Datos del documento
                      </div>
                    )}
                    {documentFields(matterDetail).map((field) => {
                      const common = {
                        required: field.requerido,
                        name: `field-${field.id}`,
                        defaultValue: isRutFieldType(field.tipo_dato)
                          ? formatRutInput(fieldAnswers[field.id] || "")
                          : fieldAnswers[field.id] || "",
                      };
                      const options = field.opciones_json
                        ? JSON.parse(field.opciones_json)
                        : [];
                      return (
                        <label key={field.id}>
                          {field.etiqueta}
                          {field.requerido ? " *" : ""}
                          {field.tipo_dato === "TEXTO_LARGO" ? (
                            <textarea
                              {...common}
                              minLength={field.largo_minimo || undefined}
                              maxLength={field.largo_maximo || undefined}
                              placeholder={field.placeholder || ""}
                            />
                          ) : field.tipo_dato === "COMUNA" ? (
                            <select {...common}>
                              <option value="">Selecciona tu comuna</option>
                              {(matterDetail.comunas || []).map((item) => (
                                <option key={String(item.codigo)} value={String(item.codigo)}>
                                  {String(item.nombre)} · {String(item.region)}
                                </option>
                              ))}
                            </select>
                          ) : field.tipo_dato === "LISTA" ? (
                            <select {...common}>
                              <option value="">Selecciona una opción</option>
                              {options.map((option: string) => (
                                <option key={option}>{option}</option>
                              ))}
                            </select>
                          ) : field.tipo_dato === "BOOLEANO" ? (
                            <select {...common}>
                              <option value="">Selecciona</option>
                              <option value="true">Sí</option>
                              <option value="false">No</option>
                            </select>
                          ) : (
                            <input
                              {...common}
                              type={
                                field.tipo_dato === "FECHA"
                                  ? "date"
                                  : field.tipo_dato === "FECHA_HORA"
                                    ? "datetime-local"
                                    : field.tipo_dato === "ENTERO" ||
                                        field.tipo_dato === "DECIMAL"
                                      ? "number"
                                      : field.tipo_dato === "EMAIL"
                                        ? "email"
                                        : field.tipo_dato === "TELEFONO"
                                          ? "tel"
                                          : "text"
                              }
                              step={
                                field.tipo_dato === "DECIMAL"
                                  ? "any"
                                  : undefined
                              }
                              min={field.valor_minimo ?? undefined}
                              max={field.valor_maximo ?? undefined}
                              minLength={field.largo_minimo || undefined}
                              maxLength={field.largo_maximo || undefined}
                              pattern={field.patron_regex || undefined}
                              onChange={
                                isRutFieldType(field.tipo_dato)
                                  ? (event) =>
                                      (event.currentTarget.value =
                                        formatRutInput(
                                          event.currentTarget.value,
                                        ))
                                  : undefined
                              }
                              placeholder={field.placeholder || ""}
                            />
                          )}
                          {field.ayuda && (
                            <small className="field-help">{field.ayuda}</small>
                          )}
                        </label>
                      );
                    })}
                  </>
                )}
                {submitError && (
                  <p className="form-error" role="alert">
                    {submitError}
                  </p>
                )}
                <button
                  className="button button-primary button-large"
                  disabled={loadingMatter || !matterDetail}
                  type="submit"
                >
                  Continuar y elegir notaría{" "}
                  <Icon name="arrow-right" size={19} />
                </button>
              </form>
            )}

            {wizardStep === 3 && (
              <div className="notary-step">
                {notaries.length ? (
                  <div className="notary-grid">
                    {notaries.map((notary) => (
                      <button
                        key={notary.directorio_id}
                        className={`notary-card ${selectedDirectory === notary.directorio_id ? "is-selected" : ""}`}
                        type="button"
                        onClick={() => {
                          setSelectedDirectory(notary.directorio_id);
                          setPaymentProvider(notary.medios_pago?.[0] || "");
                        }}
                      >
                        <span className="notary-icon">
                          <Icon name="building" size={23} />
                        </span>
                        <span>
                          <strong>{notary.nombre_fantasia}</strong>
                          <small>{notary.direccion}</small>
                          <small>{notary.comuna}</small>
                        </span>
                        <span className="notary-price">
                          ${Number(notary.precio).toLocaleString("es-CL")}
                        </span>
                        {selectedDirectory === notary.directorio_id && (
                          <span className="notary-check">
                            <Icon name="check" size={14} />
                          </span>
                        )}
                      </button>
                    ))}
                  </div>
                ) : (
                  <p className="empty-state">
                    {notaryAvailability ||
                      "No hay notarías disponibles para este documento."}
                  </p>
                )}
                <label className="wizard-check">
                  <input
                    type="checkbox"
                    checked={acceptedTerms}
                    onChange={(event) => setAcceptedTerms(event.target.checked)}
                  />{" "}
                  <span>
                    Acepto los términos, la política de privacidad y el
                    tratamiento de datos necesario para preparar este trámite.
                  </span>
                </label>
                <Turnstile onToken={setCaptchaToken} />
                {submitError && (
                  <p className="form-error" role="alert">
                    {submitError}
                  </p>
                )}
                <div className="wizard-actions">
                  <button
                    className="button button-secondary"
                    type="button"
                    onClick={() => {
                      setSubmitError("");
                      setWizardStep(2);
                    }}
                  >
                    Volver
                  </button>
                  <button
                    className="button button-primary"
                    type="button"
                    disabled={
                      submitting || !selectedDirectory || !acceptedTerms || !captchaToken
                    }
                    onClick={createSale}
                  >
                    {submitting ? "Guardando…" : "Continuar al pago"}{" "}
                    <Icon name="arrow-right" size={18} />
                  </button>
                </div>
              </div>
            )}

            {wizardStep === 4 && submitted && saleResult && (
              <div className="wizard-success">
                <span className="success-icon">
                  <Icon name="check" size={34} />
                </span>
                <span className="section-kicker">Datos guardados</span>
                <h2>Tu trámite ya comenzó.</h2>
                <p>
                  Folio <strong>{saleResult.folio}</strong>. Puedes crear una
                  cuenta para hacer seguimiento o continuar sin registrarte.
                </p>
                <PaymentSelector
                  providers={notaries.find((item) => item.directorio_id === selectedDirectory)?.medios_pago || []}
                  selected={paymentProvider}
                  onSelect={setPaymentProvider}
                />
                {!accountOpen ? (
                  <div className="account-choice">
                    <button
                      className="button button-secondary"
                      type="button"
                      onClick={() => setAccountOpen(true)}
                    >
                      Crear una cuenta
                    </button>
                    <button
                      className="button button-primary"
                      type="button"
                      disabled={submitting || !paymentProvider}
                      onClick={startPayment}
                    >
                      {submitting ? "Preparando pago…" : "Continuar sin cuenta"}{" "}
                      <Icon name="arrow-right" size={18} />
                    </button>
                  </div>
                ) : (
                  <form
                    className="optional-account-form"
                    onSubmit={createOptionalAccount}
                  >
                    <h3>Crea tu acceso opcional</h3>
                    <p>Usaremos el mismo correo informado en el trámite.</p>
                    <label>
                      Contraseña
                      <input
                        name="password"
                        type="password"
                        minLength={12}
                        required
                        autoComplete="new-password"
                      />
                      <small>Mínimo 12 caracteres.</small>
                    </label>
                    <label>
                      Repite la contraseña
                      <input
                        name="confirm_password"
                        type="password"
                        minLength={12}
                        required
                        autoComplete="new-password"
                      />
                    </label>
                    {accountError && (
                      <p className="form-error">{accountError}</p>
                    )}
                    <div className="wizard-actions">
                      <button
                        className="button button-secondary"
                        type="button"
                        onClick={() => setAccountOpen(false)}
                      >
                        Ahora no
                      </button>
                      <button
                        className="button button-primary"
                        disabled={submitting}
                      >
                        {submitting ? "Creando…" : "Crear cuenta"}
                      </button>
                    </div>
                  </form>
                )}
                {submitError && (
                  <p className="form-error" role="alert">
                    {submitError}
                  </p>
                )}
              </div>
            )}
          </section>
        </div>
      )}
    </>
  );
}
