/* global React, VmNav, VmFooter, VmPhoto, VmQuote, VmStat, VmIcon, VmCard, ItinEventBanner, NewsletterIntake */
const { useState, useEffect, useRef } = React;

/* ---------- Bilingual copy ---------- */
const COPY = {
  en: {
    nav: { itin: "Get an ITIN", banking: "Open a bank account", learn: "Learn", resources: "Resources", help: "Get help" },
    hero: {
      eyebrow: "For you and your family",
      title: "Your ITIN, your account, your future. We're with you.",
      lede: "Vesta helps you apply for your ITIN, open a bank account, and start saving, with real people on your side, in English or Spanish.",
      ctaPrimary: "Start your ITIN application",
      ctaSecondary: "Talk to a person",
    },
    privacy: {
      eyebrow: "What we promise",
      lines: [
        "We never share your information with ICE.",
        "Your documents are encrypted and stay with our IRS Acceptance Agent partners.",
        "You can stop and ask questions at any time, for free.",
      ],
    },
    journey: {
      eyebrow: "Your journey",
      title: "Wherever you're starting from, you deserve access to tools that help you build stability over time.",
      lede: "Many people start with a tax ID. But that's just the beginning. Vesta is with you for every step after.",
      steps: [
        { n: "01", label: "Tax & ITIN", body: "Get your tax ID and file your return, including Schedule C if you're self-employed. Our Certified Acceptance Agents handle the paperwork so you never have to mail a passport." },
        { n: "02", label: "Banking", body: "Open an ITIN-friendly bank account to save, send money home, and build a financial history in the US. We connect you only to banks we trust." },
        { n: "03", label: "Savings", body: "Start building an emergency fund so unexpected costs don't set you back. We'll walk you through savings options that work on any income." },
        { n: "04", label: "Retirement", body: "Plan for long-term financial security with IRAs and employer savings, tools built for ITIN holders, not just Social Security number holders." },
      ],
    },
    whatYouGet: {
      eyebrow: "Your journey",
      headline: "Everything you need to build your financial future.",
      lede: "Many people start with a tax ID. But that's just the beginning. Vesta is with you for every step after.",
      cta: "Check your fit",
      items: [
        { num: "01", title: "ITIN application", body: "Mobile intake, W-7 auto-generated, remote doc verification by Certified Acceptance Agents. You never mail a passport." },
        { num: "02", title: "Tax filing", body: "File your return including Schedule C for self-employed workers. We handle the paperwork so your appointment stays efficient." },
        { num: "03", title: "ITIN-friendly banking", body: "We match you to banks that accept ITINs by ZIP code. Save, send money home, and start building credit safely." },
        { num: "04", title: "Savings tools", body: "Start an emergency fund that works on any income. Automated tools make it easy to save a little every week, even when money is tight." },
        { num: "05", title: "Retirement planning", body: "IRAs and long-term savings tools built for ITIN holders. Your future doesn't require a Social Security number." },
        { num: "06", title: "Bilingual support", body: "Every guide, form, and message in English or Spanish. No bots, no 1-800 numbers. Real people from your community." },
      ],
    },
    how: {
      eyebrow: "How it works",
      title: "Apply. Connect. Grow.",
      lede: "Three steps to a stronger financial future. We're with you at every one.",
      cta: "Start your application",
      steps: [
        { n: "01", label: "Apply", title: "Complete a secure intake", tagline: "Answer from your phone in under 15 minutes.", body: "Tell us about yourself, upload your documents securely, and let us check if you qualify. No office visit needed." },
        { n: "02", label: "Connect", title: "Get connected to support", tagline: "A real person reviews your case and walks you through next steps.", body: "A Vesta guide or Certified Acceptance Agent reviews your information, answers your questions, and helps you move forward with confidence." },
        { n: "03", label: "Grow", title: "Build beyond your ITIN", tagline: "A tax return is step one, not the finish line.", body: "Once you have your ITIN, we connect you to ITIN-friendly banking, savings accounts, credit-building tools, and long-term financial pathways." },
      ],
    },
    guide: {
      eyebrow: "Meet your guide",
      title: "Real people. Real support.",
      lede: "When you sign up, you're matched with a Vesta guide who speaks your language, knows your community, and helps you through every step. No bots. No 1-800 numbers.",
      stat: "Average response time",
      statValue: "< 2 hours",
    },
    quote: {
      eyebrow: "Real stories",
      quote: "I don't know what could be better than what you did for me. Better than expected, honestly. I'm half legit now. I'm doing everything right.",
      name: "Diana",
      role: "Vesta ITIN client · Bronx, NY",
      story: "Diana lives in the Bronx. She came in for her ITIN and left with her number, her documents intact, and her passport never leaving her hands. She updated her bank account that same week and is already thinking about what comes next.",
    },
    trust: {
      eyebrow: "You can trust us",
      items: [
        { icon: "lock", title: "Your data is private", body: "256-bit encryption. We never share with immigration enforcement." },
        { icon: "shield", title: "IRS Acceptance Agent", body: "We submit your application directly as a Certified Acceptance Agent. Fewer rejections, faster turnaround." },
        { icon: "globe", title: "Bilingual support", body: "Every guide, every form, every email, in English or Spanish." },
        { icon: "community", title: "Backed by your community", body: "We work through nonprofits and employers you already trust." },
      ],
    },
    resources: {
      eyebrow: "Free guides",
      title: "Learn at your own pace, in your language.",
      cta: "See all guides",
      items: [
        { tag: "Guide · 8 min read", title: "What's an ITIN, and do I need one?", body: "Plain-language explainer with examples for workers, families, and small-business owners." },
        { tag: "Video · 4 min", title: "Opening your first bank account", body: "What to bring, what questions to ask, and how to avoid hidden fees." },
        { tag: "Guide · 12 min read", title: "How taxes actually work in the US", body: "Refundable credits, dependents, and what changes when you have an ITIN." },
      ],
    },
    cta: {
      eyebrow: "Ready when you are",
      title: "Start your ITIN application. It's free to begin.",
      lede: "No credit card. No commitment. Save your progress and come back anytime.",
      primary: "Start now",
      secondary: "Talk to a person first",
    },
    assessment: {
      eyebrow: "Find your fit",
      headline: "Not sure where to start?",
      lede: "5 quick questions. We'll match you to the right appointment and send you a prep checklist so you walk in ready — not coached at the door.",
      bullets: [
        "Plain-language questions — no jargon",
        "Personalized appointment match",
        "Schedule C expense checklist if you're self-employed",
      ],
      questions: [
        { q: "Did anyone pay you in cash this year?", help: "Cash from side jobs, tips, helping a friend, watching kids, selling food — anything where you got paid directly. Even small amounts add up at tax time." },
        { q: "Do you work for yourself — even just a side hustle?", help: "Hair, nails, cleaning, cooking and selling food, fixing things, sewing, watching kids, selling online, your own small store. Anything where you set your own hours and find your own customers." },
        { q: "Do you drive for Uber, Lyft, DoorDash, or any delivery app?", help: "Rideshare or delivery apps where you pick up your own jobs. We'll make sure every mile you drove for work counts." },
        { q: "Do you have a Social Security Number?", help: "If yes, your tax filing is more straightforward. If no, no problem — we'll help you apply for an ITIN so you can file taxes and start building credit. Many of our clients started exactly here." },
        { q: "Is your husband, wife, or partner filing with you?", help: "Filing together is called \"married filing jointly.\" If you're filing together, your spouse should come to the appointment with their ID and Social Security card or ITIN." },
      ],
      yes: "Yes",
      no: "No",
      back: "← Back",
      questionLabel: "Question {n} of {total}",
      yourMatch: "Your match",
      bookStep: "Get your prep guide",
      sentStep: "Sent!",
      bestFit: "Best fit for you",
      routes: {
        scheduleC: { label: "Schedule C (self-employed)", desc: "Self-employed returns take the longest — not because the tax is hard, but because expenses take time to organize on the spot. We'll send a plain-language checklist so you arrive with everything ready." },
        scheduleCItin: { label: "Schedule C + ITIN", desc: "You're self-employed and you need an ITIN. We'll handle both at one appointment — we'll send you a plain-language expense checklist and an ITIN document list so you walk in ready." },
        itin: { label: "ITIN application", desc: "Our Certified Acceptance Agents verify your documents in person — you never mail your passport to the IRS. Bring the originals, we'll verify and return them on the spot." },
        vita: { label: "Regular tax return", desc: "Standard tax filing. Most appointments take about 45 minutes when you arrive with your documents." },
      },
      namePlaceholder: "Your name (optional)",
      emailPlaceholder: "you@example.com",
      scheduleButton: "Schedule my appointment →",
      sending: "Sending…",
      schedulerLoading: "Scheduler is still loading. Try again in a moment.",
      sendError: "Couldn't send right now. Try again, or email us at hello@growwithvesta.com.",
      bookingHint: "We'll ask for your email after you pick a time, so your prep guide arrives in the right inbox.",
      // Post-schedule email capture step
      bookedTitle: "Your appointment is booked.",
      bookedBody: "Calendly sent you a confirmation. Confirm the slot you picked so we can include it in your prep email.",
      pickSlot: "Pick the slot you booked",
      sendPrepButton: "Send my prep guide →",
      // Done state
      doneTitle: "Prep guide on the way.",
      doneBody: "Check {email} for your guide. See you at your appointment!",
      openPrepGuide: "Open my prep guide now →",
    },
  },
  es: {
    nav: { itin: "Solicita tu ITIN", banking: "Abre una cuenta bancaria", learn: "Aprende", resources: "Recursos", help: "Recibe ayuda" },
    hero: {
      eyebrow: "Para ti y tu familia",
      title: "Tu ITIN, tu cuenta, tu futuro. Estamos contigo.",
      lede: "Vesta te ayuda a solicitar tu ITIN, abrir una cuenta bancaria y empezar a ahorrar, con personas reales de tu lado, en inglés o español.",
      ctaPrimary: "Empieza tu solicitud de ITIN",
      ctaSecondary: "Habla con una persona",
    },
    privacy: {
      eyebrow: "Nuestra promesa",
      lines: [
        "Nunca compartimos tu información con ICE.",
        "Tus documentos están encriptados y solo los ven nuestros socios certificados por el IRS.",
        "Puedes hacer preguntas en cualquier momento, sin costo.",
      ],
    },
    whatYouGet: {
      eyebrow: "Tu camino",
      headline: "Todo lo que necesitas para construir tu futuro financiero.",
      lede: "Muchas personas empiezan con un ID de impuestos. Pero eso es solo el comienzo. Vesta está contigo en cada paso.",
      cta: "Encuentra tu opción",
      items: [
        { num: "01", title: "Solicitud de ITIN", body: "Intake móvil, W-7 generado automáticamente, verificación remota de documentos por Agentes Aceptadores Certificados. Nunca envías un pasaporte." },
        { num: "02", title: "Declaración de impuestos", body: "Presenta tu declaración incluyendo Schedule C si trabajas por tu cuenta. Nosotros nos encargamos del papeleo." },
        { num: "03", title: "Bancos que aceptan ITIN", body: "Te conectamos con bancos que aceptan ITINs por código postal. Ahorra, envía dinero, y empieza a construir crédito con seguridad." },
        { num: "04", title: "Herramientas de ahorro", body: "Construye un fondo de emergencia que funciona con cualquier ingreso. Herramientas automatizadas para ahorrar poquito cada semana." },
        { num: "05", title: "Plan de retiro", body: "IRAs y herramientas de ahorro a largo plazo construidas para titulares de ITIN. Tu futuro no requiere un Número de Seguro Social." },
        { num: "06", title: "Apoyo bilingüe", body: "Cada guía, formulario y mensaje en inglés o español. Sin bots, sin líneas 1-800. Personas reales de tu comunidad." },
      ],
    },
    journey: {
      eyebrow: "Tu camino",
      title: "Sin importar desde dónde empiezas, mereces herramientas que te ayuden a construir estabilidad con el tiempo.",
      lede: "Muchas personas comienzan con un número de identificación fiscal. Pero eso es solo el principio. Vesta está contigo en cada paso que sigue.",
      steps: [
        { n: "01", label: "ITIN e impuestos", body: "Obtén tu número fiscal y presenta tu declaración, incluyendo el Anexo C si eres trabajador independiente. Nuestros Agentes Aceptadores certificados se encargan del papeleo para que nunca tengas que enviar tu pasaporte por correo." },
        { n: "02", label: "Cuenta bancaria", body: "Abre una cuenta bancaria que acepta ITIN para ahorrar, enviar dinero a casa y construir un historial financiero en EE. UU. Solo te conectamos con bancos de confianza." },
        { n: "03", label: "Ahorros", body: "Empieza a construir un fondo de emergencia para que los gastos imprevistos no te atrasen. Te mostraremos opciones de ahorro que funcionan con cualquier ingreso." },
        { n: "04", label: "Jubilación", body: "Planifica tu seguridad financiera a largo plazo con IRAs y opciones de ahorro del empleador, diseñadas para personas con ITIN, no solo para quienes tienen número de Seguro Social." },
      ],
    },
    how: {
      eyebrow: "Cómo funciona",
      title: "Aplica. Conéctate. Crece.",
      lede: "Tres pasos hacia un futuro financiero más sólido. Estamos contigo en cada uno.",
      cta: "Empieza tu solicitud",
      steps: [
        { n: "01", label: "Aplica", title: "Completa un intake seguro", tagline: "Responde desde tu teléfono en menos de 15 minutos.", body: "Cuéntanos sobre ti, sube tus documentos de forma segura y verificamos si calificas. Sin necesidad de ir a una oficina." },
        { n: "02", label: "Conéctate", title: "Recibe apoyo personalizado", tagline: "Una persona real revisa tu caso y te guía en los siguientes pasos.", body: "Una guía de Vesta o un Agente Aceptador certificado revisa tu información, responde tus preguntas y te ayuda a avanzar con confianza." },
        { n: "03", label: "Crece", title: "Construye más allá de tu ITIN", tagline: "Una declaración de impuestos es el primer paso, no la meta.", body: "Una vez que tienes tu ITIN, te conectamos con bancos que lo aceptan, cuentas de ahorro, herramientas para construir crédito y caminos financieros a largo plazo." },
      ],
    },
    guide: {
      eyebrow: "Conoce a tu guía",
      title: "Personas reales. Apoyo real.",
      lede: "Cuando te registras, te asignamos una guía de Vesta que habla tu idioma, conoce tu comunidad y te acompaña en cada paso. Sin bots. Sin líneas 1-800.",
      stat: "Tiempo de respuesta",
      statValue: "< 2 horas",
    },
    quote: {
      eyebrow: "Historias reales",
      quote: "Tenía miedo de empezar el papeleo del ITIN. Mi guía de Vesta me llamó, me explicó todo en español, y en tres semanas tenía mi número. Ahora tengo cuenta de cheques.",
      name: "Lucía Hernández",
      role: "Cliente de Vesta · Brooklyn, NY",
      story: "Lucía vive en Brooklyn. Vino por su ITIN y se fue con su número, sus documentos intactos, y su pasaporte nunca salió de sus manos. La misma semana actualizó su cuenta de banco y ya está pensando en lo que viene.",
    },
    trust: {
      eyebrow: "Puedes confiar en nosotros",
      items: [
        { icon: "lock", title: "Tus datos son privados", body: "Encriptación de 256 bits. Nunca compartimos con autoridades de inmigración." },
        { icon: "shield", title: "Agente Aceptador del IRS", body: "Enviamos tu solicitud directamente como Agente Aceptador Certificado. Menos rechazos, respuesta más rápida." },
        { icon: "globe", title: "Apoyo bilingüe", body: "Cada guía, cada formulario, cada correo, en inglés o español." },
        { icon: "community", title: "Respaldados por tu comunidad", body: "Trabajamos con organizaciones y empleadores en los que ya confías." },
      ],
    },
    resources: {
      eyebrow: "Guías gratis",
      title: "Aprende a tu ritmo, en tu idioma.",
      cta: "Ver todas las guías",
      items: [
        { tag: "Guía · 8 min", title: "¿Qué es un ITIN y lo necesito?", body: "Explicación clara con ejemplos para trabajadores, familias y dueños de pequeños negocios." },
        { tag: "Video · 4 min", title: "Abriendo tu primera cuenta bancaria", body: "Qué llevar, qué preguntar y cómo evitar cargos escondidos." },
        { tag: "Guía · 12 min", title: "Cómo funcionan los impuestos en EE. UU.", body: "Créditos reembolsables, dependientes y qué cambia cuando tienes un ITIN." },
      ],
    },
    cta: {
      eyebrow: "Cuando estés listo",
      title: "Empieza tu solicitud de ITIN. Gratis.",
      lede: "Sin tarjeta de crédito. Sin compromiso. Guarda tu progreso y vuelve cuando quieras.",
      primary: "Empezar ahora",
      secondary: "Hablar con una persona primero",
    },
    assessment: {
      eyebrow: "Encuentra tu opción",
      headline: "¿No sabes por dónde empezar?",
      lede: "5 preguntas rápidas. Te emparejamos con la cita correcta y te enviamos una lista de preparación para que llegues listo — no instruido en la puerta.",
      bullets: [
        "Preguntas en lenguaje sencillo — sin jerga",
        "Cita personalizada según tus necesidades",
        "Lista de gastos Schedule C si trabajas por tu cuenta",
      ],
      questions: [
        { q: "¿Alguien te pagó en efectivo este año?", help: "Propinas, trabajos extra, ayudar a un amigo, cuidar niños, vender comida — cualquier dinero que recibiste directamente. Hasta cantidades pequeñas suman al final del año." },
        { q: "¿Trabajas por tu cuenta — aunque sea solo un trabajo extra?", help: "Cabello, uñas, limpieza, cocina y venta de comida, arreglos, costura, cuidado de niños, ventas en línea, tu propia tiendita. Cualquier cosa donde tú pones tus horarios y encuentras tus propios clientes." },
        { q: "¿Manejas para Uber, Lyft, DoorDash o alguna app de entrega?", help: "Aplicaciones de transporte o entrega donde tomas tus propios trabajos. Nos aseguraremos de que cada milla que manejaste por trabajo cuente." },
        { q: "¿Tienes un Número de Seguro Social?", help: "Si sí, tu declaración de impuestos es más sencilla. Si no, no hay problema — te ayudamos a solicitar un ITIN para que puedas declarar impuestos y empezar a construir crédito. Muchos de nuestros clientes empezaron justo aquí." },
        { q: "¿Tu esposo, esposa o pareja va a declarar contigo?", help: "Declarar juntos se llama \"casados declarando juntos.\" Si declaran juntos, tu pareja debe venir a la cita también con su identificación y tarjeta de Seguro Social o ITIN." },
      ],
      yes: "Sí",
      no: "No",
      back: "← Atrás",
      questionLabel: "Pregunta {n} de {total}",
      yourMatch: "Tu opción",
      bookStep: "Obtén tu guía",
      sentStep: "¡Enviado!",
      bestFit: "Tu mejor opción",
      routes: {
        scheduleC: { label: "Schedule C (por cuenta propia)", desc: "Las citas por cuenta propia toman más tiempo — no porque los impuestos sean difíciles, sino porque organizar los gastos toma tiempo. Te enviamos una lista en lenguaje sencillo para que llegues lista." },
        scheduleCItin: { label: "Schedule C + ITIN", desc: "Trabajas por tu cuenta y necesitas un ITIN. Nos encargamos de ambos en una sola cita — te enviamos una lista de gastos en lenguaje sencillo y una lista de documentos del ITIN para que llegues lista." },
        itin: { label: "Solicitud de ITIN", desc: "Nuestros Agentes Tramitadores Certificados verifican tus documentos en persona — nunca envías tu pasaporte al IRS por correo. Trae los originales, los verificamos y te los devolvemos en el momento." },
        vita: { label: "Declaración de impuestos regular", desc: "Declaración estándar. La mayoría de las citas toman 45 minutos cuando llegas con tus documentos." },
      },
      namePlaceholder: "Tu nombre (opcional)",
      emailPlaceholder: "tu@ejemplo.com",
      scheduleButton: "Programar mi cita →",
      sending: "Enviando…",
      schedulerLoading: "El programador aún se está cargando. Intenta de nuevo.",
      sendError: "No pudimos enviar ahora. Intenta de nuevo o escríbenos a hello@growwithvesta.com.",
      bookingHint: "Te pediremos tu correo después de elegir la hora — así tu guía llega a tu bandeja correcta.",
      bookedTitle: "¡Tu cita está reservada!",
      bookedBody: "Calendly ya te envió la confirmación. Confirma el horario que elegiste para incluirlo en tu correo.",
      pickSlot: "Elige el horario que reservaste",
      sendPrepButton: "Enviar mi guía →",
      doneTitle: "Tu guía va en camino.",
      doneBody: "Revisa {email} para tu guía. ¡Nos vemos en tu cita!",
      openPrepGuide: "Abrir mi guía ahora →",
    },
  },
};

/* ---------- Lang switcher ---------- */
function LangSwitch({ lang, setLang }) {
  return (
    <div
      style={{
        position: "fixed",
        bottom: 24,
        right: 24,
        zIndex: 200,
        background: "var(--vesta-black)",
        borderRadius: 999,
        padding: 4,
        display: "flex",
        gap: 0,
        boxShadow: "0 10px 30px rgba(0,0,0,0.18)",
      }}
    >
      {[
        { code: "en", label: "English" },
        { code: "es", label: "Español" },
      ].map((l) => (
        <button
          key={l.code}
          type="button"
          onClick={() => setLang(l.code)}
          style={{
            fontFamily: "var(--font-sans)",
            fontSize: 13,
            fontWeight: 700,
            padding: "8px 16px",
            borderRadius: 999,
            border: "none",
            background: lang === l.code ? "var(--vesta-orange)" : "transparent",
            color: lang === l.code ? "#fff" : "rgba(255,255,255,0.7)",
            cursor: "pointer",
            transition: "all 150ms",
          }}
        >
          {l.label}
        </button>
      ))}
    </div>
  );
}

function ClientHero({ t, lang }) {
  return (
    <header className="vm-section" style={{ paddingTop: "clamp(48px, 6vw, 80px)", paddingBottom: "clamp(48px, 6vw, 80px)" }} lang={lang}>
      <div className="vm-container">
        <div className="vm-grid" style={{ alignItems: "end" }}>
          <div className="vm-col-7" style={{ display: "flex", flexDirection: "column", gap: 22 }}>
            <span className="vm-eyebrow">{t.hero.eyebrow}</span>
            <h1 className="vm-display">{t.hero.title}</h1>
            <p className="vm-lede">{t.hero.lede}</p>
            <div style={{ display: "flex", gap: 12, marginTop: 6, flexWrap: "wrap" }}>
              <a href="#how" className="vm-btn vm-btn-green vm-btn-lg">{lang === "es" ? "Cómo funciona ↓" : "See how it works ↓"}</a>
              <a href="https://calendly.com/growwithvesta/30min" className="vm-btn vm-btn-secondary vm-btn-lg">{t.hero.ctaSecondary}</a>
            </div>
          </div>
          <div className="vm-col-5">
            <img
              src="newsletter-1.png"
              alt={lang === "es" ? "Familia en comunidad · evento Vesta" : "Community at a Vesta event"}
              style={{
                width: "100%",
                height: "clamp(300px, 38vw, 500px)",
                borderRadius: 16,
                display: "block",
                objectFit: "cover",
                objectPosition: "center top",
              }}
            />
          </div>
        </div>
      </div>
    </header>
  );
}

function PrivacyBand({ t, lang }) {
  return (
    <section
      lang={lang}
      style={{
        background: "var(--vesta-green)",
        color: "#fff",
        paddingBlock: 28,
      }}
    >
      <div className="vm-container">
        <div style={{ display: "flex", gap: 32, alignItems: "center", flexWrap: "wrap" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 12, color: "#fff" }}>
            <VmIcon name="shield" size={22} />
            <span style={{ fontWeight: 700, fontSize: 14, letterSpacing: "0.04em", textTransform: "uppercase" }}>
              {t.privacy.eyebrow}
            </span>
          </div>
          <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "flex", gap: 28, flexWrap: "wrap" }}>
            {t.privacy.lines.map((l) => (
              <li key={l} style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 14, color: "rgba(255,255,255,0.95)" }}>
                <VmIcon name="check" size={16} />
                <span>{l}</span>
              </li>
            ))}
          </ul>
        </div>
      </div>
    </section>
  );
}


function ClientsWhat({ t, lang }) {
  const [open, setOpen] = useState(() => new Set());
  const toggle = (i) => setOpen((prev) => {
    const next = new Set(prev);
    if (next.has(i)) next.delete(i); else next.add(i);
    return next;
  });
  const w = t.whatYouGet;
  const items = w.items;

  return (
    <section id="start" lang={lang} style={{ background: "var(--vesta-green)", paddingBlock: "clamp(72px, 8vw, 112px)" }}>
      <div className="vm-container">

        {/* Full-width stacked header */}
        <div style={{
          paddingBottom: "clamp(48px, 5vw, 80px)",
          borderBottom: "1px solid rgba(255,255,255,0.2)",
          marginBottom: "clamp(32px, 4vw, 56px)",
        }}>
          <span className="vm-eyebrow" style={{ color: "rgba(255,255,255,0.6)" }}>{w.eyebrow}</span>
          <h2 className="vm-display" style={{ marginTop: 14, color: "#fff", fontSize: "clamp(28px, 3.6vw, 46px)" }}>
            {w.headline}
          </h2>
          <div style={{ display: "flex", alignItems: "center", gap: 40, marginTop: 28, flexWrap: "wrap" }}>
            <p className="vm-lede" style={{ margin: 0, color: "rgba(255,255,255,0.85)", maxWidth: "52ch" }}>
              {w.lede}
            </p>
            <a href="#find-your-fit" className="vm-btn vm-btn-on-green vm-btn-lg" style={{ flexShrink: 0 }}>
              {w.cta} →
            </a>
          </div>
        </div>

        {/* 6 items — collapsed by default, click to expand, mirrors PartnersWhat */}
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "0 clamp(32px, 4vw, 80px)" }}>
          {items.map((it, i) => {
            const isOpen = open.has(i);
            return (
              <div
                key={it.num}
                style={{
                  borderBottom: "1px solid rgba(255,255,255,0.2)",
                }}
              >
                <button
                  type="button"
                  onClick={() => toggle(i)}
                  aria-expanded={isOpen}
                  style={{
                    all: "unset",
                    boxSizing: "border-box",
                    cursor: "pointer",
                    width: "100%",
                    display: "grid",
                    gridTemplateColumns: "48px 1fr 24px",
                    gap: "0 20px",
                    padding: "clamp(20px, 2.5vw, 32px) 0",
                    alignItems: "start",
                  }}
                >
                  <span style={{
                    fontSize: 11, fontWeight: 700,
                    color: "rgba(255,255,255,0.5)",
                    letterSpacing: "0.08em",
                    paddingTop: 5, lineHeight: 1,
                  }}>
                    {it.num}
                  </span>
                  <h3 style={{ margin: 0, fontSize: "clamp(18px, 1.5vw, 22px)", fontWeight: 700, color: "#fff", letterSpacing: "-0.02em", lineHeight: 1.1 }}>
                    {it.title}
                  </h3>
                  <span
                    aria-hidden="true"
                    style={{
                      fontSize: 22,
                      lineHeight: 1,
                      color: "rgba(255,255,255,0.7)",
                      transform: isOpen ? "rotate(45deg)" : "rotate(0)",
                      transition: "transform 200ms cubic-bezier(0.22,1,0.36,1)",
                      paddingTop: 2,
                      justifySelf: "end",
                    }}
                  >
                    +
                  </span>
                </button>
                {isOpen && (
                  <p className="vm-body" style={{
                    margin: 0,
                    paddingLeft: 68,
                    paddingBottom: "clamp(20px, 2.5vw, 32px)",
                    color: "rgba(255,255,255,0.85)",
                    lineHeight: 1.5,
                  }}>
                    {it.body}
                  </p>
                )}
              </div>
            );
          })}
        </div>
      </div>
    </section>
  );
}

function ClientsHow({ t, lang }) {
  return (
    <section className="vm-section vm-section-alt" id="how" lang={lang}>
      <div className="vm-container">
        {/* Header — full width */}
        <div style={{ maxWidth: "60ch" }}>
          <span className="vm-eyebrow">{t.how.eyebrow}</span>
          <h2 className="vm-h1" style={{ marginTop: 14 }}>{t.how.title}</h2>
          <p className="vm-lede" style={{ marginTop: 18 }}>{t.how.lede}</p>
          <div style={{ marginTop: 28 }}>
            <a href="https://www.growwithvesta.com/itin-intake" className="vm-btn vm-btn-green">{t.how.cta} →</a>
          </div>
        </div>

        {/* Three columns below */}
        <ol
          className="vm-how-cols"
          style={{
            listStyle: "none", padding: 0,
            marginTop: "clamp(48px, 6vw, 80px)",
            display: "grid",
            gridTemplateColumns: "repeat(3, 1fr)",
            gap: "clamp(24px, 3vw, 48px)",
          }}
        >
          {t.how.steps.map((s) => (
            <li
              key={s.n}
              style={{
                display: "flex",
                flexDirection: "column",
                gap: 12,
                paddingTop: 24,
                borderTop: "1px solid var(--vesta-gray-2)",
              }}
            >
              <div style={{ display: "flex", alignItems: "baseline", gap: 12 }}>
                <span style={{ fontSize: 11, fontWeight: 700, color: "var(--vesta-green)", letterSpacing: "0.08em", textTransform: "uppercase" }}>{s.label}</span>
                <span style={{ fontSize: 12, fontWeight: 700, color: "var(--vesta-gray-3)" }}>{s.n}</span>
              </div>
              <h4 className="vm-h3" style={{ margin: 0 }}>{s.title}</h4>
              <p style={{ margin: 0, fontSize: 15, fontWeight: 500, color: "var(--vesta-black)", fontStyle: "italic" }}>{s.tagline}</p>
              <p className="vm-body" style={{ margin: 0, color: "var(--vesta-gray-4)" }}>{s.body}</p>
            </li>
          ))}
        </ol>
      </div>
    </section>
  );
}

function ClientsFind({ lang }) {
  const [open, setOpen] = useState(() => new Set());
  const toggle = (i) => setOpen((prev) => {
    const next = new Set(prev);
    if (next.has(i)) next.delete(i); else next.add(i);
    return next;
  });
  const partners = [
    {
      n: "01",
      region: lang === "es" ? "Upstate Nueva York" : "Upstate New York",
      org: "Hartwick VITA/TCE & Upstate Caring Partners",
      detail: lang === "es"
        ? "Sitios VITA/TCE certificados por el IRS que ofrecen declaración de impuestos e ITIN gratuitos. Usa el localizador del IRS para encontrar el más cercano a ti."
        : "IRS-certified VITA/TCE sites offering free tax filing and ITIN support. Use the IRS locator tool to find the closest site to you.",
    },
    {
      n: "02",
      region: lang === "es" ? "Tu empleador" : "Your employer",
      org: lang === "es" ? "Organizaciones empleadoras asociadas" : "Partner employers",
      detail: lang === "es"
        ? "Algunos empleadores ofrecen acceso a Vesta directamente en el trabajo. Pregunta a tu departamento de recursos humanos."
        : "Some employers offer Vesta access directly through work. Ask your HR department if your organization is a partner.",
    },
    {
      n: "03",
      region: lang === "es" ? "Tu comunidad" : "Your community",
      org: lang === "es" ? "Centros comunitarios y organizaciones de fe" : "Community centers & faith organizations",
      detail: lang === "es"
        ? "Muchos de nuestros socios trabajan a través de iglesias, mezquitas y centros que ya conoces y en los que confías."
        : "Many of our partners work through churches, mosques, and community centers you already know and trust.",
    },
  ];

  return (
    <section className="vm-section" lang={lang} style={{ paddingBottom: "clamp(64px, 8vw, 120px)" }}>
      <div className="vm-container">

        {/* Header */}
        <div className="vm-mobile-stack" style={{
          display: "grid",
          gridTemplateColumns: "1fr 1fr",
          gap: "clamp(32px, 4vw, 80px)",
          alignItems: "end",
          paddingBottom: "clamp(40px, 5vw, 64px)",
          marginBottom: "clamp(8px, 2vw, 0px)",
        }}>
          <div>
            <span className="vm-eyebrow">{lang === "es" ? "En tu comunidad" : "In your community"}</span>
            <h2 className="vm-h1" style={{ marginTop: 14 }}>
              {lang === "es" ? "Encuentra apoyo cerca de ti." : "Find support where you live."}
            </h2>
          </div>
          <div style={{ display: "flex", flexDirection: "column", justifyContent: "flex-end", gap: 24 }}>
            <p className="vm-lede" style={{ margin: 0 }}>
              {lang === "es"
                ? "Vesta trabaja a través de organizaciones locales en las que ya confías. Si no hay un socio cerca, te conectamos directamente."
                : "Vesta works through local nonprofits, employers, and community organizations. If there's no partner near you yet, we'll connect you directly."}
            </p>
            <a href="https://freetaxassistance.for.irs.gov/s/sitelocator" target="_blank" rel="noopener noreferrer" className="vm-btn vm-btn-green" style={{ alignSelf: "flex-start" }}>
              {lang === "es" ? "Encuentra un sitio VITA cerca →" : "Find a VITA site near me →"}
            </a>
          </div>
        </div>

        {/* Partner columns — 3-col collapsible */}
        <ol
          className="vm-how-cols"
          style={{
            listStyle: "none", padding: 0, margin: "clamp(32px, 4vw, 48px) 0 0",
            display: "grid",
            gridTemplateColumns: "repeat(3, 1fr)",
            gap: "clamp(20px, 3vw, 32px)",
          }}
        >
          {partners.map((p, i) => {
            const isOpen = open.has(i);
            return (
              <li
                key={p.n}
                style={{ borderTop: "1px solid var(--vesta-gray-2)" }}
              >
                <button
                  type="button"
                  onClick={() => toggle(i)}
                  aria-expanded={isOpen}
                  style={{
                    all: "unset", boxSizing: "border-box", cursor: "pointer", width: "100%",
                    display: "flex", flexDirection: "column", gap: 10,
                    paddingTop: 20, paddingBottom: 20,
                  }}
                >
                  <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", gap: 12 }}>
                    <span style={{ fontSize: 11, fontWeight: 700, color: "var(--vesta-green)", letterSpacing: "0.08em", lineHeight: 1 }}>{p.n}</span>
                    <span aria-hidden="true" style={{
                      fontSize: 22, lineHeight: 1, color: "var(--vesta-gray-3)",
                      transform: isOpen ? "rotate(45deg)" : "rotate(0)",
                      transition: "transform 200ms cubic-bezier(0.22,1,0.36,1)",
                    }}>+</span>
                  </div>
                  <div style={{ fontSize: 11, fontWeight: 700, color: "var(--vesta-gray-3)", letterSpacing: "0.08em", textTransform: "uppercase" }}>{p.region}</div>
                  <div style={{ fontSize: "clamp(15px, 1.2vw, 17px)", fontWeight: 700, color: "var(--vesta-black)", lineHeight: 1.2 }}>{p.org}</div>
                </button>
                {isOpen && (
                  <p className="vm-body" style={{ margin: 0, paddingBottom: 24, color: "var(--vesta-gray-4)", lineHeight: 1.6 }}>{p.detail}</p>
                )}
              </li>
            );
          })}
        </ol>
      </div>
    </section>
  );
}

function MeetGuide({ t, lang }) {
  return (
    <section className="vm-section vm-section-alt" lang={lang}>
      <div className="vm-container">
        <div className="vm-grid" style={{ alignItems: "center", gap: "clamp(40px, 5vw, 80px)" }}>

          {/* Image */}
          <div className="vm-col-5">
            <img
              src="newsletter-2.png"
              alt={lang === "es" ? "Comunidad Vesta · evento bilingüe" : "Vesta community event"}
              style={{
                width: "100%",
                aspectRatio: "1 / 1",
                objectFit: "cover",
                objectPosition: "center top",
                borderRadius: 16,
                display: "block",
              }}
            />
          </div>

          {/* Story */}
          <div className="vm-col-7" style={{ display: "flex", flexDirection: "column", gap: 28 }}>
            <span className="vm-eyebrow">{t.quote.eyebrow}</span>

            {/* Pull quote */}
            <p style={{
              margin: 0,
              fontSize: "clamp(22px, 2.6vw, 36px)",
              fontWeight: 400,
              letterSpacing: "-0.025em",
              lineHeight: 1.15,
              color: "var(--vesta-black)",
            }}>
              "{t.quote.quote}"
            </p>

            {/* Attribution */}
            <div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
              <span style={{ fontSize: 15, fontWeight: 700, color: "var(--vesta-black)" }}>
                {t.quote.name}
              </span>
              <span style={{ fontSize: 13, color: "var(--vesta-gray-3)", letterSpacing: "0.01em" }}>
                {t.quote.role}
              </span>
            </div>

            {/* Green rule */}
            <div style={{ width: 40, height: 2, background: "var(--vesta-green)", borderRadius: 99 }} />

            {/* Body */}
            <p className="vm-body" style={{ margin: 0, maxWidth: "52ch", color: "var(--vesta-gray-4)", lineHeight: 1.65 }}>
              {t.quote.story}
            </p>
          </div>
        </div>
      </div>
    </section>
  );
}


function Trust({ t, lang }) {
  const [open, setOpen] = useState(() => new Set());
  const toggle = (i) => setOpen((prev) => {
    const next = new Set(prev);
    if (next.has(i)) next.delete(i); else next.add(i);
    return next;
  });

  return (
    <section lang={lang} style={{ background: "var(--vesta-black)", paddingBlock: "clamp(72px, 8vw, 112px)" }}>
      <div className="vm-container">
        {/* Full-width stacked header */}
        <div style={{
          paddingBottom: "clamp(48px, 5vw, 80px)",
          borderBottom: "1px solid rgba(255,255,255,0.15)",
          marginBottom: "clamp(32px, 4vw, 56px)",
        }}>
          <span className="vm-eyebrow" style={{ color: "rgba(255,255,255,0.55)" }}>{t.trust.eyebrow}</span>
          <h2 className="vm-display" style={{ marginTop: 14, color: "#fff", maxWidth: "20ch" }}>
            {lang === "es" ? "Construido con cuidado, enraizado en tu comunidad." : "Built with care. Rooted in your community."}
          </h2>
          <p className="vm-lede" style={{ margin: "24px 0 0", color: "rgba(255,255,255,0.75)", maxWidth: "52ch" }}>
            {lang === "es"
              ? "Tu privacidad y seguridad son nuestra prioridad. Trabajamos solo con socios en los que ya confías."
              : "Your privacy and safety are our priority. We work only with partners your community already trusts."}
          </p>
        </div>

        {/* 2-col accordion grid — click to expand */}
        <div className="vm-mobile-stack" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "0 clamp(32px, 4vw, 80px)" }}>
          {t.trust.items.map((it, i) => {
            const isOpen = open.has(i);
            return (
              <div key={it.title} style={{ borderBottom: "1px solid rgba(255,255,255,0.12)" }}>
                <button
                  type="button"
                  onClick={() => toggle(i)}
                  aria-expanded={isOpen}
                  style={{
                    all: "unset", boxSizing: "border-box", cursor: "pointer", width: "100%",
                    display: "grid", gridTemplateColumns: "48px 1fr 24px", gap: "0 20px",
                    padding: "clamp(20px, 2.5vw, 32px) 0", alignItems: "center",
                  }}
                >
                  <span style={{ paddingTop: 3, color: "var(--vesta-orange)", display: "flex", alignItems: "flex-start" }}>
                    <VmIcon name={it.icon} size={22} />
                  </span>
                  <h3 style={{ margin: 0, fontSize: "clamp(18px, 1.5vw, 22px)", fontWeight: 700, color: "#fff", letterSpacing: "-0.02em", lineHeight: 1.1 }}>
                    {it.title}
                  </h3>
                  <span aria-hidden="true" style={{
                    fontSize: 22, lineHeight: 1, color: "rgba(255,255,255,0.6)",
                    transform: isOpen ? "rotate(45deg)" : "rotate(0)",
                    transition: "transform 200ms cubic-bezier(0.22,1,0.36,1)",
                    justifySelf: "end",
                  }}>+</span>
                </button>
                {isOpen && (
                  <p className="vm-body" style={{ margin: 0, paddingLeft: 68, paddingBottom: "clamp(20px, 2.5vw, 32px)", color: "rgba(255,255,255,0.65)", lineHeight: 1.5 }}>
                    {it.body}
                  </p>
                )}
              </div>
            );
          })}
        </div>
      </div>
    </section>
  );
}

function ResourcesPreview({ t, lang }) {
  return (
    <section className="vm-section" lang={lang}>
      <div className="vm-container">
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", marginBottom: 48, flexWrap: "wrap", gap: 16 }}>
          <div>
            <span className="vm-eyebrow">{t.resources.eyebrow}</span>
            <h2 className="vm-h1" style={{ marginTop: 12 }}>{t.resources.title}</h2>
          </div>
          <a href="/clients/resources.html" className="vm-btn vm-btn-secondary" style={{ flexShrink: 0 }}>{t.resources.cta}</a>
        </div>
        <ol
          className="vm-how-cols"
          style={{
            listStyle: "none", padding: 0, margin: 0,
            display: "grid",
            gridTemplateColumns: "repeat(3, 1fr)",
            gap: "clamp(24px, 3vw, 48px)",
          }}
        >
          {t.resources.items.map((r) => (
            <li
              key={r.title}
              style={{
                display: "flex",
                flexDirection: "column",
                gap: 12,
                paddingTop: 24,
                borderTop: "1px solid var(--vesta-gray-2)",
              }}
            >
              <span style={{
                fontSize: 11, fontWeight: 600,
                letterSpacing: "0.08em", textTransform: "uppercase",
                color: "var(--vesta-gray-3)",
              }}>
                {r.tag}
              </span>
              <h3 className="vm-h3" style={{ margin: 0 }}>{r.title}</h3>
              <p className="vm-body" style={{ margin: 0 }}>{r.body}</p>
              <a
                href="/clients/resources.html"
                style={{
                  marginTop: "auto",
                  paddingTop: 8,
                  fontSize: 14,
                  fontWeight: 700,
                  color: "var(--vesta-green)",
                  textDecoration: "none",
                  display: "inline-flex",
                  alignItems: "center",
                  gap: 6,
                  alignSelf: "flex-start",
                }}
              >
                {lang === "es" ? "Abrir" : "Open"} <VmIcon name="arrow-right" size={16} />
              </a>
            </li>
          ))}
        </ol>
      </div>
    </section>
  );
}

function CallToAction({ t, lang }) {
  return (
    <section id="talk" lang={lang} style={{ background: "var(--vesta-black)", paddingBlock: "clamp(72px, 8vw, 112px)" }}>
      <div className="vm-container">
        <div className="vm-grid" style={{ alignItems: "center" }}>
          <div className="vm-col-7">
            <span className="vm-eyebrow" style={{ color: "rgba(255,255,255,0.55)" }}>{t.cta.eyebrow}</span>
            <h2 className="vm-h1" style={{ marginTop: 14, color: "#fff" }}>{t.cta.title}</h2>
            <p className="vm-lede" style={{ marginTop: 16, color: "rgba(255,255,255,0.85)" }}>{t.cta.lede}</p>
          </div>
          <div className="vm-col-5" style={{ display: "flex", flexDirection: "column", gap: 12 }}>
            <a href="https://www.growwithvesta.com/itin-intake" className="vm-btn vm-btn-green vm-btn-lg" style={{ alignSelf: "flex-start" }}>
              {t.cta.primary}
            </a>
            <a href="https://calendly.com/growwithvesta/30min" className="vm-link" style={{ color: "rgba(255,255,255,0.85)" }}>{t.cta.secondary}</a>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ============================================================
   ClientAssessment — 5-question readiness flow that routes to
   the right appointment type and emails the client a prep guide
   (Schedule C plain-language checklist when applicable).
   PRD: Vesta_ScheduleC_PRD.docx — Feature 1 + slice of Feature 2
   ============================================================ */
/* Generate the next ~5 weekdays with sample appointment slots.
   This is the demo source until we wire Calendly's paid API. */
function generateSlots(locale = "en-US") {
  const slots = [];
  const today = new Date();
  let daysFound = 0;
  let offset = 1;
  const times = [
    { h: 9, m: 0 },
    { h: 10, m: 30 },
    { h: 13, m: 0 },
    { h: 15, m: 30 },
  ];
  while (daysFound < 5 && offset < 14) {
    const d = new Date(today);
    d.setDate(today.getDate() + offset);
    const day = d.getDay();
    if (day !== 0 && day !== 6) {
      const dateLabel = d.toLocaleDateString(locale, { weekday: "long", month: "long", day: "numeric" });
      const dateIsoBase = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
      slots.push({
        dateLabel,
        times: times.map(({ h, m }) => {
          const slot = new Date(d);
          slot.setHours(h, m, 0, 0);
          return {
            iso: `${dateIsoBase}T${String(h).padStart(2, "0")}:${String(m).padStart(2, "0")}`,
            label: slot.toLocaleTimeString(locale, { hour: "numeric", minute: "2-digit" }),
          };
        }),
      });
      daysFound++;
    }
    offset++;
  }
  return slots;
}

/* Cal.com inline embed — shows real availability, fires bookingSuccessful with full booking data */
const CAL_LINK = "yanjaa-munkhbat-c2whsr/30min";
const CAL_NAMESPACE = "vesta-assessment";

function CalEmbed({ onBooked }) {
  const ref = useRef(null);
  useEffect(() => {
    let cancelled = false;
    function init() {
      if (cancelled) return;
      if (window.Cal && ref.current) {
        ref.current.innerHTML = "";
        try {
          window.Cal("init", CAL_NAMESPACE, { origin: "https://cal.com" });
          window.Cal.ns[CAL_NAMESPACE]("inline", {
            elementOrSelector: ref.current,
            calLink: CAL_LINK,
            config: { layout: "column_view", theme: "light" },
          });
          window.Cal.ns[CAL_NAMESPACE]("on", {
            action: "bookingSuccessful",
            callback: (e) => {
              const data = e && e.detail && e.detail.data ? e.detail.data : {};
              if (onBooked) onBooked(data);
            },
          });
        } catch (err) {
          /* swallow init errors — embed will show empty */
        }
      } else {
        setTimeout(init, 250);
      }
    }
    init();
    return () => { cancelled = true; };
  }, [onBooked]);
  return (
    <div
      ref={ref}
      style={{
        minWidth: 320,
        height: 700,
        background: "#fff",
        borderRadius: 12,
        overflow: "hidden",
      }}
    />
  );
}

function ClientAssessment({ t, lang }) {
  const a = t.assessment;
  const KEYS = ["cashOr1099", "smallBiz", "gig", "hasSSN", "joint"];
  const QUESTIONS = a.questions.map((q, i) => ({ key: KEYS[i], q: q.q, help: q.help }));

  const [step, setStep] = useState(0); // 0..QUESTIONS.length-1 = questions; QUESTIONS.length = result; +1 = email; +2 = done
  const [answers, setAnswers] = useState({});
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [apptSlot, setApptSlot] = useState(""); // ISO datetime string
  const [sending, setSending] = useState(false);
  const [sendError, setSendError] = useState(null);

  const totalQuestions = QUESTIONS.length;
  const onResult = step === totalQuestions;
  const onEmail = step === totalQuestions + 1;
  const onDone = step === totalQuestions + 2;
  const progress = onResult ? 1 : onEmail ? 1 : onDone ? 1 : (step) / totalQuestions;

  /* Called by Cal.com embed when a booking is confirmed.
     Cal.com payload gives us name, email, and time in one event —
     so we fire the prep email automatically with no extra form. */
  async function handleBooked(data) {
    try {
      // Pull invitee details from Cal.com's payload (shape varies slightly by version)
      const booking = data.booking || data;
      const startTime = booking.startTime || booking.start_time || data.startTime || "";
      const attendees = booking.attendees || data.attendees || [];
      const attendee = attendees[0] || {};
      const capturedName = attendee.name || attendee.firstName || "";
      const capturedEmail = attendee.email || "";

      setName(capturedName);
      setEmail(capturedEmail);
      setApptSlot(startTime);

      if (capturedEmail.includes("@")) {
        setSending(true);
        try {
          const res = await fetch("/api/appointment-prep", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({
              name: capturedName,
              email: capturedEmail,
              answers,
              apptDateTime: startTime,
              surface: "clients",
            }),
          });
          if (!res.ok) throw new Error("HTTP " + res.status);
          setStep(totalQuestions + 2);
        } catch (err) {
          setSendError(a.sendError);
          setStep(totalQuestions + 1); // fall back to manual email step
        } finally {
          setSending(false);
        }
      } else {
        // Couldn't extract email from Cal.com payload — fall back to manual form
        setStep(totalQuestions + 1);
      }
    } catch {
      setStep(totalQuestions + 1);
    }
  }

  function pick(key, value) {
    const next = { ...answers, [key]: value };
    setAnswers(next);
    // Auto-advance after a tiny delay so the choice registers visually
    setTimeout(() => setStep((s) => s + 1), 220);
  }

  function back() {
    if (step > 0) setStep(step - 1);
  }

  function route() {
    const selfEmployed = answers.cashOr1099 || answers.smallBiz || answers.gig;
    const noSSN = answers.hasSSN === false;

    if (selfEmployed) {
      const r = noSSN ? a.routes.scheduleCItin : a.routes.scheduleC;
      return { id: "schedule-c", label: r.label, desc: r.desc, color: "var(--vesta-green)", noSSN };
    }
    if (noSSN) {
      return { id: "itin", label: a.routes.itin.label, desc: a.routes.itin.desc, color: "var(--vesta-green)", noSSN: true };
    }
    return { id: "vita", label: a.routes.vita.label, desc: a.routes.vita.desc, color: "var(--vesta-green)", noSSN: false };
  }

  async function submit() {
    if (!email.includes("@") || sending) return;
    setSendError(null);
    setSending(true);
    try {
      const res = await fetch("/api/appointment-prep", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ name, email, answers, apptDateTime: apptSlot, surface: "clients" }),
      });
      if (!res.ok) throw new Error("HTTP " + res.status);
      // Jump to the done state
      setStep(totalQuestions + 2);
    } catch (err) {
      setSendError(a.sendError);
    } finally {
      setSending(false);
    }
  }

  const r = route();
  const q = QUESTIONS[step];

  return (
    <section id="find-your-fit" lang={lang} style={{ background: "var(--vesta-green)", color: "#fff", paddingBlock: "clamp(72px, 8vw, 112px)" }}>
      <div className="vm-container">
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(min(100%, 380px), 1fr))", gap: "clamp(40px, 5vw, 96px)", alignItems: "start" }}>

          {/* Left: pitch */}
          <div>
            <span className="vm-eyebrow" style={{ color: "rgba(255,255,255,0.7)" }}>{a.eyebrow}</span>
            <h2 className="vm-display" style={{ marginTop: 14, color: "#fff", fontSize: "clamp(28px, 3.6vw, 46px)" }}>
              {a.headline}
            </h2>
            <p className="vm-lede" style={{ marginTop: 16, color: "rgba(255,255,255,0.85)", maxWidth: "44ch" }}>
              {a.lede}
            </p>
            <ul style={{ listStyle: "none", padding: 0, margin: "28px 0 0", display: "flex", flexDirection: "column", gap: 10 }}>
              {a.bullets.map((line) => (
                <li key={line} style={{ display: "grid", gridTemplateColumns: "20px 1fr", gap: 10, fontSize: 14, color: "rgba(255,255,255,0.9)" }}>
                  <span style={{ color: "#fff", fontWeight: 700 }}>✓</span>
                  <span>{line}</span>
                </li>
              ))}
            </ul>
          </div>

          {/* Right: assessment card */}
          <div style={{ background: "#fff", color: "var(--vesta-black)", borderRadius: 16, padding: "clamp(24px, 3vw, 40px)", boxShadow: "0 1px 3px rgba(0,0,0,0.08)" }}>

            {/* Progress */}
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", fontSize: 12, color: "var(--vesta-gray-3)", marginBottom: 16 }}>
              <span>{onResult ? a.yourMatch : onEmail ? a.bookStep : onDone ? a.sentStep : a.questionLabel.replace("{n}", step + 1).replace("{total}", totalQuestions)}</span>
              <span style={{ color: "var(--vesta-green)", fontWeight: 700 }}>{Math.round(progress * 100)}%</span>
            </div>
            <div style={{ height: 4, background: "var(--vesta-gray-1)", borderRadius: 999, marginBottom: 28, overflow: "hidden" }}>
              <div style={{ height: "100%", width: `${progress * 100}%`, background: "var(--vesta-green)", transition: "width 250ms cubic-bezier(0.22,1,0.36,1)" }} />
            </div>

            {/* Question */}
            {!onResult && !onEmail && !onDone && (
              <>
                <h3 style={{ margin: "0 0 8px", fontSize: "clamp(18px, 1.6vw, 22px)", fontWeight: 700, color: "var(--vesta-black)", letterSpacing: "-0.015em", lineHeight: 1.25 }}>
                  {q.q}
                </h3>
                <p style={{ margin: "0 0 24px", fontSize: 13, color: "var(--vesta-gray-3)", lineHeight: 1.55 }}>{q.help}</p>
                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
                  {[
                    { value: true, label: a.yes },
                    { value: false, label: a.no },
                  ].map((opt) => {
                    const selected = answers[q.key] === opt.value;
                    return (
                      <button
                        key={String(opt.value)}
                        type="button"
                        onClick={() => pick(q.key, opt.value)}
                        style={{
                          padding: "16px 20px", borderRadius: 12, border: "none",
                          background: selected ? "var(--vesta-green)" : "var(--vesta-gray-1)",
                          color: selected ? "#fff" : "var(--vesta-black)",
                          fontSize: 15, fontWeight: 700, fontFamily: "inherit",
                          cursor: "pointer", transition: "background 150ms, color 150ms",
                        }}
                      >
                        {opt.label}
                      </button>
                    );
                  })}
                </div>
                {step > 0 && (
                  <button type="button" onClick={back} style={{ marginTop: 20, background: "none", border: "none", padding: 0, color: "var(--vesta-gray-3)", fontSize: 13, cursor: "pointer", fontFamily: "inherit" }}>{a.back}</button>
                )}
              </>
            )}

            {/* Result — show fit + inline Calendly time picker */}
            {onResult && (
              <>
                <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: "0.08em", textTransform: "uppercase", color: r.color, marginBottom: 8 }}>{a.bestFit}</div>
                <h3 style={{ margin: "0 0 12px", fontSize: "clamp(22px, 2vw, 28px)", fontWeight: 700, color: "var(--vesta-black)", letterSpacing: "-0.02em", lineHeight: 1.15 }}>
                  {r.label}
                </h3>
                <p style={{ margin: "0 0 16px", fontSize: 14, color: "var(--vesta-gray-4)", lineHeight: 1.55 }}>{r.desc}</p>

                {/* Cal.com inline embed — real availability + auto prep email on booking */}
                <CalEmbed onBooked={handleBooked} />

                <p style={{ margin: "14px 0 0", fontSize: 12, color: "var(--vesta-gray-3)", textAlign: "center" }}>
                  {a.bookingHint}
                </p>
                <button type="button" onClick={back} style={{ marginTop: 16, background: "none", border: "none", padding: 0, color: "var(--vesta-gray-3)", fontSize: 13, cursor: "pointer", fontFamily: "inherit", display: "block", marginInline: "auto" }}>{a.back}</button>
              </>
            )}

            {/* Email capture — after scheduling */}
            {onEmail && (
              <>
                <div style={{ width: 48, height: 48, borderRadius: 999, background: "var(--vesta-green)", color: "#fff", display: "inline-flex", alignItems: "center", justifyContent: "center", fontSize: 22, marginBottom: 14 }}>✓</div>
                <h3 style={{ margin: "0 0 8px", fontSize: "clamp(18px, 1.6vw, 22px)", fontWeight: 700, color: "var(--vesta-black)", letterSpacing: "-0.015em", lineHeight: 1.25 }}>
                  {a.bookedTitle}
                </h3>
                <p style={{ margin: "0 0 20px", fontSize: 13, color: "var(--vesta-gray-3)", lineHeight: 1.55 }}>
                  {a.bookedBody}
                </p>
                <input
                  type="text" name="name" autoComplete="given-name" placeholder={a.namePlaceholder} value={name}
                  onChange={(e) => setName(e.target.value)}
                  style={{ width: "100%", padding: "13px 16px", borderRadius: 10, border: "none", background: "var(--vesta-gray-1)", fontSize: 14, color: "var(--vesta-black)", fontFamily: "inherit", outline: "none", boxSizing: "border-box", marginBottom: 10 }}
                />
                <input
                  type="email" name="email" autoComplete="email" inputMode="email" placeholder={a.emailPlaceholder} value={email} required
                  onChange={(e) => setEmail(e.target.value)}
                  style={{ width: "100%", padding: "13px 16px", borderRadius: 10, border: "none", background: "var(--vesta-gray-1)", fontSize: 14, color: "var(--vesta-black)", fontFamily: "inherit", outline: "none", boxSizing: "border-box", marginBottom: 10 }}
                />
                <div style={{ marginBottom: 14 }}>
                  <label style={{ display: "block", fontSize: 11, fontWeight: 700, letterSpacing: "0.05em", textTransform: "uppercase", color: "var(--vesta-gray-3)", marginBottom: 10 }}>{a.pickSlot}</label>
                  <div style={{ maxHeight: 280, overflowY: "auto", paddingRight: 4 }}>
                    {generateSlots(lang === "es" ? "es-ES" : "en-US").map((group) => (
                      <div key={group.dateLabel} style={{ marginBottom: 12 }}>
                        <div style={{ fontSize: 12, fontWeight: 700, color: "var(--vesta-gray-4)", marginBottom: 6 }}>{group.dateLabel}</div>
                        <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
                          {group.times.map((t) => {
                            const selected = apptSlot === t.iso;
                            return (
                              <button
                                key={t.iso}
                                type="button"
                                onClick={() => setApptSlot(t.iso)}
                                style={{
                                  all: "unset", cursor: "pointer",
                                  padding: "8px 14px", borderRadius: 999,
                                  background: selected ? "var(--vesta-green)" : "var(--vesta-gray-1)",
                                  color: selected ? "#fff" : "var(--vesta-black)",
                                  fontSize: 13, fontWeight: 700,
                                  transition: "background 150ms, color 150ms",
                                }}
                              >
                                {t.label}
                              </button>
                            );
                          })}
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
                <button
                  type="button"
                  disabled={!email.includes("@") || sending}
                  onClick={submit}
                  className="vm-btn vm-btn-green vm-btn-lg"
                  style={{ width: "100%", opacity: (!email.includes("@") || sending) ? 0.38 : 1, pointerEvents: (!email.includes("@") || sending) ? "none" : "auto", cursor: sending ? "wait" : "pointer" }}
                >
                  {sending ? a.sending : a.sendPrepButton}
                </button>
                {sendError && <p style={{ margin: "10px 0 0", fontSize: 12, color: "var(--vesta-orange)", textAlign: "center" }}>{sendError}</p>}
              </>
            )}

            {/* Done */}
            {onDone && (
              <div style={{ textAlign: "center", padding: "8px 0" }}>
                <div style={{ width: 56, height: 56, borderRadius: 999, background: "var(--vesta-green)", color: "#fff", display: "inline-flex", alignItems: "center", justifyContent: "center", fontSize: 26, marginBottom: 16 }}>✓</div>
                <h3 style={{ margin: "0 0 8px", fontSize: 22, fontWeight: 700, color: "var(--vesta-black)" }}>{a.doneTitle}</h3>
                <p style={{ margin: "0 0 24px", fontSize: 14, color: "var(--vesta-gray-3)", lineHeight: 1.55 }}>
                  {a.doneBody.split("{email}")[0]}<strong style={{ color: "var(--vesta-black)" }}>{email}</strong>{a.doneBody.split("{email}")[1]}
                </p>
                {(() => {
                  const sp = new URLSearchParams();
                  sp.set("r", r.id);
                  if (name) sp.set("n", name);
                  if (email) sp.set("e", email);
                  if (r.noSSN) sp.set("noSSN", "1");
                  if (answers.gig) sp.set("gig", "1");
                  if (answers.joint) sp.set("joint", "1");
                  sp.set("booked", "1");
                  return (
                    <a
                      href={`portal/?${sp.toString()}`}
                      className="vm-btn vm-btn-secondary"
                      style={{ width: "100%", boxSizing: "border-box" }}
                    >
                      {a.openPrepGuide}
                    </a>
                  );
                })()}
              </div>
            )}
          </div>
        </div>
      </div>
    </section>
  );
}

function App() {
  const [lang, setLang] = useState("en");
  const t = COPY[lang];
  return (
    <div data-screen-label="Clients home" data-surface="clients" lang={lang}>
      <VmNav surface="clients" links={[
        { href: "#start", label: t.nav.itin },
        { href: "/clients/guides/banking.html", label: t.nav.banking },
        { href: "/clients/resources.html", label: t.nav.resources },
      ]} />
      <ClientHero t={t} lang={lang} />
      <VmPartnerLogos />
      <ClientsWhat t={t} lang={lang} />
      <ClientsHow t={t} lang={lang} />
      <MeetGuide t={t} lang={lang} />
      <ClientsFind lang={lang} />
      <Trust t={t} lang={lang} />
      <ResourcesPreview t={t} lang={lang} />
      <ClientAssessment t={t} lang={lang} />
      <NewsletterIntake id="newsletter" surface="clients" />
      <CallToAction t={t} lang={lang} />
      <VmFooter surface="clients" />
      <LangSwitch lang={lang} setLang={setLang} />
    </div>
  );
}

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