// i18n.jsx — translations + provider for Hair by Gra
// Two locales: EN (default) and ES. Spanish-first audience is a real one for Gra.
// Components consume via `useI18n()` which returns { lang, setLang, T }.
// T is the active translation tree, so usage reads naturally: T.nav.services.

const TRANSLATIONS = {
  en: {
    code: "en",
    flag: "EN",
    nav: {
      services: "Services",
      gallery: "Gallery",
      about: "About",
      contact: "Contact",
      book: "Book now",
      bookFull: "Book an appointment",
    },
    hero: {
      eyebrow: "Long Island, NY · Est. 2019",
      byAppointment: "By appointment only",
      headlineA: "Hair that",
      headlineB: "moves",
      headlineBSuffix: " with",
      headlineC: "you",
      lede: "Editorial cuts, dimensional color, and bridal styling from Graciela Alvarado Rodríguez. A private studio where every chair feels considered, never rushed.",
      ctaBook: "Book your appointment",
      ctaExplore: "Explore services",
      badge: { a: "Hair", b: "by", c: "Gra" },
      stats: [
        { k: "15+", v: "Years styling" },
        { k: "1k+", v: "Clients served" },
        { k: "★★★★★", v: "Five-star rated" },
        { k: "100%", v: "By appointment" },
      ],
    },
    marquee: ["Extensions", "Blowouts", "Balayage", "Bridal", "Color correction"],
    services: {
      eyebrow: "Menu",
      titlePre: "Services &",
      titleEm: "care",
      intro: "Every service starts with a consultation. Prices are starting points; final quote depends on length, density, and product. All chemical work requires a strand test on first visit.",
      cta: "Reserve a chair",
      from: "From",
      byQuote: "By quote",
      custom: "Custom",
      items: [
        { num: "01", pre: "Signature",       em: "cut",         desc: "Consultation, shampoo, precision cut, and finish.",                price: "$85",       dur: "75 min" },
        { num: "02", pre: "Balayage &",      em: "highlights",  desc: "Hand-painted dimension tailored to your tone and lifestyle.",      price: "$220",      dur: "3 hrs" },
        { num: "03", pre: "Single-process",  em: "color",       desc: "All-over color refresh, root touch-up or full coverage.",          price: "$120",      dur: "2 hrs" },
        { num: "04", pre: "Bridal &",        em: "events",      desc: "Trial plus day-of styling. Travel available within Long Island.",  price: "$300",      dur: "2 hrs" },
        { num: "05", pre: "Smoothing",       em: "treatment",   desc: "Keratin or bond-rebuilding treatment for shine and structure.",    price: "$180",      dur: "2.5 hrs" },
        { num: "06", pre: "Blowout &",       em: "style",       desc: "Wash, blow-dry, and finished style: waves, sleek, or volume.",      price: "$55",       dur: "45 min" },
        { num: "07", pre: "Hair",            em: "extensions",  desc: "Hand-tied wefts. Consultation and certified placement.",           price: "By quote",  dur: "Custom" },
      ],
    },
    gallery: {
      eyebrow: "Portfolio",
      titlePre: "Recent",
      titleEm: "work",
      introA: "A selection from the last twelve months: color transformations, editorial cuts, and bridal styling. Follow ",
      introLink: "@hairby.gra",
      introB: " for the full archive.",
      tabs: { all: "All", color: "Color", cuts: "Cuts", bridal: "Bridal", extensions: "Extensions" },
      tiles: [
        "Bridal, Sept '25", "Balayage, caramel", "Lob, blunt finish",
        "Hand-tied wefts", "Glossy single-process", "Soft waves, evening",
        "Curtain bangs", "Money-piece",
      ],
    },
    testimonial: {
      eyebrow: "From the chair",
      quote: { a: "Gra didn't just give me ", em: "hair I love", b: ". She gave me a color that actually suits my skin, my job, and the way I live. I drive forty minutes for this chair." },
      cite: "Ana Rodríguez · Client since 2015",
    },
    about: {
      eyebrow: "About the stylist",
      role: "Owner · Lead stylist · Colorist",
      bodyA: "Born in Costa Rica and trained in the United States, Graciela built Hair by Gra to be the kind of studio she always wanted to walk into: quiet, careful, and tuned to the person in the chair.",
      bodyB: { a: "Her work sits at the intersection of editorial precision and lived-in softness. Balayage you can grow out without panic, cuts that fall into place after a wash, bridal styling that still looks like ", em: "you", b: " in the photos." },
      pull: "The brief is never the haircut. It's the morning after the haircut. That's what we're designing for.",
      creds: [
        { k: "'19",    v: "Studio est." },
        { k: "EN · ES", v: "Bilingual" },
        { k: "L.I., NY", v: "Private studio" },
      ],
      portrait: "[ Graciela at the chair, editorial portrait ]",
      portraitTag: "graciela.jpg · 4:5",
    },
    contact: {
      eyebrow: "Get in touch",
      titlePre: "Let's plan your",
      titleEm: "next look.",
      lede: "Booking is by appointment. The easiest way to reach Gra is by text or WhatsApp. New-client consultations are complimentary.",
      cta: "Open booking form",
      hoursA: "Hours · Tue–Sat · 10a–7p",
      hoursB: "Sun · 11a–4p (bridal only)",
      ch: {
        whatsapp: "WhatsApp · preferred",
        text: "Text message",
        ig: "Instagram",
        fb: "Facebook",
        fbVal: "Hair by Gra",
      },
    },
    footer: {
      rights: "Hair by Gra · Graciela Alvarado Rodríguez",
      locale: "Long Island, NY",
    },
    modal: {
      eyebrow: "Booking inquiry",
      titlePre: "Reserve a",
      titleEm: "chair",
      lede: "Tell Gra a little about what you're after. She'll confirm by text within 24 hours.",
      name: "Name", namePh: "Your full name",
      date: "Preferred date",
      service: "Service",
      notes: "Notes (optional)",
      notesPh: "Inspiration, hair history, anything Gra should know",
      ctaSend: "Send via text",
      ctaWa: "Send via WhatsApp",
      successPre: "Inquiry",
      successEm: "sent",
      successLede: (name) => `Thanks, ${name || 'friend'}. Your message has opened in your messaging app. Gra will reply within 24 hours.`,
      close: "Close",
      notSure: "Not sure yet, consultation",
      msg: (f) => `Hi Gra! I'd like to book an appointment.\n\nName: ${f.name || '(not given)'}\nService: ${f.service}\nPreferred date: ${f.date || 'flexible'}\n\nNotes:\n${f.note || '(none)'}`,
    },
    placeholders: {
      heroPortrait: "[ Portrait of Graciela, styling chair, soft daylight ]",
      heroTag: "portrait.jpg · 4:5",
    },
    image: "image",
  },

  es: {
    code: "es",
    flag: "ES",
    nav: {
      services: "Servicios",
      gallery: "Galería",
      about: "Sobre Gra",
      contact: "Contacto",
      book: "Reservar",
      bookFull: "Reservar una cita",
    },
    hero: {
      eyebrow: "Long Island, NY · Desde 2019",
      byAppointment: "Solo con cita previa",
      headlineA: "Cabello que",
      headlineB: "se mueve",
      headlineBSuffix: "",
      headlineC: "contigo",
      lede: "Cortes editoriales, color dimensional y peinado nupcial de Graciela Alvarado Rodríguez. Un estudio privado donde cada silla se siente atendida, nunca apresurada.",
      ctaBook: "Reserva tu cita",
      ctaExplore: "Ver servicios",
      badge: { a: "Hair", b: "by", c: "Gra" },
      stats: [
        { k: "15+", v: "Años estilizando" },
        { k: "1k+", v: "Clientas atendidas" },
        { k: "★★★★★", v: "Cinco estrellas" },
        { k: "100%", v: "Solo con cita" },
      ],
    },
    marquee: ["Extensiones", "Blowouts", "Balayage", "Novias", "Corrección de color"],
    services: {
      eyebrow: "Carta",
      titlePre: "Servicios y",
      titleEm: "cuidado",
      intro: "Cada servicio comienza con una consulta. Los precios son puntos de partida; la cotización final depende del largo, la densidad y el producto. Todo trabajo químico requiere una prueba de mecha en la primera visita.",
      cta: "Reserva tu silla",
      from: "Desde",
      byQuote: "A cotizar",
      custom: "A medida",
      items: [
        { num: "01", pre: "Corte de",         em: "firma",        desc: "Consulta, lavado, corte de precisión y acabado.",                       price: "$85",        dur: "75 min" },
        { num: "02", pre: "Balayage y",       em: "mechas",       desc: "Dimensión pintada a mano, adaptada a tu tono y estilo de vida.",        price: "$220",       dur: "3 hrs" },
        { num: "03", pre: "Color",            em: "uniforme",     desc: "Refresco de color, retoque de raíz o cobertura completa.",              price: "$120",       dur: "2 hrs" },
        { num: "04", pre: "Novias y",         em: "eventos",      desc: "Prueba más styling el día de. Servicio a domicilio en Long Island.",    price: "$300",       dur: "2 hrs" },
        { num: "05", pre: "Tratamiento",      em: "alisante",     desc: "Keratina o reconstrucción molecular para brillo y estructura.",         price: "$180",       dur: "2.5 hrs" },
        { num: "06", pre: "Blowout y",        em: "peinado",      desc: "Lavado, secado y peinado. Ondas, sleek o volumen.",                     price: "$55",        dur: "45 min" },
        { num: "07", pre: "Extensiones",      em: "de cabello",   desc: "Wefts cosidas a mano. Consulta y colocación certificada.",              price: "A cotizar",  dur: "A medida" },
      ],
    },
    gallery: {
      eyebrow: "Portafolio",
      titlePre: "Trabajo",
      titleEm: "reciente",
      introA: "Una selección de los últimos doce meses: transformaciones de color, cortes editoriales y novias. Sigue ",
      introLink: "@hairby.gra",
      introB: " para el archivo completo.",
      tabs: { all: "Todo", color: "Color", cuts: "Cortes", bridal: "Novias", extensions: "Extensiones" },
      tiles: [
        "Novia, sep. '25", "Balayage, caramelo", "Lob, acabado recto",
        "Wefts cosidas a mano", "Color uniforme con brillo", "Ondas suaves, noche",
        "Flequillo cortina", "Money-piece",
      ],
    },
    testimonial: {
      eyebrow: "Desde la silla",
      quote: { a: "Gra no solo me dio ", em: "un cabello que amo", b: ". Me dio un color que de verdad va con mi piel, mi trabajo y mi forma de vivir. Manejo cuarenta minutos por esta silla." },
      cite: "Ana Rodríguez · Clienta desde 2015",
    },
    about: {
      eyebrow: "Sobre la estilista",
      role: "Propietaria · Estilista principal · Colorista",
      bodyA: "Nacida en Costa Rica y formada en Estados Unidos, Graciela creó Hair by Gra para ser el tipo de estudio al que ella siempre quiso entrar: tranquilo, cuidadoso y atento a la persona en la silla.",
      bodyB: { a: "Su trabajo vive entre la precisión editorial y la suavidad vivida. Balayage que puedes dejar crecer sin pánico, cortes que caen en su sitio después de un lavado, peinados de novia que todavía se ven a ", em: "ti", b: " en las fotos." },
      pull: "El brief nunca es el corte. Es la mañana siguiente al corte. Eso es lo que estamos diseñando.",
      creds: [
        { k: "'19",     v: "Estudio fundado" },
        { k: "ES · EN", v: "Bilingüe" },
        { k: "L.I., NY", v: "Estudio privado" },
      ],
      portrait: "[ Graciela en la silla, retrato editorial ]",
      portraitTag: "graciela.jpg · 4:5",
    },
    contact: {
      eyebrow: "Contacto",
      titlePre: "Planeemos tu",
      titleEm: "próximo look.",
      lede: "Las reservas son solo con cita. La forma más fácil de contactar a Gra es por mensaje o WhatsApp. Las consultas para clientas nuevas son gratuitas.",
      cta: "Abrir formulario",
      hoursA: "Horario · Mar–Sáb · 10a–7p",
      hoursB: "Dom · 11a–4p (solo novias)",
      ch: {
        whatsapp: "WhatsApp · preferido",
        text: "Mensaje de texto",
        ig: "Instagram",
        fb: "Facebook",
        fbVal: "Hair by Gra",
      },
    },
    footer: {
      rights: "Hair by Gra · Graciela Alvarado Rodríguez",
      locale: "Long Island, NY",
    },
    modal: {
      eyebrow: "Solicitud de reserva",
      titlePre: "Reserva una",
      titleEm: "silla",
      lede: "Cuéntale a Gra qué buscas. Te confirmará por mensaje en menos de 24 horas.",
      name: "Nombre", namePh: "Tu nombre completo",
      date: "Fecha preferida",
      service: "Servicio",
      notes: "Notas (opcional)",
      notesPh: "Inspiración, historia de tu cabello, cualquier cosa que Gra deba saber",
      ctaSend: "Enviar por mensaje",
      ctaWa: "Enviar por WhatsApp",
      successPre: "Solicitud",
      successEm: "enviada",
      successLede: (name) => `Gracias, ${name || 'amiga'}. Tu mensaje se abrió en tu app de mensajería. Gra responderá en menos de 24 horas.`,
      close: "Cerrar",
      notSure: "Aún no estoy segura, consulta",
      msg: (f) => `¡Hola Gra! Me gustaría reservar una cita.\n\nNombre: ${f.name || '(no indicado)'}\nServicio: ${f.service}\nFecha preferida: ${f.date || 'flexible'}\n\nNotas:\n${f.note || '(ninguna)'}`,
    },
    placeholders: {
      heroPortrait: "[ Retrato de Graciela, silla de styling, luz natural suave ]",
      heroTag: "portrait.jpg · 4:5",
    },
    image: "imagen",
  },
};

const I18nContext = React.createContext(null);
const LANG_STORAGE_KEY = "hbg-lang";

function readStoredLang() {
  try {
    const v = window.localStorage.getItem(LANG_STORAGE_KEY);
    return v === "en" || v === "es" ? v : null;
  } catch (_) { return null; }
}

function LangPicker({ onChoose }) {
  return (
    <div className="lang-picker-backdrop" role="dialog" aria-modal="true" aria-label="Choose your language">
      <div className="lang-picker">
        <img src="uploads/logo1.png" alt="Hair by Gra" className="lang-picker-logo" />
        <div className="lang-picker-eyebrow">Welcome · Bienvenida</div>
        <h2 className="lang-picker-title">
          Choose your <em>language</em><br />Elige tu <em>idioma</em>
        </h2>
        <div className="lang-picker-buttons">
          <button className="lang-picker-btn" onClick={() => onChoose("en")}>
            <span className="flag">EN</span>
            <span className="label">English</span>
          </button>
          <button className="lang-picker-btn" onClick={() => onChoose("es")}>
            <span className="flag">ES</span>
            <span className="label">Español</span>
          </button>
        </div>
      </div>
    </div>
  );
}

function I18nProvider({ children }) {
  const initial = typeof window !== "undefined" ? readStoredLang() : null;
  const [lang, setLangState] = React.useState(initial || "en");
  const [needsChoice, setNeedsChoice] = React.useState(initial === null);
  const T = TRANSLATIONS[lang] || TRANSLATIONS.en;

  const setLang = React.useCallback((l) => {
    setLangState(l);
    try { window.localStorage.setItem(LANG_STORAGE_KEY, l); } catch (_) {}
  }, []);

  const choose = (l) => {
    setLang(l);
    setNeedsChoice(false);
  };

  // Reflect on <html lang> for accessibility / browser hinting.
  React.useEffect(() => { document.documentElement.lang = lang; }, [lang]);

  // Lock background scroll while the language picker is showing.
  React.useEffect(() => {
    if (needsChoice) {
      const prev = document.body.style.overflow;
      document.body.style.overflow = "hidden";
      return () => { document.body.style.overflow = prev; };
    }
  }, [needsChoice]);

  return (
    <I18nContext.Provider value={{ lang, setLang, T }}>
      {children}
      {needsChoice && <LangPicker onChoose={choose} />}
    </I18nContext.Provider>
  );
}

function useI18n() {
  const ctx = React.useContext(I18nContext);
  if (!ctx) throw new Error("useI18n must be used inside I18nProvider");
  return ctx;
}

Object.assign(window, { I18nProvider, useI18n, LangPicker, TRANSLATIONS });
