/* app.jsx - Acacias Capital landing */

const { useEffect, useRef, useState } = React;

const HERO_IMAGES = {
  shard:
    "https://images.unsplash.com/photo-1486299267070-83823f5448dd?auto=format&fit=crop&w=2400&q=80",
  canary:
    "https://images.unsplash.com/photo-1529655683826-aba9b3e77383?auto=format&fit=crop&w=2400&q=80",
  city:
    "https://images.unsplash.com/photo-1513635269975-59663e0ac1ad?auto=format&fit=crop&w=2400&q=80",
  thames:
    "https://images.unsplash.com/photo-1520986606214-8b456906c813?auto=format&fit=crop&w=2400&q=80",
};

const TILE_IMAGES = [
  "https://images.unsplash.com/photo-1545324418-cc1a3fa10c00?auto=format&fit=crop&w=1600&q=80",
  "https://images.unsplash.com/photo-1586528116311-ad8dd3c8310d?auto=format&fit=crop&w=1600&q=80",
  "https://images.unsplash.com/photo-1486718448742-163732cd1544?auto=format&fit=crop&w=1600&q=80",
  "https://images.unsplash.com/photo-1582719508461-905c673771fd?auto=format&fit=crop&w=1600&q=80",
];

const CTA_IMAGE =
  "https://images.unsplash.com/photo-1448630360428-65456885c650?auto=format&fit=crop&w=2400&q=80";

const BROCHURE_PATH = "acacias-brochure.pdf";
const BROCHURE_FILENAME = "Acacias-Capital-Brochure.pdf";
const CALENDAR_EMBED_URL =
  "https://calendar.google.com/calendar/appointments/schedules/AcZssZ10Y1rVF4x9-UE_GrDY_dfPBE6pfgNypHYPEpvWdFV8O16qZqsZo2pEvbaoBfcpkur1uxS6k98O?gv=true";
const INTRO_VIDEO_PATH = "acacias-intro.mp4";
const LANGUAGE_STORAGE_KEY = "acacias_language";
const FOUNDER_IMAGE = "founder-jaime-moreno.png";
const JORGE_IMAGE = "jorge-morgado.png";
const SEBASTIAN_IMAGE = "sebastian-martinez.png";
const PEDRO_IMAGE = "pedro-trueba.png";

const COPY = {
  es: {
    nav: {
      services: "Servicios",
      mandates: "Mandatos",
      approach: "Enfoque",
      team: "Equipo",
      contact: "Contacto",
      privateOffice: "Private Office",
      login: "Ingresar",
      menuLabel: "Abrir menu",
      languageLabel: "Cambiar idioma",
    },
    hero: {
      eyebrow: "Independent Advisory for Latinamerican Capital",
      title: "Capital con perspectiva global.",
      body:
        "Asesoría independiente para clientes latinoamericanos en activos alternativos en Reino Unido y mercados seleccionados. Análisis riguroso. Ejecución completa. Intereses alineados. Pensado para el capital privado, con visión generacional, que mide décadas y no trimestres.",
      cta: "Explorar Acacias",
      brochureCta: "Descargar Brochure",
      videoCta: "Ver video",
      scroll: "Scroll to explore",
      modalEyebrow: "Brochure corporativo",
      modalTitle: "Recibe la presentacion de Acacias.",
      modalBody: "Comparte tus datos y descargaremos el brochure corporativo de forma inmediata.",
      nameLabel: "Nombre",
      emailLabel: "Correo electronico",
      closeLabel: "Cerrar formulario",
      requiredError: "Completa nombre y correo electronico para descargar el brochure.",
      emailError: "Ingresa un correo electronico valido.",
      submitError: "No pudimos registrar tus datos.",
      fallbackError: "No pudimos registrar tus datos. Intentalo nuevamente.",
      success: "Datos recibidos. Iniciando descarga...",
      submitting: "Registrando...",
    },
    introVideo: {
      title: "Acacias Capital",
      closeLabel: "Cerrar video de introduccion",
    },
    statement: {
      eyebrow: "Nuestro enfoque",
      title: "Asesoría imparcial. Intereses alineados.",
      body:
        "No representamos desarrolladores ni agentes. No administramos capital bajo un mandato discrecional. Buscamos en todo el mercado, evaluamos con criterios independientes y estructuramos cada operación desde la perspectiva del cliente.",
      imageLabel: "Arquitectura moderna en Londres",
    },
    services: {
      eyebrow: "Servicios",
      title: "Conviccion antes que volumen.",
      body:
        "Cada inversión comienza con una conversacion y avanza con debida diligencia, coordinacion transfronteriza y criterio independiente.",
      moreCta: "Conocer mas",
      contactCta: "Solicitar contacto",
      items: [
        {
          n: "01",
          title: "Property Advisory",
          body:
            "Identificamos, evaluamos y estructuramos oportunidades inmobiliarias residenciales, lifestyle, comerciales, industriales y generadoras de renta.",
          cta: "Ver proyectos",
          disabled: true,
        },
        {
          n: "02",
          title: "Alternative Assets",
          body:
            "Acceso a deuda inmobiliaria, oro físico y deuda privada estructurada para inversores internacionales, con documentación formal.",
        },
        {
          n: "03",
          title: "Private Office",
          body:
            "Co-inversión privada para un grupo reducido de clientes internacionales. Un servicio selectivo disponible exclusivamente por invitación.",
          id: "private-office",
        },
      ],
    },
    mandates: {
      eyebrow: "Mandatos activos",
      title: "Real estate, sin fronteras.",
      body:
        "Una selección representativa de activos asesorados por Acacias. Reino Unido y mercados seleccionados. Los detalles completos, precios y términos se comparten mediante consulta directa y acuerdo de confidencialidad.",
      cta: "Consultar mandatos",
    },
    metrics: [
      ["£100M+", "Transacciones asesoradas"],
      ["£200K-£20M", "Rango de operaciones"],
      ["2", "Continentes"],
      ["2", "Hubs internacionales"],
    ],
    vision: {
      eyebrow: "Vision transfronteriza",
      title: "Una firma de Londres. Una perspectiva global.",
      body:
        "Con socios en Londres, Madrid y Santiago, combinamos profundidad de mercado local con la fluidez cultural que requieren familias e inversores internacionales.",
      cta: "Hablar con nosotros",
    },
    team: {
      eyebrow: "Equipo",
      title: "Una nota del fundador",
      founderName: "Jaime Moreno",
      founderLabel: "Fundador, Acacias Capital",
      founderLinkedin:
        "https://www.linkedin.com/in/jaimemorenom?utm_source=share_via&utm_content=profile&utm_medium=member_ios",
      imageAlt: "Fundador de Acacias Capital",
      paragraphs: [
        "Acacias nace para conectar dos mundos que históricamente han estado separados: el capital latinoamericano y el mercado inmobiliario del Reino Unido.",
        "Después de años trabajando en mercados de capitales e inversión entre América Latina y Europa, vi una necesidad clara: muchos inversionistas latinoamericanos quieren invertir en Reino Unido, pero enfrentan un mercado desconocido, estructuras legales complejas y asesores que muchas veces tienen incentivos comerciales propios.",
        "Acacias fue creada sobre una premisa distinta: ofrecer asesoría independiente, sin conflictos de interés y sin agendas ocultas.",
        "No somos un fondo. No somos un banco. El capital permanece siempre bajo control del cliente. Nuestro rol es asesorar con independencia, criterio y alineación total de intereses.",
        "Elegimos el nombre Acacias por su significado. La acacia fue asociada históricamente a la incorruptibilidad; en griego, akakia significa ausencia de malicia. Pureza de intención. Actuar sin agenda oculta.",
        "Ese es el estándar con el que trabajamos.",
      ],
      membersTitle: "Resto del equipo",
      members: [
        [
          "Jorge Morgado A.",
          "Socio Chile",
          "Experiencia en originación de negocios, estructuración y distribución de oportunidades de inversión, con foco en clientes institucionales y family offices.",
          "https://www.linkedin.com/in/jm2022?utm_source=share_via&utm_content=profile&utm_medium=member_ios",
          JORGE_IMAGE,
        ],
        [
          "Sebastián Martínez L.",
          "Socio Chile",
          "Acompaña a clientes latinoamericanos durante todo el ciclo de inversión: definición de mandato, KYC, estructuras transfronterizas, seguimiento de portafolio y coordinación de salida.",
          "https://www.linkedin.com/in/samartil?utm_source=share_via&utm_content=profile&utm_medium=member_ios",
          SEBASTIAN_IMAGE,
        ],
        [
          "Pedro Trueba",
          "Socio España",
          "Experiencia en banca internacional en España, México y Chile. Abogado colegiado en Madrid y fundador de Peñalara Financial Strategies, combina mirada financiera y legal para inversión internacional.",
          "https://www.linkedin.com/in/pedrotrueba-divisas/",
          PEDRO_IMAGE,
        ],
      ],
    },
    contact: {
      eyebrow: "Contacto",
      title: "Cada inversión empieza con una conversación.",
      body:
        "Todas las consultas son tratadas con estricta confidencialidad. Cuentenos tus planes y coordinaremos una llamada.",
      cta: "Contactar",
      submitCta: "Enviar solicitud",
      email: "info@acaciascapital.com",
      scheduleCta: "Agendar llamada",
      modalEyebrow: "Contacto privado",
      modalTitle: "Comparte tus datos y te escribiremos.",
      modalBody:
        "Déjanos tu nombre y correo para que el equipo de Acacias te contacte de forma confidencial.",
      nameLabel: "Nombre",
      emailLabel: "Correo electronico",
      closeLabel: "Cerrar formulario",
      requiredError: "Completa nombre y correo electronico para continuar.",
      emailError: "Ingresa un correo electronico valido.",
      submitError: "No pudimos enviar tu solicitud.",
      fallbackError: "No pudimos enviar tu solicitud. Intentalo nuevamente.",
      success: "Solicitud enviada. Te contactaremos pronto.",
      submitting: "Enviando...",
      location: "London, United Kingdom",
      company:
        "Acacias Capital Ltd · Company No. 10715824\nRegistrada en Inglaterra y Gales.",
    },
    calendar: {
      title: "Agendar llamada",
      eyebrow: "Calendario",
      closeLabel: "Cerrar calendario",
    },
    chatbot: {
      toggle: "¿Tienes una pregunta?",
      title: "Asistente Acacias",
      subtitle: "Preguntas frecuentes",
      closeLabel: "Cerrar asistente",
      greeting:
        "Hola. Puedo ayudarte con preguntas generales sobre Acacias, nuestro enfoque y cómo iniciar una conversación.",
      questionsTitle: "Preguntas sugeridas",
      disclaimer:
        "Información general. No constituye asesoría financiera, legal ni tributaria.",
      actions: {
        brochure: "Descargar brochure",
        schedule: "Agendar llamada",
        contact: "Contactar",
      },
      items: [
        {
          id: "what",
          question: "¿Qué hace Acacias Capital?",
          answer:
            "Acacias Capital ofrece asesoría independiente para clientes latinoamericanos e internacionales que evalúan inversiones en activos alternativos, especialmente en Reino Unido y mercados seleccionados.",
        },
        {
          id: "investors",
          question: "¿Para qué tipo de inversionistas trabajan?",
          answer:
            "Trabajamos con familias, family offices e inversionistas sofisticados que buscan una mirada independiente, alineada y de largo plazo para operaciones transfronterizas.",
        },
        {
          id: "markets",
          question: "¿En qué mercados opera Acacias?",
          answer:
            "La firma tiene base en Londres y socios en Madrid y Santiago. El foco principal está en Reino Unido, con perspectiva hacia mercados seleccionados según cada mandato.",
        },
        {
          id: "capital",
          question: "¿Acacias administra mi capital?",
          answer:
            "No. Acacias no es un fondo ni un banco. El capital permanece bajo control del cliente; nuestro rol es asesorar con independencia durante el análisis, estructuración y ejecución.",
        },
        {
          id: "process",
          question: "¿Cómo funciona el proceso de inversión?",
          answer:
            "Todo comienza con una conversación privada. Luego se define el mandato, se evalúan oportunidades, se realiza debida diligencia y se coordina la ejecución con asesores especializados cuando corresponde.",
        },
        {
          id: "call",
          question: "¿Puedo agendar una llamada?",
          answer:
            "Sí. Puedes agendar una llamada privada desde el botón de agenda o escribirnos directamente para coordinar una conversación confidencial.",
        },
        {
          id: "brochure",
          question: "¿Dónde descargo el brochure?",
          answer:
            "Puedes descargar el brochure corporativo desde el botón del Hero o desde este asistente. Te pediremos datos básicos para registrar la solicitud.",
        },
        {
          id: "advice",
          question: "¿La información es asesoría financiera?",
          answer:
            "No. La información pública del sitio es general. Cualquier análisis específico requiere una conversación privada y revisión del perfil, objetivos y restricciones del cliente.",
        },
      ],
    },
    footer:
      "Acacias Capital Ltd no esta autorizada ni regulada por la FCA. Capital en riesgo. Solo para inversores sofisticados no residentes en el Reino Unido.",
  },
  en: {
    nav: {
      services: "Services",
      mandates: "Mandates",
      approach: "Approach",
      team: "Team",
      contact: "Contact",
      privateOffice: "Private Office",
      login: "Sign in",
      menuLabel: "Open menu",
      languageLabel: "Change language",
    },
    hero: {
      eyebrow: "Independent Advisory for Latinamerican Capital",
      title: "Capital with a global perspective.",
      body:
        "Independent advisory for Latin American clients investing in alternative assets across the United Kingdom and selected markets. Rigorous analysis. Complete execution. Aligned interests. Designed for private capital with a generational view, measured in decades rather than quarters.",
      cta: "Explore Acacias",
      brochureCta: "Download Brochure",
      videoCta: "Watch video",
      scroll: "Scroll to explore",
      modalEyebrow: "Corporate brochure",
      modalTitle: "Receive the Acacias presentation.",
      modalBody: "Share your details and the corporate brochure will download immediately.",
      nameLabel: "Name",
      emailLabel: "Email",
      closeLabel: "Close form",
      requiredError: "Complete your name and email to download the brochure.",
      emailError: "Enter a valid email address.",
      submitError: "We could not register your details.",
      fallbackError: "We could not register your details. Please try again.",
      success: "Details received. Starting download...",
      submitting: "Registering...",
    },
    introVideo: {
      title: "Acacias Capital",
      closeLabel: "Close introduction video",
    },
    statement: {
      eyebrow: "Our Approach",
      title: "Impartial advice. Aligned interests.",
      body:
        "We do not represent developers or agents. We do not manage capital under a discretionary mandate. We search across the market, assess opportunities independently and structure each transaction from the client's perspective.",
      imageLabel: "Modern architecture in London",
    },
    services: {
      eyebrow: "Services",
      title: "Conviction before volume.",
      body:
        "Each investment begins with a conversation and advances through due diligence, cross-border coordination and independent judgement.",
      moreCta: "Learn more",
      contactCta: "Request contact",
      items: [
        {
          n: "01",
          title: "Property Advisory",
          body:
            "We identify, assess and structure residential, lifestyle, commercial, industrial and income-generating real estate opportunities.",
          cta: "View projects",
          disabled: true,
        },
        {
          n: "02",
          title: "Alternative Assets",
          body:
            "Access to real estate debt, physical gold and structured private credit for international investors, with formal documentation.",
        },
        {
          n: "03",
          title: "Private Office",
          body:
            "Private co-investment for a select group of international clients. A selective service available by invitation only.",
          id: "private-office",
        },
      ],
    },
    mandates: {
      eyebrow: "Active Mandates",
      title: "Real estate, without borders.",
      body:
        "A representative selection of assets advised by Acacias. The United Kingdom and selected markets. Full details, pricing and terms are shared through direct consultation and confidentiality agreement.",
      cta: "Review mandates",
    },
    metrics: [
      ["£100M+", "Advised transactions"],
      ["£200K-£20M", "Transaction range"],
      ["2", "Continents"],
      ["2", "International hubs"],
    ],
    vision: {
      eyebrow: "Cross-border vision",
      title: "A London firm. A global perspective.",
      body:
        "With partners in London, Madrid and Santiago, we combine deep local market knowledge with the cultural fluency required by families and international investors.",
      cta: "Speak with us",
    },
    team: {
      eyebrow: "Team",
      title: "A note from the founder",
      founderName: "Jaime Moreno",
      founderLabel: "Founder, Acacias Capital",
      founderLinkedin:
        "https://www.linkedin.com/in/jaimemorenom?utm_source=share_via&utm_content=profile&utm_medium=member_ios",
      imageAlt: "Founder of Acacias Capital",
      paragraphs: [
        "Acacias was created to connect two worlds that have historically remained separate: Latin American capital and the United Kingdom real estate market.",
        "After years working across capital markets and investment between Latin America and Europe, I saw a clear need: many Latin American investors want to invest in the United Kingdom, but face an unfamiliar market, complex legal structures and advisers who often have commercial incentives of their own.",
        "Acacias was built on a different premise: to offer independent advice, free from conflicts of interest and hidden agendas.",
        "We are not a fund. We are not a bank. Capital always remains under the client's control. Our role is to advise with independence, judgement and full alignment of interests.",
        "We chose the name Acacias for its meaning. The acacia has historically been associated with incorruptibility; in Greek, akakia means absence of malice. Purity of intention. Acting without a hidden agenda.",
        "That is the standard by which we work.",
      ],
      membersTitle: "The wider team",
      members: [
        [
          "Jorge Morgado A.",
          "Partner Chile",
          "Experience in business origination, structuring and distribution of investment opportunities, with a focus on institutional clients and family offices.",
          "https://www.linkedin.com/in/jm2022?utm_source=share_via&utm_content=profile&utm_medium=member_ios",
          JORGE_IMAGE,
        ],
        [
          "Sebastián Martínez L.",
          "Partner Chile",
          "Supports Latin American clients across the full investment lifecycle: mandate scoping, KYC, cross-border structures, portfolio reporting and exit coordination.",
          "https://www.linkedin.com/in/samartil?utm_source=share_via&utm_content=profile&utm_medium=member_ios",
          SEBASTIAN_IMAGE,
        ],
        [
          "Pedro Trueba",
          "Partner Spain",
          "Extensive experience in international banking across Spain, Mexico and Chile. A registered solicitor with the Madrid Bar and founder of Peñalara Financial Strategies, Pedro combines financial and legal expertise for international investment.",
          "https://www.linkedin.com/in/pedrotrueba-divisas/",
          PEDRO_IMAGE,
        ],
      ],
    },
    contact: {
      eyebrow: "Contact",
      title: "Every investment starts with a conversation.",
      body:
        "All enquiries are handled with strict confidentiality. Tell us about your plans and we will coordinate a call.",
      cta: "Contact",
      submitCta: "Send request",
      email: "info@acaciascapital.com",
      scheduleCta: "Schedule a call",
      modalEyebrow: "Private contact",
      modalTitle: "Share your details and we will get in touch.",
      modalBody:
        "Leave your name and email so the Acacias team can contact you confidentially.",
      nameLabel: "Name",
      emailLabel: "Email",
      closeLabel: "Close form",
      requiredError: "Complete your name and email to continue.",
      emailError: "Enter a valid email address.",
      submitError: "We could not send your request.",
      fallbackError: "We could not send your request. Please try again.",
      success: "Request sent. We will contact you soon.",
      submitting: "Sending...",
      location: "London, United Kingdom",
      company:
        "Acacias Capital Ltd · Company No. 10715824\nRegistered in England and Wales.",
    },
    calendar: {
      title: "Schedule a call",
      eyebrow: "Calendar",
      closeLabel: "Close calendar",
    },
    chatbot: {
      toggle: "Have a question?",
      title: "Acacias Assistant",
      subtitle: "Frequently asked questions",
      closeLabel: "Close assistant",
      greeting:
        "Hello. I can help with general questions about Acacias, our approach and how to start a conversation.",
      questionsTitle: "Suggested questions",
      disclaimer:
        "General information only. This is not financial, legal or tax advice.",
      actions: {
        brochure: "Download brochure",
        schedule: "Schedule a call",
        contact: "Contact",
      },
      items: [
        {
          id: "what",
          question: "What does Acacias Capital do?",
          answer:
            "Acacias Capital provides independent advisory for Latin American and international clients evaluating alternative asset investments, especially across the United Kingdom and selected markets.",
        },
        {
          id: "investors",
          question: "What type of investors do you work with?",
          answer:
            "We work with families, family offices and sophisticated investors seeking independent, aligned and long-term judgement for cross-border transactions.",
        },
        {
          id: "markets",
          question: "Which markets does Acacias cover?",
          answer:
            "The firm is based in London with partners in Madrid and Santiago. The primary focus is the United Kingdom, with a selective view across other markets depending on each mandate.",
        },
        {
          id: "capital",
          question: "Does Acacias manage my capital?",
          answer:
            "No. Acacias is not a fund or a bank. Capital remains under the client's control; our role is to advise independently through analysis, structuring and execution.",
        },
        {
          id: "process",
          question: "How does the investment process work?",
          answer:
            "It begins with a private conversation. We then define the mandate, assess opportunities, conduct due diligence and coordinate execution with specialist advisers when appropriate.",
        },
        {
          id: "call",
          question: "Can I schedule a call?",
          answer:
            "Yes. You can schedule a private call from the calendar button or contact us directly to coordinate a confidential conversation.",
        },
        {
          id: "brochure",
          question: "Where can I download the brochure?",
          answer:
            "You can download the corporate brochure from the Hero button or from this assistant. We request basic details to register the enquiry.",
        },
        {
          id: "advice",
          question: "Is this financial advice?",
          answer:
            "No. Public information on this website is general. Specific analysis requires a private conversation and review of the client's profile, objectives and constraints.",
        },
      ],
    },
    footer:
      "Acacias Capital Ltd is not authorised or regulated by the FCA. Capital at risk. For sophisticated investors not resident in the United Kingdom only.",
  },
};

const SPANISH_REGIONS = new Set([
  "AR",
  "BO",
  "CL",
  "CO",
  "CR",
  "CU",
  "DO",
  "EC",
  "ES",
  "GT",
  "HN",
  "MX",
  "NI",
  "PA",
  "PE",
  "PY",
  "SV",
  "UY",
  "VE",
]);

const SPANISH_TIMEZONE_HINTS = [
  "Argentina",
  "Bogota",
  "Caracas",
  "Guatemala",
  "La_Paz",
  "Lima",
  "Mexico",
  "Montevideo",
  "Santiago",
];

function normalizeLanguage(value) {
  return value === "en" || value === "es" ? value : null;
}

function languageFromLocale(locale) {
  if (!locale) return null;
  const normalized = locale.replace("_", "-");
  const [language, region] = normalized.split("-");
  if (language === "es") return "es";
  if (language === "en") return "en";
  if (region && SPANISH_REGIONS.has(region.toUpperCase())) return "es";
  return null;
}

function detectInitialLanguage() {
  if (typeof window === "undefined") return "en";

  const urlLanguage = normalizeLanguage(new URLSearchParams(window.location.search).get("lang"));
  if (urlLanguage) return urlLanguage;

  let saved = null;
  try {
    saved = normalizeLanguage(window.localStorage.getItem(LANGUAGE_STORAGE_KEY));
  } catch (error) {
    saved = null;
  }
  if (saved) return saved;

  const regionalLanguage = normalizeLanguage(new URLSearchParams(window.location.search).get("autoLang"));
  if (regionalLanguage) return regionalLanguage;

  const browserLanguages = (navigator.languages || [navigator.language]).map(languageFromLocale);
  if (browserLanguages.includes("es")) return "es";

  const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone || "";
  if (SPANISH_TIMEZONE_HINTS.some((hint) => timeZone.includes(hint))) return "es";

  if (browserLanguages.includes("en")) return "en";

  return "en";
}

function useInView(options = { threshold: 0.13 }) {
  const ref = useRef(null);
  const [seen, setSeen] = useState(false);

  useEffect(() => {
    if (!ref.current || seen) return undefined;

    const observer = new IntersectionObserver((entries) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          setSeen(true);
          observer.disconnect();
        }
      });
    }, options);

    observer.observe(ref.current);
    return () => observer.disconnect();
  }, [seen]);

  return [ref, seen];
}

function Reveal({ children, as: As = "div", className = "" }) {
  const [ref, seen] = useInView();
  return (
    <As ref={ref} className={`reveal ${seen ? "show" : ""} ${className}`.trim()}>
      {children}
    </As>
  );
}

function BrandMark() {
  return (
    <svg viewBox="0 0 28 28" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
      <path d="M14 2 V26" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round" opacity="0.55" />
      {[4, 8, 12, 16, 20].map((y, i) => {
        const w = 8 - i * 0.6;
        return (
          <g key={y} opacity={1 - i * 0.04}>
            <ellipse cx={14 - w / 2 - 1} cy={y + 1} rx={w / 2} ry="1.4" fill="currentColor" opacity="0.85" />
            <ellipse cx={14 + w / 2 + 1} cy={y + 1} rx={w / 2} ry="1.4" fill="currentColor" opacity="0.85" />
          </g>
        );
      })}
    </svg>
  );
}

function LinkedInIcon() {
  return (
    <svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">
      <path
        fill="currentColor"
        d="M6.94 8.98H3.82V20h3.12V8.98ZM5.38 4a1.82 1.82 0 1 0 0 3.64A1.82 1.82 0 0 0 5.38 4Zm14.8 9.66c0-3.04-1.62-4.45-3.79-4.45a3.26 3.26 0 0 0-2.94 1.62h-.04V8.98h-2.99V20h3.12v-5.46c0-1.44.27-2.83 2.05-2.83 1.76 0 1.78 1.64 1.78 2.92V20h3.12v-6.34Z"
      />
    </svg>
  );
}

function LanguageSwitch({ language, onLanguageChange, label }) {
  return (
    <div className="language-switch" aria-label={label}>
      {["es", "en"].map((code) => (
        <button
          key={code}
          type="button"
          className={language === code ? "active" : ""}
          aria-pressed={language === code}
          onClick={() => onLanguageChange(code)}
        >
          {code.toUpperCase()}
        </button>
      ))}
    </div>
  );
}

function Nav({ t, language, onLanguageChange }) {
  const [scrolled, setScrolled] = useState(false);
  const [open, setOpen] = useState(false);

  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 32);
    window.addEventListener("scroll", onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  const close = () => setOpen(false);

  return (
    <header className={`nav ${scrolled ? "scrolled" : ""}`}>
      <a className="logo" href="#inicio" onClick={close}>
        <span className="logo-mark"><BrandMark /></span>
        ACACIAS<span>.</span>
      </a>
      <nav className={`navlinks ${open ? "open" : ""}`}>
        <a href="#servicios" onClick={close}>{t.nav.services}</a>
        <a href="#propiedades" onClick={close}>{t.nav.mandates}</a>
        <a href="#enfoque" onClick={close}>{t.nav.approach}</a>
        <a href="#equipo" onClick={close}>{t.nav.team}</a>
        <a href="#contacto" onClick={close}>{t.nav.contact}</a>
        <a href="#private-office" onClick={close}>{t.nav.privateOffice}</a>
        <LanguageSwitch
          language={language}
          onLanguageChange={onLanguageChange}
          label={t.nav.languageLabel}
        />
        <a className="login-cta" href="/login" target="_top" onClick={close}>{t.nav.login}</a>
      </nav>
      <button
        className={`burger ${open ? "open" : ""}`}
        aria-label={t.nav.menuLabel}
        onClick={() => setOpen((value) => !value)}
      >
        <i />
        <i />
        <i />
      </button>
    </header>
  );
}

function Hero({ t, language, onVideoOpen }) {
  const [showLeadForm, setShowLeadForm] = useState(false);
  const [leadName, setLeadName] = useState("");
  const [leadEmail, setLeadEmail] = useState("");
  const [leadStatus, setLeadStatus] = useState("idle");
  const [leadError, setLeadError] = useState("");

  const downloadBrochure = () => {
    const link = document.createElement("a");
    link.href = BROCHURE_PATH;
    link.download = BROCHURE_FILENAME;
    document.body.appendChild(link);
    link.click();
    link.remove();
  };

  const resetLeadForm = () => {
    if (leadStatus === "submitting") return;
    setShowLeadForm(false);
    setLeadStatus("idle");
    setLeadError("");
  };

  const submitLead = async (event) => {
    event.preventDefault();
    const name = leadName.trim();
    const email = leadEmail.trim().toLowerCase();

    if (!name || !email) {
      setLeadError(t.hero.requiredError);
      return;
    }

    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
      setLeadError(t.hero.emailError);
      return;
    }

    setLeadStatus("submitting");
    setLeadError("");

    try {
      const response = await fetch("/api/brochure-leads", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          name,
          email,
          source: `hero_brochure_${language}`,
        }),
      });

      const payload = await response.json().catch(() => ({}));

      if (!response.ok) {
        throw new Error(payload.error || t.hero.submitError);
      }

      setLeadStatus("success");
      downloadBrochure();
      window.setTimeout(() => {
        setShowLeadForm(false);
        setLeadStatus("idle");
      }, 1200);
    } catch (error) {
      setLeadStatus("idle");
      setLeadError(error.message || t.hero.fallbackError);
    }
  };

  return (
    <section className="hero" id="inicio">
      <div className="media" style={{ backgroundImage: `url(${HERO_IMAGES.shard})` }} aria-hidden="true" />
      <div className="shade" />
      <Reveal className="content">
        <div className="eyebrow">{t.hero.eyebrow}</div>
        <h1>{t.hero.title}</h1>
        <p className="sub">
          {t.hero.body}
        </p>
        <div className="hero-actions">
          <a className="btn" href="#servicios">
            {t.hero.cta} <span className="arrow">→</span>
          </a>
          <button className="btn gold" type="button" onClick={() => setShowLeadForm(true)}>
            {t.hero.brochureCta} <span className="arrow">↓</span>
          </button>
        </div>
        <button className="hero-video-link" type="button" onClick={onVideoOpen}>
          {t.hero.videoCta} <span className="arrow">→</span>
        </button>
      </Reveal>
      <div className="scroll">{t.hero.scroll}</div>

      {showLeadForm && (
        <div className="lead-modal" role="dialog" aria-modal="true" aria-labelledby="brochure-title">
          <button className="lead-backdrop" type="button" aria-label={t.hero.closeLabel} onClick={resetLeadForm} />
          <form className="lead-card" onSubmit={submitLead}>
            <button className="lead-close" type="button" aria-label={t.hero.closeLabel} onClick={resetLeadForm}>
              X
            </button>
            <div className="eyebrow">{t.hero.modalEyebrow}</div>
            <h3 id="brochure-title">{t.hero.modalTitle}</h3>
            <p>
              {t.hero.modalBody}
            </p>
            <label>
              {t.hero.nameLabel}
              <input
                type="text"
                name="name"
                value={leadName}
                onChange={(event) => setLeadName(event.target.value)}
                autoComplete="name"
                required
              />
            </label>
            <label>
              {t.hero.emailLabel}
              <input
                type="email"
                name="email"
                value={leadEmail}
                onChange={(event) => setLeadEmail(event.target.value)}
                autoComplete="email"
                required
              />
            </label>
            {leadError && <p className="lead-message error">{leadError}</p>}
            {leadStatus === "success" && (
              <p className="lead-message success">{t.hero.success}</p>
            )}
            <button className="btn gold lead-submit" type="submit" disabled={leadStatus === "submitting"}>
              {leadStatus === "submitting" ? t.hero.submitting : t.hero.brochureCta}
            </button>
          </form>
        </div>
      )}
    </section>
  );
}

function Statement({ t }) {
  return (
    <section className="statement" id="enfoque">
      <Reveal className="statement-copy">
        <div className="eyebrow">{t.statement.eyebrow}</div>
        <h2>{t.statement.title}</h2>
        <p>
          {t.statement.body}
        </p>
      </Reveal>
      <div
        className="statement-img"
        style={{ backgroundImage: `url(${HERO_IMAGES.city})` }}
        role="img"
        aria-label={t.statement.imageLabel}
      />
    </section>
  );
}

function Services({ t }) {
  return (
    <section className="services" id="servicios">
      <Reveal className="services-head">
        <div>
          <div className="eyebrow">{t.services.eyebrow}</div>
          <h2>{t.services.title}</h2>
        </div>
        <p>
          {t.services.body}
        </p>
      </Reveal>
      <div className="grid">
        {t.services.items.map((item, index) => (
          <Reveal as="article" className="card" key={item.n}>
            <span id={item.id} className="num">{item.n}</span>
            <h3>{item.title}</h3>
            <p>{item.body}</p>
            {item.disabled ? (
              <span className="disabled-link">
                {item.cta || t.services.moreCta}
              </span>
            ) : (
              <a
                href={item.href || "#contacto"}
                target={item.href ? "_top" : undefined}
                rel={item.href ? "noopener noreferrer" : undefined}
              >
                {item.cta || (index === 2 ? t.services.contactCta : t.services.moreCta)} <span className="arrow">→</span>
              </a>
            )}
          </Reveal>
        ))}
      </div>
    </section>
  );
}

function Mandates({ t }) {
  return (
    <section className="chapter" id="propiedades">
      <div className="media" style={{ backgroundImage: `url(${HERO_IMAGES.thames})` }} aria-hidden="true" />
      <div className="shade" />
      <Reveal className="content">
        <div className="eyebrow">{t.mandates.eyebrow}</div>
        <h2>{t.mandates.title}</h2>
        <p>
          {t.mandates.body}
        </p>
        <a className="btn" href="#contacto">
          {t.mandates.cta} <span className="arrow">→</span>
        </a>
      </Reveal>
    </section>
  );
}

function Metrics({ t }) {
  return (
    <section className="metrics">
      {t.metrics.map(([value, label]) => (
        <Reveal className="metric" key={label}>
          <b>{value}</b>
          <span>{label}</span>
        </Reveal>
      ))}
    </section>
  );
}

function CrossBorder({ t }) {
  return (
    <section className="chapter right">
      <div className="media" style={{ backgroundImage: `url(${TILE_IMAGES[2]})` }} aria-hidden="true" />
      <div className="shade" />
      <Reveal className="content">
        <div className="eyebrow">{t.vision.eyebrow}</div>
        <h2>{t.vision.title}</h2>
        <p>
          {t.vision.body}
        </p>
        <a className="btn" href="#contacto">
          {t.vision.cta} <span className="arrow">→</span>
        </a>
      </Reveal>
    </section>
  );
}

function Team({ t }) {
  return (
    <section className="team" id="equipo">
      <Reveal className="team-copy">
        <div className="team-founder-grid">
          <div className="team-photo">
            <img src={FOUNDER_IMAGE} alt={t.team.imageAlt} />
            <div className="founder-identity">
              <strong>{t.team.founderName}</strong>
              <a
                className="founder-link"
                href={t.team.founderLinkedin}
                target="_blank"
                rel="noopener noreferrer"
                aria-label={`LinkedIn - ${t.team.founderName}`}
                title="LinkedIn"
              >
                <LinkedInIcon />
              </a>
            </div>
            <span>{t.team.founderLabel}</span>
          </div>
          <div>
            <div className="eyebrow">{t.team.eyebrow}</div>
            <h2>{t.team.title}</h2>
            <div className="founder-note">
              {t.team.paragraphs.map((paragraph) => (
                <p key={paragraph}>{paragraph}</p>
              ))}
            </div>
          </div>
        </div>
        <div className="team-members">
          <h3>{t.team.membersTitle}</h3>
          <div className="team-list">
            {t.team.members.map(([name, role, brief, linkedinUrl, imageUrl]) => (
              <article key={name}>
                {imageUrl ? (
                  <img className="team-member-photo" src={imageUrl} alt={name} />
                ) : (
                  <div
                    className="team-member-photo team-member-photo-placeholder"
                    aria-hidden="true"
                  >
                    <span />
                  </div>
                )}
                <strong>{name}</strong>
                <span>{role}</span>
                <p>{brief}</p>
                <a
                  className="linkedin-link"
                  href={linkedinUrl || "#linkedin-pendiente"}
                  target={linkedinUrl ? "_blank" : undefined}
                  rel={linkedinUrl ? "noopener noreferrer" : undefined}
                  aria-label={`LinkedIn - ${name}`}
                  title="LinkedIn"
                >
                  <LinkedInIcon />
                </a>
              </article>
            ))}
          </div>
        </div>
      </Reveal>
    </section>
  );
}

function Contact({ t, onContactOpen, onScheduleOpen }) {
  return (
    <section className="contact" id="contacto">
      <Reveal className="contact-copy">
        <div className="eyebrow">{t.contact.eyebrow}</div>
        <h2>{t.contact.title}</h2>
        <p>
          {t.contact.body}
        </p>
        <div className="contact-actions">
          <button className="btn dark" type="button" onClick={onContactOpen}>
            {t.contact.cta} <span className="arrow">→</span>
          </button>
          <button
            className="btn dark outline"
            type="button"
            onClick={onScheduleOpen}
          >
            {t.contact.scheduleCta} <span className="arrow">→</span>
          </button>
        </div>
      </Reveal>
      <aside className="contact-meta">
        <div className="eyebrow">{t.contact.location}</div>
        <a href={`mailto:${t.contact.email}`}>{t.contact.email}</a>
        <small>
          {t.contact.company.split("\n").map((line) => (
            <React.Fragment key={line}>
              {line}
              <br />
            </React.Fragment>
          ))}
        </small>
      </aside>
    </section>
  );
}

function ChatbotFaq({ t, onContactOpen, onScheduleOpen }) {
  const [isOpen, setIsOpen] = useState(false);
  const [activeId, setActiveId] = useState(t.chatbot.items[0].id);
  const activeItem =
    t.chatbot.items.find((item) => item.id === activeId) || t.chatbot.items[0];

  return (
    <aside className={`chatbot-faq ${isOpen ? "is-open" : ""}`} aria-live="polite">
      <button
        className="chatbot-toggle"
        type="button"
        aria-expanded={isOpen}
        aria-controls="acacias-chatbot-panel"
        onClick={() => setIsOpen((value) => !value)}
      >
        <span className="chatbot-toggle-dot" aria-hidden="true" />
        {t.chatbot.toggle}
      </button>

      {isOpen && (
        <div className="chatbot-panel" id="acacias-chatbot-panel" role="dialog" aria-label={t.chatbot.title}>
          <div className="chatbot-head">
            <div>
              <strong>{t.chatbot.title}</strong>
              <span>{t.chatbot.subtitle}</span>
            </div>
            <button
              className="chatbot-close"
              type="button"
              aria-label={t.chatbot.closeLabel}
              onClick={() => setIsOpen(false)}
            >
              ×
            </button>
          </div>

          <div className="chatbot-messages">
            <div className="chatbot-message assistant">{t.chatbot.greeting}</div>
            <div className="chatbot-message user">{activeItem.question}</div>
            <div className="chatbot-message assistant">{activeItem.answer}</div>
          </div>

          <div className="chatbot-questions">
            <span>{t.chatbot.questionsTitle}</span>
            {t.chatbot.items.map((item) => (
              <button
                key={item.id}
                className={item.id === activeItem.id ? "active" : ""}
                type="button"
                onClick={() => setActiveId(item.id)}
              >
                {item.question}
              </button>
            ))}
          </div>

          <div className="chatbot-actions">
            <a href={BROCHURE_PATH} download={BROCHURE_FILENAME}>
              {t.chatbot.actions.brochure}
            </a>
            <button
              type="button"
              onClick={() => {
                setIsOpen(false);
                onScheduleOpen();
              }}
            >
              {t.chatbot.actions.schedule}
            </button>
            <button
              type="button"
              onClick={() => {
                setIsOpen(false);
                onContactOpen();
              }}
            >
              {t.chatbot.actions.contact}
            </button>
          </div>

          <p className="chatbot-disclaimer">{t.chatbot.disclaimer}</p>
        </div>
      )}
    </aside>
  );
}

function CalendarPopup({ t, onClose }) {
  return (
    <div className="calendar-modal" role="dialog" aria-modal="true" aria-label={t.calendar.title}>
      <button
        className="calendar-backdrop"
        type="button"
        aria-label={t.calendar.closeLabel}
        onClick={onClose}
      />
      <div className="calendar-card">
        <div className="calendar-head">
          <div>
            <span>{t.calendar.eyebrow}</span>
            <h3>{t.calendar.title}</h3>
          </div>
          <button
            className="calendar-close"
            type="button"
            aria-label={t.calendar.closeLabel}
            onClick={onClose}
          >
            X
          </button>
        </div>
        <iframe
          className="calendar-frame"
          src={CALENDAR_EMBED_URL}
          title={t.calendar.title}
          loading="lazy"
        />
      </div>
    </div>
  );
}

function ContactPopup({ t, language, onClose }) {
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [status, setStatus] = useState("idle");
  const [error, setError] = useState("");

  const reset = () => {
    if (status === "submitting") return;
    onClose();
  };

  const submitContact = async (event) => {
    event.preventDefault();

    const trimmedName = name.trim();
    const normalizedEmail = email.trim().toLowerCase();

    if (!trimmedName || !normalizedEmail) {
      setError(t.contact.requiredError);
      return;
    }

    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(normalizedEmail)) {
      setError(t.contact.emailError);
      return;
    }

    setStatus("submitting");
    setError("");

    try {
      const response = await fetch("/api/contact-request", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          name: trimmedName,
          email: normalizedEmail,
          source: `contact_${language}`,
        }),
      });

      const payload = await response.json().catch(() => ({}));

      if (!response.ok) {
        throw new Error(payload.error || t.contact.submitError);
      }

      setStatus("success");
      window.setTimeout(() => {
        onClose();
      }, 1200);
    } catch (submissionError) {
      setStatus("idle");
      setError(submissionError.message || t.contact.fallbackError);
    }
  };

  return (
    <div className="lead-modal" role="dialog" aria-modal="true" aria-labelledby="contact-title">
      <button className="lead-backdrop" type="button" aria-label={t.contact.closeLabel} onClick={reset} />
      <form className="lead-card" onSubmit={submitContact}>
        <button className="lead-close" type="button" aria-label={t.contact.closeLabel} onClick={reset}>
          X
        </button>
        <div className="eyebrow">{t.contact.modalEyebrow}</div>
        <h3 id="contact-title">{t.contact.modalTitle}</h3>
        <p>
          {t.contact.modalBody}
        </p>
        <label>
          {t.contact.nameLabel}
          <input
            type="text"
            name="name"
            value={name}
            onChange={(event) => setName(event.target.value)}
            autoComplete="name"
            required
          />
        </label>
        <label>
          {t.contact.emailLabel}
          <input
            type="email"
            name="email"
            value={email}
            onChange={(event) => setEmail(event.target.value)}
            autoComplete="email"
            required
          />
        </label>
        {error && <p className="lead-message error">{error}</p>}
        {status === "success" && (
          <p className="lead-message success">{t.contact.success}</p>
        )}
        <button className="btn dark lead-submit" type="submit" disabled={status === "submitting"}>
          {status === "submitting" ? t.contact.submitting : t.contact.submitCta}
        </button>
      </form>
    </div>
  );
}

function IntroVideoPopup({ t, onClose }) {
  return (
    <div className="intro-video-modal" role="dialog" aria-modal="true" aria-label={t.introVideo.title}>
      <button
        className="intro-video-backdrop"
        type="button"
        aria-label={t.introVideo.closeLabel}
        onClick={onClose}
      />
      <div className="intro-video-card">
        <button
          className="intro-video-close"
          type="button"
          aria-label={t.introVideo.closeLabel}
          onClick={onClose}
        >
          X
        </button>
        <video
          src={INTRO_VIDEO_PATH}
          autoPlay
          muted
          playsInline
          controls
          preload="metadata"
        />
      </div>
    </div>
  );
}

function App() {
  const [language, setLanguage] = useState(detectInitialLanguage);
  const [showIntroVideo, setShowIntroVideo] = useState(false);
  const [showCalendar, setShowCalendar] = useState(false);
  const [showContactForm, setShowContactForm] = useState(false);
  const t = COPY[language] || COPY.en;

  const openCalendar = () => {
    setShowIntroVideo(false);
    setShowContactForm(false);
    setShowCalendar(true);
  };

  const openIntroVideo = () => {
    setShowCalendar(false);
    setShowContactForm(false);
    setShowIntroVideo(true);
  };

  const openContactForm = () => {
    setShowCalendar(false);
    setShowIntroVideo(false);
    setShowContactForm(true);
  };

  useEffect(() => {
    document.documentElement.lang = language;
    try {
      window.localStorage.setItem(LANGUAGE_STORAGE_KEY, language);
    } catch (error) {
      // La deteccion regional sigue funcionando aunque el navegador bloquee storage.
    }
  }, [language]);

  return (
    <>
      <Nav t={t} language={language} onLanguageChange={setLanguage} />
      <main>
        <Hero t={t} language={language} onVideoOpen={openIntroVideo} />
        <Statement t={t} />
        <Services t={t} />
        <Mandates t={t} />
        <Metrics t={t} />
        <CrossBorder t={t} />
        <Team t={t} />
        <Contact t={t} onContactOpen={openContactForm} onScheduleOpen={openCalendar} />
      </main>
      {showIntroVideo && (
        <IntroVideoPopup t={t} onClose={() => setShowIntroVideo(false)} />
      )}
      {showCalendar && (
        <CalendarPopup t={t} onClose={() => setShowCalendar(false)} />
      )}
      {showContactForm && (
        <ContactPopup t={t} language={language} onClose={() => setShowContactForm(false)} />
      )}
      <ChatbotFaq t={t} onContactOpen={openContactForm} onScheduleOpen={openCalendar} />
      <footer>
        <strong>© 2026 ACACIAS CAPITAL LTD.</strong>
        <span>
          {t.footer}
        </span>
      </footer>
    </>
  );
}

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<App />);
