/* global React, VmNav, VmFooter, VmIcon, VmCard, VmPartnerLogos */
const { useState } = React;

/* ─── Section palette ───────────────────────────────────────────────
   01 Tax & ITIN   white      green numbers   dark dividers
   02 Banking      warm sand  amber numbers   sand dividers
   03 Savings      pale sage  green numbers   sage dividers
   04 Retirement   near-black coral numbers   translucent dividers
──────────────────────────────────────────────────────────────────── */
const SECTIONS_META = [
  { bg: "#FFFFFF",  textColor: "var(--vesta-black)", accent: "var(--vesta-green)",  divider: "rgba(0,0,0,0.10)",  eyebrowColor: "var(--vesta-green)" },
  { bg: "#F5F0E8",  textColor: "var(--vesta-black)", accent: "#9B6B00",             divider: "rgba(0,0,0,0.10)",  eyebrowColor: "#9B6B00" },
  { bg: "#FFFFFF",  textColor: "var(--vesta-black)", accent: "var(--vesta-green)",  divider: "rgba(0,0,0,0.10)",  eyebrowColor: "var(--vesta-green)" },
  { bg: "#1A1A1A",  textColor: "#FFFFFF",            accent: "var(--vesta-orange)", divider: "rgba(255,255,255,0.12)", eyebrowColor: "rgba(255,255,255,0.55)" },
];

const COPY = {
  en: {
    nav: { itin: "Get an ITIN", banking: "Open a bank account", resources: "Resources" },
    eyebrow: "Free guides",
    title: "The financial knowledge you deserve, in your language.",
    lede: "Clear, honest guides on taxes, banking, credit, and savings, written by people who know this work and the communities it serves.",
    sections: [
      {
        n: "01",
        eyebrow: "Tax & ITIN",
        title: "Your tax ID is your first key to financial life in the U.S.",
        lede: "An ITIN lets you file taxes, open accounts, and access programs most people don't know are available to them. Here's how to use it.",
        cta: null,
        items: [
          {
            num: "01",
            href: "/clients/guides/itin-basics.html",
            title: "ITIN Basics: What it is and how to get one",
            body: "No Social Security Number? You can still participate in the U.S. financial system. Here's how.",
            time: "6 min",
          },
          {
            num: "02",
            href: "/clients/guides/itin-documents.html",
            title: "The documents you need, and which ones you don't",
            body: "Walk in prepared the first time. A checklist reviewed by our Certified Acceptance Agents.",
            time: "5 min",
          },
          {
            num: "03",
            href: "/clients/guides/itin-filing.html",
            title: "Why filing taxes matters, even if you weren't born here",
            body: "Filing creates a record that works in your favor: refunds, credits, and future applications.",
            time: "7 min",
          },
        ],
      },
      {
        n: "02",
        eyebrow: "Banking",
        title: "You can open a bank account, even without a Social Security Number.",
        lede: "Having money in a bank is safer than cash, cheaper than check cashing, and opens the door to savings and credit.",
        cta: null,
        items: [
          {
            num: "01",
            href: "/clients/guides/banking.html",
            title: "How to open your first U.S. bank account with an ITIN",
            body: "What to bring, what to ask, and which red flags to watch for before you sign anything.",
            time: "6 min",
          },
          {
            num: "02",
            href: "/clients/guides/remittances.html",
            title: "Sending money home: what's cheapest, safest, and fastest",
            body: "Fees can eat 5–10% of every transfer. Here's an honest side-by-side of your real options.",
            time: "6 min",
          },
        ],
      },
      {
        n: "03",
        eyebrow: "Savings & Credit",
        title: "Credit isn't just for people who grew up here. It's for you.",
        lede: "With an ITIN, you can start building a credit score. Here's the safest way to do it.",
        cta: null,
        items: [
          {
            num: "01",
            href: "/clients/guides/credit-building.html",
            title: "Building credit with an ITIN: a real guide, not a sales pitch",
            body: "What a credit score actually is, what affects it, and what to avoid. Straight from a Vesta workshop.",
            time: "8 min",
          },
          {
            num: "02",
            href: "/clients/guides/credit-start.html",
            title: "Three concrete steps to start building credit this month",
            body: "Check your report, choose a starter product, set up autopay. You can do all three this week.",
            time: "5 min",
          },
        ],
      },
      {
        n: "04",
        eyebrow: "Retirement",
        title: "You can save for the future, even without a Social Security Number.",
        lede: "IRAs and 401(k)s are open to ITIN holders. Here's what's available and how the tax benefits work.",
        cta: null,
        items: [
          {
            num: "01",
            href: "/clients/guides/retirement.html",
            title: "IRAs, 401(k)s, and what ITIN holders can actually use",
            body: "The retirement system isn't only for people with decades of U.S. work history. Here's your starting point.",
            time: "7 min",
          },
        ],
      },
    ],

    faqEyebrow: "Questions we hear often",
    faqTitle: "Honest answers, no jargon.",
    faq: [
      { q: "How do I access these services?", a: "Services are available through nonprofit partners. If your local organization works with Vesta, services are free for you. Contact us or ask your organization. You should never pay out of pocket for help getting an ITIN." },
      { q: "How long does the ITIN process take?", a: "Digital intake takes most people under 15 minutes from their phone. Once submitted, the IRS typically processes ITIN applications in 6–11 weeks. We'll keep you updated so you're never wondering what's happening." },
      { q: "Do I need a Social Security Number to use Vesta?", a: "No. Vesta exists specifically for people who don't have a Social Security Number, including ITIN holders and people applying for one for the first time. Your immigration status does not affect your eligibility." },
      { q: "Can I do this from my phone?", a: "Yes. The entire process is designed to work on a smartphone. You can complete your intake, upload documents, and check your status without a computer or printer." },
      { q: "Is my personal information safe?", a: "Yes. We use secure, encrypted systems. We never share your information without your consent. If you're concerned about your home address, we offer address protection through a secure PO Box so your personal address is never exposed." },
      { q: "I'm self-employed. Can you help with my taxes?", a: "Yes, and this is actually something we specialize in. Gig workers, freelancers, and small business owners often file a Schedule C. We help you organize your expenses before your appointment so the session stays on track and you don't leave money on the table." },
      { q: "What happens after I file my taxes?", a: "Filing is the beginning, not the end. After your return, we connect you to next steps: banking, savings, and longer-term financial resources, all matched to where you are right now. You won't have to figure out next steps alone." },
      { q: "Can someone help me in Spanish?", a: "Yes. Services are available in English and Spanish. Additional languages are coming. If you have a language need not yet covered, contact us. We want to know." },
    ],
    helpEyebrow: "Still have questions?",
    helpTitle: "A real person is one message away.",
    helpBody: "Email, text, or schedule a call, in English or Spanish. Most people hear back within two hours.",
    helpCta: "Talk to a guide",
  },
  es: {
    nav: { itin: "Solicita tu ITIN", banking: "Abre una cuenta bancaria", resources: "Recursos" },
    eyebrow: "Guías gratis",
    title: "El conocimiento financiero que mereces, en tu idioma.",
    lede: "Guías claras y honestas sobre impuestos, bancos, crédito y ahorro, escritas por personas que conocen este trabajo y las comunidades a las que sirven.",
    sections: [
      {
        n: "01",
        eyebrow: "Impuestos e ITIN",
        title: "Tu número de identificación fiscal es tu primera llave a la vida financiera en EE. UU.",
        lede: "Un ITIN te permite declarar impuestos, abrir cuentas y acceder a programas que muchas personas no saben que están disponibles para ellas. Aquí te explicamos cómo usarlo.",
        cta: null,
        items: [
          {
            num: "01",
            href: "/clients/guides/itin-basics.html",
            title: "¿Qué es un ITIN y cómo obtenerlo?",
            body: "Sin Número de Seguro Social igual puedes participar en el sistema financiero. Así es cómo.",
            time: "6 min",
          },
          {
            num: "02",
            href: "/clients/guides/itin-documents.html",
            title: "Los documentos que necesitas, y cuáles no",
            body: "Ve preparado la primera vez. Una lista revisada por nuestros Agentes de Aceptación Certificados.",
            time: "5 min",
          },
          {
            num: "03",
            href: "/clients/guides/itin-filing.html",
            title: "Por qué declarar impuestos importa, aunque no hayas nacido aquí",
            body: "Declarar crea un historial que trabaja a tu favor: reembolsos, créditos y solicitudes futuras.",
            time: "7 min",
          },
        ],
      },
      {
        n: "02",
        eyebrow: "Bancos",
        title: "Puedes abrir una cuenta bancaria, incluso sin Número de Seguro Social.",
        lede: "Tener dinero en un banco es más seguro, más barato que las casas de cambio y abre la puerta al crédito.",
        cta: null,
        items: [
          {
            num: "01",
            href: "/clients/guides/banking.html",
            title: "Cómo abrir tu primera cuenta bancaria en EE. UU. con un ITIN",
            body: "Qué llevar, qué preguntar y qué señales de alerta observar antes de firmar cualquier cosa.",
            time: "6 min",
          },
          {
            num: "02",
            href: "/clients/guides/remittances.html",
            title: "Enviar dinero a casa: lo más barato, seguro y rápido",
            body: "Las comisiones pueden consumir hasta el 10% de lo que envías. Aquí comparamos tus opciones reales.",
            time: "6 min",
          },
        ],
      },
      {
        n: "03",
        eyebrow: "Ahorro y Crédito",
        title: "El crédito no es solo para quienes crecieron aquí. También es para ti.",
        lede: "Con un ITIN puedes empezar a construir historial crediticio. Te mostramos la forma más segura.",
        cta: null,
        items: [
          {
            num: "01",
            href: "/clients/guides/credit-building.html",
            title: "Construyendo crédito con un ITIN: una guía real, no un argumento de venta",
            body: "Qué es un puntaje crediticio, qué lo afecta y qué evitar. Directo de un taller financiero de Vesta.",
            time: "8 min",
          },
          {
            num: "02",
            href: "/clients/guides/credit-start.html",
            title: "Tres pasos concretos para empezar a construir crédito este mes",
            body: "Verifica tu reporte, elige un producto inicial, configura autopago. Puedes hacer los tres esta semana.",
            time: "5 min",
          },
        ],
      },
      {
        n: "04",
        eyebrow: "Jubilación",
        title: "Puedes ahorrar para el futuro, aunque no tengas Número de Seguro Social.",
        lede: "Las IRA y los 401(k) están disponibles para titulares de ITIN. Aquí explicamos cómo funcionan.",
        cta: null,
        items: [
          {
            num: "01",
            href: "/clients/guides/retirement.html",
            title: "IRA, 401(k) y qué pueden usar realmente los titulares de ITIN",
            body: "El sistema de jubilación no es solo para quienes llevan décadas en EE. UU. Aquí tu punto de partida.",
            time: "7 min",
          },
        ],
      },
    ],

    faqEyebrow: "Preguntas frecuentes",
    faqTitle: "Respuestas honestas, sin tecnicismos.",
    faq: [
      { q: "¿Cómo accedo a estos servicios?", a: "Los servicios están disponibles a través de organizaciones sin fines de lucro. Si tu organización local trabaja con Vesta, los servicios son gratuitos para ti. Contáctanos o pregúntale a tu organización. Nunca deberías pagar de tu bolsillo por ayuda para obtener un ITIN." },
      { q: "¿Cuánto tarda el proceso del ITIN?", a: "El registro digital toma a la mayoría de las personas menos de 15 minutos desde su teléfono. Una vez enviado, el IRS generalmente procesa las solicitudes de ITIN en 6 a 11 semanas. Te mantendremos informado para que nunca te preguntes qué está pasando." },
      { q: "¿Necesito un Número de Seguro Social para usar Vesta?", a: "No. Vesta existe específicamente para personas que no tienen Número de Seguro Social, incluyendo titulares de ITIN y personas que solicitan uno por primera vez. Tu estatus migratorio no afecta tu elegibilidad." },
      { q: "¿Puedo hacerlo desde mi teléfono?", a: "Sí. Todo el proceso está diseñado para funcionar en un teléfono inteligente. Puedes completar tu registro, subir documentos y verificar tu estado sin computadora ni impresora." },
      { q: "¿Mi información personal está segura?", a: "Sí. Usamos sistemas seguros y cifrados. Nunca compartimos tu información sin tu consentimiento. Si te preocupa tu dirección de casa, ofrecemos protección de dirección a través de un apartado postal seguro para que tu domicilio personal nunca quede expuesto." },
      { q: "Soy trabajador independiente. ¿Pueden ayudarme con mis impuestos?", a: "Sí, y esto es algo en lo que nos especializamos. Los trabajadores de plataformas, freelancers y dueños de pequeños negocios suelen presentar el Anexo C. Te ayudamos a organizar tus gastos antes de tu cita para que la sesión sea eficiente y no dejes dinero sobre la mesa." },
      { q: "¿Qué pasa después de declarar mis impuestos?", a: "Declarar es el comienzo, no el final. Después de tu declaración, te conectamos con los siguientes pasos: banca, ahorro y recursos financieros a largo plazo, todos adaptados a donde estás ahora. No tendrás que descubrir los próximos pasos solo." },
      { q: "¿Pueden ayudarme en español?", a: "Sí. Los servicios están disponibles en inglés y español. Próximamente habrá más idiomas. Si tienes una necesidad de idioma que aún no está cubierta, contáctanos. Queremos saberlo." },
    ],
    helpEyebrow: "¿Aún tienes preguntas?",
    helpTitle: "Una persona real está a un mensaje de distancia.",
    helpBody: "Correo, mensaje o agenda una llamada, en inglés o español. La mayoría recibe respuesta en menos de dos horas.",
    helpCta: "Habla con una guía",
  },
};

/* ─── Language Switch ──────────────────────────────────────────────
   Fixed bottom-right pill, always visible during scroll
──────────────────────────────────────────────────────────────────── */
function LangSwitch({ lang, setLang }) {
  return (
    <div
      role="group"
      aria-label="Language selector"
      style={{
        position: "fixed",
        bottom: 28,
        right: 28,
        zIndex: 300,
        background: "var(--vesta-black)",
        borderRadius: 999,
        padding: 5,
        display: "flex",
        gap: 2,
        boxShadow: "0 8px 32px rgba(0,0,0,0.22), 0 1px 4px rgba(0,0,0,0.12)",
      }}
    >
      {[{ code: "en", label: "EN" }, { code: "es", label: "ES" }].map((l) => (
        <button
          key={l.code}
          type="button"
          aria-pressed={lang === l.code}
          onClick={() => setLang(l.code)}
          style={{
            fontFamily: "var(--font-sans)",
            fontSize: 12,
            fontWeight: 700,
            letterSpacing: "0.06em",
            padding: "9px 18px",
            borderRadius: 999,
            border: "none",
            background: lang === l.code ? "var(--vesta-orange)" : "transparent",
            color: lang === l.code ? "#fff" : "rgba(255,255,255,0.6)",
            cursor: "pointer",
            transition: "all 150ms ease",
          }}
        >
          {l.label}
        </button>
      ))}
    </div>
  );
}

/* ─── Resource Section ─────────────────────────────────────────────
   Full-width colored background, PartnersWhat-style header + 2-col
   numbered grid of items
──────────────────────────────────────────────────────────────────── */
function ResourceSection({ section, meta, lang }) {
  const isDark = meta.textColor === "#FFFFFF";
  return (
    <section style={{ background: meta.bg, paddingBlock: "clamp(64px, 7vw, 104px)" }}>
      <div className="vm-container">

        {/* Section header — full width */}
        <div style={{ marginBottom: "clamp(40px, 5vw, 64px)" }}>
          <span className="vm-eyebrow" style={{ color: meta.eyebrowColor }}>{section.eyebrow}</span>
          <h2 style={{
            margin: "14px 0 0",
            fontSize: "clamp(22px, 2.4vw, 34px)",
            fontWeight: 700,
            letterSpacing: "-0.025em",
            color: meta.textColor,
            lineHeight: 1.15,
          }}>{section.title}</h2>
          <p style={{
            margin: "18px 0 0",
            fontSize: "clamp(15px, 1.1vw, 17px)",
            color: isDark ? "rgba(255,255,255,0.72)" : "var(--vesta-gray-4)",
            lineHeight: 1.65,
            maxWidth: "60ch",
          }}>{section.lede}</p>
        </div>

        {/* Numbered items — 3 column cards */}
        <ol
          className="vm-how-cols"
          style={{
            listStyle: "none", padding: 0, margin: 0,
            display: "grid",
            gridTemplateColumns: "repeat(auto-fit, minmax(240px, 1fr))",
            gap: "clamp(24px, 3vw, 48px)",
          }}
        >
          {section.items.map((it) => (
            <li key={it.num} style={{ display: "flex" }}>
              <a
                href={it.href || "#"}
                style={{
                  display: "flex",
                  flexDirection: "column",
                  gap: 10,
                  paddingTop: 24,
                  borderTop: `1px solid ${meta.divider}`,
                  textDecoration: "none",
                  color: "inherit",
                  transition: "opacity 150ms ease",
                  width: "100%",
                }}
                onMouseEnter={e => e.currentTarget.style.opacity = "0.75"}
                onMouseLeave={e => e.currentTarget.style.opacity = "1"}
              >
                <span style={{
                  fontSize: 11,
                  fontWeight: 700,
                  color: meta.accent,
                  letterSpacing: "0.08em",
                  lineHeight: 1,
                }}>{it.num}</span>
                <h3 style={{
                  margin: 0,
                  fontSize: "clamp(16px, 1.3vw, 20px)",
                  fontWeight: 700,
                  color: meta.textColor,
                  letterSpacing: "-0.02em",
                  lineHeight: 1.2,
                }}>{it.title}</h3>
                <p style={{
                  margin: 0,
                  fontSize: 13,
                  color: isDark ? "rgba(255,255,255,0.55)" : "var(--vesta-gray-3)",
                  lineHeight: 1.55,
                }}>{it.body}</p>
                <div style={{ display: "flex", alignItems: "center", gap: 12, marginTop: "auto", paddingTop: 8 }}>
                  <span style={{
                    fontSize: 13,
                    fontWeight: 700,
                    color: meta.accent,
                    letterSpacing: "0.02em",
                  }}>{lang === "es" ? "Leer guía →" : "Read guide →"}</span>
                  {it.time && (
                    <span style={{
                      fontSize: 11,
                      fontWeight: 600,
                      color: isDark ? "rgba(255,255,255,0.35)" : "rgba(0,0,0,0.3)",
                      letterSpacing: "0.04em",
                    }}>{it.time} read</span>
                  )}
                </div>
              </a>
            </li>
          ))}
        </ol>

      </div>
    </section>
  );
}

/* ─── FAQ ──────────────────────────────────────────────────────── */
function ClientsFaq({ t }) {
  const [open, setOpen] = React.useState(null);
  const toggle = (i) => setOpen(open === i ? null : i);

  return (
    <section id="faq" className="vm-section">
      <div className="vm-container">
        <div style={{
          display: "grid",
          gridTemplateColumns: "repeat(auto-fit, minmax(280px, 1fr))",
          gap: "clamp(32px, 4vw, 80px)",
          paddingBottom: "clamp(40px, 4vw, 64px)",
          borderBottom: "1px solid var(--vesta-gray-2)",
          marginBottom: "clamp(8px, 2vw, 24px)",
        }}>
          <div>
            <span className="vm-eyebrow">{t.faqEyebrow}</span>
            <h2 className="vm-h1" style={{ marginTop: 14 }}>{t.faqTitle}</h2>
          </div>
        </div>

        <div>
          {t.faq.map((item, i) => (
            <div key={i} style={{ borderBottom: "1px solid var(--vesta-gray-2)" }}>
              <button
                type="button"
                onClick={() => toggle(i)}
                aria-expanded={open === i}
                style={{
                  width: "100%",
                  display: "grid",
                  gridTemplateColumns: "1fr 24px",
                  alignItems: "center",
                  gap: 16,
                  padding: "clamp(18px, 2vw, 24px) 0",
                  background: "none",
                  border: "none",
                  cursor: "pointer",
                  textAlign: "left",
                  fontFamily: "var(--font-sans)",
                }}
              >
                <span style={{
                  fontSize: "clamp(15px, 1.2vw, 18px)",
                  fontWeight: 600,
                  letterSpacing: "-0.015em",
                  color: "var(--vesta-black)",
                  lineHeight: 1.3,
                }}>{item.q}</span>
                <span style={{
                  fontSize: 20,
                  fontWeight: 300,
                  color: "var(--vesta-gray-3)",
                  lineHeight: 1,
                  transform: open === i ? "rotate(45deg)" : "none",
                  transition: "transform 0.2s ease",
                  display: "block",
                  textAlign: "center",
                }}>+</span>
              </button>
              {open === i && (
                <p className="vm-body" style={{
                  margin: "0 0 clamp(18px, 2vw, 24px)",
                  color: "var(--vesta-gray-4)",
                  maxWidth: "70ch",
                  lineHeight: 1.7,
                }}>{item.a}</p>
              )}
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ─── App ─────────────────────────────────────────────────────── */
function App() {
  const [lang, setLang] = useState("en");
  const t = COPY[lang];

  return (
    <div data-screen-label="Clients resources" lang={lang}>
      <VmNav surface="clients" links={[
        { href: "/clients/#start", label: t.nav.itin },
        { href: "/clients/guides/banking.html", label: t.nav.banking },
        { href: "/clients/resources.html", label: t.nav.resources, active: true },
      ]} />

      {/* Hero */}
      <header className="vm-section" style={{ paddingTop: "clamp(48px, 6vw, 80px)", paddingBottom: "clamp(48px, 6vw, 80px)" }}>
        <div className="vm-container">
          <div className="vm-grid" style={{ alignItems: "end" }}>
            <div className="vm-col-7">
              <span className="vm-eyebrow">{t.eyebrow}</span>
              <h1 className="vm-display" style={{ marginTop: 14 }}>{t.title}</h1>
              <p className="vm-lede" style={{ marginTop: 16, maxWidth: "48ch" }}>{t.lede}</p>
            </div>
            <div className="vm-col-5">
              <img
                src="newsletter-1.png"
                alt="Vesta community"
                style={{ width: "100%", height: "clamp(280px, 32vw, 440px)", borderRadius: 16, objectFit: "cover", objectPosition: "center top" }}
              />
            </div>
          </div>
        </div>
      </header>

      <VmPartnerLogos />

      {/* Resource sections — one per topic, each with its own bg */}
      {t.sections.map((section, i) => (
        <ResourceSection
          key={section.n}
          section={section}
          meta={SECTIONS_META[i]}
          lang={lang}
        />
      ))}

      <ClientsFaq t={t} />

      <section className="vm-section vm-section-orange" id="help">
        <div className="vm-container">
          <div className="vm-grid" style={{ alignItems: "center" }}>
            <div className="vm-col-7">
              <span className="vm-eyebrow">{t.helpEyebrow}</span>
              <h2 className="vm-h1" style={{ marginTop: 14, color: "#fff" }}>{t.helpTitle}</h2>
              <p className="vm-lede" style={{ marginTop: 16 }}>{t.helpBody}</p>
            </div>
            <div className="vm-col-5">
              <a href="https://calendly.com/growwithvesta/30min" className="vm-btn vm-btn-green vm-btn-lg">{t.helpCta}</a>
            </div>
          </div>
        </div>
      </section>

      <VmFooter surface="clients" />

      {/* Language switch — always visible */}
      <LangSwitch lang={lang} setLang={setLang} />
    </div>
  );
}

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