/* global React, ReactDOM */
const { useState, useEffect, useRef, useCallback } = React;

/* ===================== Custom cursor ===================== */
function CustomCursor() {
  const dotRef  = useRef(null);
  const ringRef = useRef(null);
  const target  = useRef({ x: -100, y: -100 });
  const ring    = useRef({ x: -100, y: -100 });
  const isDown  = useRef(false);

  useEffect(() => {
    // Only render on devices with a fine pointer
    const mq = window.matchMedia('(hover: hover) and (pointer: fine)');
    if (!mq.matches) return;

    let raf;
    function loop() {
      const t = target.current;
      const r = ring.current;
      r.x += (t.x - r.x) * 0.18;
      r.y += (t.y - r.y) * 0.18;
      if (dotRef.current)  dotRef.current.style.transform  = `translate3d(${t.x}px, ${t.y}px, 0) translate(-50%, -50%)`;
      if (ringRef.current) ringRef.current.style.transform = `translate3d(${r.x}px, ${r.y}px, 0) translate(-50%, -50%) scale(${isDown.current ? 0.85 : 1})`;
      raf = requestAnimationFrame(loop);
    }

    function onMove(e) {
      target.current = { x: e.clientX, y: e.clientY };
      // dark backgrounds: figure out element under cursor
      const el = document.elementFromPoint(e.clientX, e.clientY);
      const onDark = !!(el && el.closest && el.closest('.on-dark, [data-dark]'));
      ringRef.current && ringRef.current.classList.toggle('is-dark', onDark);
      dotRef.current  && dotRef.current .classList.toggle('is-dark', onDark);
    }
    function onOver(e) {
      const interactive = e.target.closest && e.target.closest('a, button, [role="button"], input, select, textarea, label, summary');
      ringRef.current && ringRef.current.classList.toggle('is-hover', !!interactive);
    }
    function onOut(e) {
      if (!e.relatedTarget) {
        ringRef.current && ringRef.current.classList.remove('is-hover');
      }
    }
    function onDown(){ isDown.current = true; }
    function onUp()  { isDown.current = false; }

    window.addEventListener('mousemove', onMove, { passive: true });
    document.addEventListener('mouseover', onOver, { passive: true });
    document.addEventListener('mouseout',  onOut,  { passive: true });
    window.addEventListener('mousedown', onDown);
    window.addEventListener('mouseup',   onUp);
    raf = requestAnimationFrame(loop);

    return () => {
      cancelAnimationFrame(raf);
      window.removeEventListener('mousemove', onMove);
      document.removeEventListener('mouseover', onOver);
      document.removeEventListener('mouseout',  onOut);
      window.removeEventListener('mousedown', onDown);
      window.removeEventListener('mouseup',   onUp);
    };
  }, []);

  return (
    <>
      <div ref={ringRef} className="cursor-ring" aria-hidden="true"></div>
      <div ref={dotRef}  className="cursor-dot"  aria-hidden="true"></div>
    </>
  );
}

/* ===================== Media slots (image / video) ===================== */
function ImgSlot({ src, alt, label, badge, className = "", aspect = "aspect-[3/4]" }) {
  return (
    <figure className={"media-card " + aspect + " " + className}>
      <img src={src} alt={alt} loading="lazy"
           onError={(e) => { e.currentTarget.style.display = "none"; }} />
      {(label || badge) && (
        <figcaption className="absolute inset-x-4 bottom-4 flex items-end justify-between gap-3 z-10">
          {label && <span className="placeholder-tag text-white/95">{label}</span>}
          {badge && <span className="placeholder-tag text-white/95 bg-white/15 backdrop-blur px-2 py-1 rounded-full border border-white/30">{badge}</span>}
        </figcaption>
      )}
    </figure>
  );
}

function VideoSlot({ label, srcs = [], poster, aspect = "aspect-[3/4]", className = "" }) {
  return (
    <figure className={"media-card is-dark " + aspect + " " + className}>
      {/* Poster image as fallback while there is no real video */}
      {poster && (
        <img src={poster} alt="" aria-hidden="true" loading="lazy"
             onError={(e) => { e.currentTarget.style.display = "none"; }} />
      )}
      <video autoPlay loop muted playsInline poster={poster}
             className="!opacity-100" aria-label={label}>
        {srcs.map((s, i) => <source key={i} src={s.src} type={s.type} />)}
      </video>
      <div aria-hidden="true" className="absolute inset-0 pointer-events-none bg-gradient-to-t from-black/55 via-black/0 to-black/10" />
      <div aria-hidden="true" className="absolute inset-0 flex items-center justify-center">
        <span className="inline-flex items-center justify-center w-14 h-14 rounded-full bg-white/15 backdrop-blur border border-white/30 text-white">
          <svg width="14" height="16" viewBox="0 0 14 16" fill="currentColor" aria-hidden="true"><path d="M0 0v16l14-8z"/></svg>
        </span>
      </div>
      <figcaption className="absolute inset-x-4 bottom-4 flex items-end justify-between gap-3 z-10">
        <span className="placeholder-tag text-white/95">{label}</span>
        <span className="placeholder-tag text-white/95 bg-white/10 backdrop-blur px-2 py-1 rounded-full border border-white/30">Reel</span>
      </figcaption>
    </figure>
  );
}

/* ===================== Gallery (Resultados Reales) ===================== */
function Gallery({ onNavigate, dark = false }) {
  const tiles = (window.siteMedia && window.siteMedia.gallery) || [];

  const bg = dark ? "bg-charcoal text-ivory on-dark" : "bg-ivory";
  const muteText = dark ? "text-ivory/60" : "text-mute";
  const heading  = dark ? "text-ivory" : "text-ink";

  return (
    <section aria-labelledby="galeria-title" className={bg}>
      <div className="mx-auto max-w-[1400px] px-6 md:px-10 lg:px-14 py-24 md:py-32">
        <div className="grid grid-cols-12 gap-6 md:gap-10 items-end stagger">
          <div className="col-span-12 md:col-span-8">
            <p className={"text-[11px] tracking-widest-2 uppercase mb-8 flex items-center gap-4 " + muteText}>
              <span aria-hidden="true" className={"inline-block w-10 h-px " + (dark ? "bg-ivory/40" : "bg-mute")}></span>
              Resultados reales
            </p>
            <h2 id="galeria-title"
                className={"font-serif-display text-[40px] sm:text-[52px] md:text-[64px] lg:text-[72px] leading-[1.04] tracking-[-0.015em] " + heading}>
              Tu mejor versión,
              <br className="hidden sm:block" />
              <em className="italic font-light">en imagen y movimiento</em>.
            </h2>
          </div>
          <div className="col-span-12 md:col-span-4 md:col-start-9">
            <p className={"text-[15px] md:text-[16px] leading-[1.75] max-w-[42ch] " + (dark ? "text-ivory/80" : "text-charcoal")}>
              Una selección del trabajo del atelier — fotografía editorial y reels capturados en cabina. Lo que ves es real, sin filtros.
            </p>
            <a href="https://instagram.com/vibelami" target="_blank" rel="noopener noreferrer"
               className={"mt-6 inline-flex items-center gap-2 text-[11px] tracking-widest-2 uppercase nav-link " + heading}>
              Ver más en Instagram
              <svg width="14" height="10" viewBox="0 0 14 10" fill="none" aria-hidden="true">
                <path d="M1 5h12M9 1l4 4-4 4" stroke="currentColor" strokeWidth="1.2" strokeLinecap="square"/>
              </svg>
            </a>
          </div>
        </div>

        <div className="mt-14 md:mt-20 grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4 md:gap-5 stagger">
          {tiles.map((t, i) => (
            t.kind === "video"
              ? <VideoSlot key={i} label={t.label} poster={t.poster} srcs={t.videoSources || []} aspect="aspect-[9/16] md:aspect-[3/4]" />
              : <ImgSlot   key={i} label={t.label} src={t.src} alt={t.alt} />
          ))}
        </div>

        <div className={"mt-12 flex flex-col sm:flex-row items-start sm:items-center justify-between gap-6 border-t pt-8 " + (dark ? "border-ivory/15" : "border-line/80")}>
          <p className={"text-[11px] tracking-widest-2 uppercase " + muteText}>
            Atelier Vibelami · Castellón / Valencia
          </p>
          <button onClick={() => onNavigate("contacto")}
                  className={"inline-flex items-center gap-3 px-7 py-[16px] text-[11px] tracking-widest-2 uppercase transition-colors " +
                    (dark ? "bg-ivory text-ink hover:bg-cream" : "bg-ink text-ivory hover:bg-charcoal")}>
            Reservar valoración
            <svg width="14" height="10" viewBox="0 0 14 10" fill="none" aria-hidden="true">
              <path d="M1 5h12M9 1l4 4-4 4" stroke="currentColor" strokeWidth="1.2" strokeLinecap="square"/>
            </svg>
          </button>
        </div>
      </div>
    </section>
  );
}

/* ===================== Brand mark ===================== */
/* Returns a real URL for a page id when running in multipage mode
   (window.VIBELAMI_LINKS is defined by each page's <head>); otherwise null. */
function pageHref(id) {
  return (typeof window !== "undefined" && window.VIBELAMI_LINKS) ? window.VIBELAMI_LINKS[id] : null;
}

function Logo({ className = "", onClick }) {
  const inner = (
    <span className="font-serif-display text-[24px] md:text-[26px] leading-none tracking-[0.04em]">
      VIBELAMI<span className="text-nude">.</span>
    </span>
  );
  const href = pageHref("inicio");
  if (href) {
    return (
      <a href={href} aria-label="Vibelami — Inicio"
         className={"flex items-baseline gap-1 group " + className}>
        {inner}
      </a>
    );
  }
  return (
    <button onClick={onClick} aria-label="Vibelami — Inicio"
            className={"flex items-baseline gap-1 group bg-transparent " + className}>
      {inner}
    </button>
  );
}

/* ===================== Top utility strip ===================== */
function TopStrip() {
  return (
    <div className="bg-ink text-ivory text-[11px] tracking-[0.22em] uppercase on-dark" role="region" aria-label="Avisos del estudio">
      <div className="mx-auto max-w-[1400px] px-6 md:px-10 lg:px-14 h-9 flex items-center justify-between">
        <span className="hidden sm:inline opacity-80">Castellón · Valencia</span>
        <span className="opacity-90">Agenda 2026 abierta — Citas y formaciones disponibles</span>
        <span className="hidden sm:inline opacity-80">Atelier privado · Por cita previa</span>
      </div>
    </div>
  );
}

/* ===================== Navigation ===================== */
function Nav({ currentPage, onNavigate }) {
  const [open, setOpen] = useState(false);
  const items = [
    { id: "inicio",    label: "Inicio"    },
    { id: "servicios", label: "Servicios" },
    { id: "academia",  label: "Academia"  },
    { id: "promocion", label: "Promoción" },
    { id: "contacto",  label: "Contacto"  },
  ];

  function go(id) {
    setOpen(false);
    onNavigate(id);
  }

  return (
    <header className="relative z-30 border-b border-line/70 bg-ivory">
      <div className="mx-auto max-w-[1400px] px-6 md:px-10 lg:px-14">
        <div className="flex items-center justify-between h-20 md:h-24">
          <Logo onClick={() => go("inicio")} />

          <nav aria-label="Principal" className="hidden md:flex items-center gap-10">
            {items.map((it) => {
              const href = pageHref(it.id);
              const cls = "nav-link bg-transparent text-[13px] tracking-[0.18em] uppercase text-charcoal hover:text-ink";
              return href ? (
                <a key={it.id} href={href}
                   aria-current={currentPage === it.id ? "page" : undefined}
                   className={cls}>{it.label}</a>
              ) : (
                <button key={it.id} onClick={() => go(it.id)}
                        aria-current={currentPage === it.id ? "page" : undefined}
                        className={cls}>{it.label}</button>
              );
            })}
          </nav>

          <div className="hidden md:flex items-center gap-6">
            <span className="text-[12px] tracking-[0.18em] uppercase text-charcoal/80">ES / EN</span>
            {pageHref("contacto") ? (
              <a href={pageHref("contacto")}
                 className="btn-primary inline-flex items-center gap-2 bg-ink text-ivory text-[12px] tracking-[0.18em] uppercase px-5 py-3">
                Reservar
                <svg width="14" height="10" viewBox="0 0 14 10" fill="none" aria-hidden="true">
                  <path d="M1 5h12M9 1l4 4-4 4" stroke="currentColor" strokeWidth="1.2" strokeLinecap="square"/>
                </svg>
              </a>
            ) : (
              <button onClick={() => go("contacto")}
                      className="btn-primary inline-flex items-center gap-2 bg-ink text-ivory text-[12px] tracking-[0.18em] uppercase px-5 py-3">
                Reservar
                <svg width="14" height="10" viewBox="0 0 14 10" fill="none" aria-hidden="true">
                  <path d="M1 5h12M9 1l4 4-4 4" stroke="currentColor" strokeWidth="1.2" strokeLinecap="square"/>
                </svg>
              </button>
            )}
          </div>

          <button type="button" onClick={() => setOpen(v => !v)}
                  aria-expanded={open} aria-controls="m-menu"
                  aria-label={open ? "Cerrar menú" : "Abrir menú"}
                  className="md:hidden inline-flex items-center justify-center w-11 h-11 border border-ink/70">
            <span className="sr-only">Menú</span>
            <div className="flex flex-col gap-[5px]">
              <span className={"block h-px w-5 bg-ink transition-transform " + (open ? "translate-y-[3px] rotate-45" : "")}></span>
              <span className={"block h-px w-5 bg-ink transition-opacity " + (open ? "opacity-0" : "")}></span>
              <span className={"block h-px w-5 bg-ink transition-transform " + (open ? "-translate-y-[3px] -rotate-45" : "")}></span>
            </div>
          </button>
        </div>

        {open && (
          <div id="m-menu" className="md:hidden pb-6 border-t border-line/70">
            <nav aria-label="Principal móvil" className="flex flex-col py-4">
              {items.map(it => {
                const href = pageHref(it.id);
                const cls = "text-left py-3 text-[14px] tracking-[0.18em] uppercase text-charcoal hover:text-ink";
                return href ? (
                  <a key={it.id} href={href}
                     aria-current={currentPage === it.id ? "page" : undefined}
                     className={cls}>{it.label}</a>
                ) : (
                  <button key={it.id} onClick={() => go(it.id)}
                          aria-current={currentPage === it.id ? "page" : undefined}
                          className={cls}>{it.label}</button>
                );
              })}
              {pageHref("contacto") ? (
                <a href={pageHref("contacto")}
                   className="btn-primary mt-4 inline-flex items-center justify-center bg-ink text-ivory text-[12px] tracking-[0.18em] uppercase px-5 py-3">
                  Reservar valoración
                </a>
              ) : (
                <button onClick={() => go("contacto")}
                        className="btn-primary mt-4 inline-flex items-center justify-center bg-ink text-ivory text-[12px] tracking-[0.18em] uppercase px-5 py-3">
                  Reservar valoración
                </button>
              )}
            </nav>
          </div>
        )}
      </div>
    </header>
  );
}

/* ===================== Glyphs for "para ti" ===================== */
function Glyph({ kind }) {
  const common = { width: 56, height: 56, viewBox: "0 0 56 56", fill: "none", "aria-hidden": true, stroke: "currentColor" };
  if (kind === "lift") {
    return (
      <svg {...common}>
        <circle cx="28" cy="28" r="22" strokeWidth="1" />
        <circle cx="28" cy="28" r="3" fill="currentColor" stroke="none" />
        <line x1="28" y1="6"  x2="28" y2="14" strokeWidth="1" />
        <line x1="28" y1="42" x2="28" y2="50" strokeWidth="1" />
        <line x1="6"  y1="28" x2="14" y2="28" strokeWidth="1" />
        <line x1="42" y1="28" x2="50" y2="28" strokeWidth="1" />
      </svg>
    );
  }
  if (kind === "diamond") {
    return (
      <svg {...common}>
        <rect x="14" y="14" width="28" height="28" transform="rotate(45 28 28)" strokeWidth="1" />
        <rect x="22" y="22" width="12" height="12" transform="rotate(45 28 28)" strokeWidth="1" />
      </svg>
    );
  }
  return (
    <svg {...common}>
      <circle cx="28" cy="28" r="22" strokeWidth="1" />
      <circle cx="28" cy="28" r="14" strokeWidth="1" />
      <circle cx="28" cy="28" r="6"  strokeWidth="1" />
    </svg>
  );
}

/* ===================== Contact ===================== */
function Contact({ defaultService }) {
  const [form, setForm] = useState({ nombre: "", telefono: "", servicio: defaultService || "", mensaje: "", rgpd: false });
  const [sent, setSent] = useState(false);
  const [touched, setTouched] = useState(false);

  const handle = (k) => (e) => setForm({ ...form, [k]: e.target.type === "checkbox" ? e.target.checked : e.target.value });
  const required = form.nombre.trim() && form.telefono.trim() && form.servicio && form.rgpd;

  function submit(e) {
    e.preventDefault();
    setTouched(true);
    if (!required) return;
    setSent(true);
  }

  const inputBase = "w-full bg-transparent border-0 border-b border-line/80 focus:border-ink py-3 text-[15px] text-ink placeholder:text-mute/70 transition-colors";
  const labelBase = "block text-[10px] tracking-widest-2 uppercase text-mute mb-2";

  return (
    <section id="contacto" aria-labelledby="contacto-title" className="bg-ivory">
      <div className="mx-auto max-w-[1400px] px-6 md:px-10 lg:px-14 py-24 md:py-36">
        <div className="grid grid-cols-12 gap-6 md:gap-10 lg:gap-16 items-start">

          <div className="col-span-12 lg:col-span-5">
            <p className="text-[11px] tracking-widest-2 uppercase text-mute mb-8 flex items-center gap-4 fade-up">
              <span aria-hidden="true" className="inline-block w-10 h-px bg-mute"></span>
              Contacto
            </p>
            <h2 id="contacto-title"
                className="font-serif-display text-ink text-[40px] sm:text-[52px] md:text-[60px] lg:text-[64px] leading-[1.04] tracking-[-0.015em] fade-up delay-1">
              Escríbenos.
              <br />
              <em className="italic font-light">Te respondemos hoy</em>.
            </h2>
            <p className="mt-8 text-[15px] md:text-[16px] leading-[1.75] text-charcoal max-w-[42ch] fade-up delay-2">
              Cuéntanos qué buscas. Nuestro equipo se pondrá en contacto contigo en menos de 24h para agendar tu valoración personalizada.
            </p>

            <dl className="mt-12 grid grid-cols-1 sm:grid-cols-2 gap-8 border-t border-line/80 pt-8 fade-up delay-3">
              <div>
                <dt className="text-[10px] tracking-widest-2 uppercase text-mute mb-3">Castellón</dt>
                <dd className="font-serif-display text-[22px] leading-[1.2] text-ink">Atelier Castellón</dd>
                <dd className="mt-1 text-[14px] leading-[1.6] text-charcoal">Av. del Mar, 00<br />12003 · Castellón de la Plana</dd>
                <dd className="mt-3 text-[12px] tracking-widest-2 uppercase">
                  <a href="tel:+34642606395" className="text-ink nav-link">+34 642 606 395</a>
                </dd>
              </div>
              <div>
                <dt className="text-[10px] tracking-widest-2 uppercase text-mute mb-3">Valencia</dt>
                <dd className="font-serif-display text-[22px] leading-[1.2] text-ink">Atelier Valencia</dd>
                <dd className="mt-1 text-[14px] leading-[1.6] text-charcoal">C/ Colón, 00<br />46004 · Valencia</dd>
                <dd className="mt-3 text-[12px] tracking-widest-2 uppercase">
                  <a href="tel:+34642606395" className="text-ink nav-link">+34 642 606 395</a>
                </dd>
              </div>
            </dl>

            <dl className="mt-8 grid grid-cols-1 sm:grid-cols-2 gap-8 fade-up delay-4">
              <div>
                <dt className="text-[10px] tracking-widest-2 uppercase text-mute mb-2">Horario</dt>
                <dd className="text-[14px] leading-[1.6] text-charcoal">Lun – Sáb · 10:00 – 20:00<br />Por cita previa</dd>
              </div>
              <div>
                <dt className="text-[10px] tracking-widest-2 uppercase text-mute mb-2">Email</dt>
                <dd className="text-[14px] leading-[1.6]">
                  <a href="mailto:hola@vibelami.com" className="text-ink nav-link">hola@vibelami.com</a>
                </dd>
              </div>
            </dl>
          </div>

          <div className="col-span-12 lg:col-span-7 lg:pl-6 fade-up delay-2">
            {sent ? (
              <div role="status" aria-live="polite" className="border border-line/80 p-10 md:p-14 bg-cream/50">
                <p className="text-[10px] tracking-widest-2 uppercase text-mute mb-4">Mensaje enviado</p>
                <h3 className="font-serif-display text-ink text-[32px] md:text-[40px] leading-[1.1]">
                  Gracias, {form.nombre.split(" ")[0] || "hablamos pronto"}.
                </h3>
                <p className="mt-5 text-[15px] leading-[1.7] text-charcoal max-w-[48ch]">
                  Hemos recibido tu mensaje. Te escribiremos por WhatsApp o email en las próximas horas para coordinar tu cita.
                </p>
                <button type="button"
                        onClick={() => { setSent(false); setTouched(false); setForm({ nombre: "", telefono: "", servicio: "", mensaje: "", rgpd: false }); }}
                        className="mt-8 text-[11px] tracking-widest-2 uppercase text-ink nav-link bg-transparent">
                  Enviar otro mensaje
                </button>
              </div>
            ) : (
              <form noValidate onSubmit={submit} className="grid grid-cols-1 sm:grid-cols-2 gap-x-10 gap-y-8">
                <div className="sm:col-span-1">
                  <label htmlFor="f-nombre" className={labelBase}>Nombre *</label>
                  <input id="f-nombre" name="nombre" type="text" autoComplete="name" required
                         value={form.nombre} onChange={handle("nombre")}
                         aria-invalid={touched && !form.nombre.trim()}
                         placeholder="Tu nombre completo"
                         className={inputBase} />
                </div>
                <div className="sm:col-span-1">
                  <label htmlFor="f-tel" className={labelBase}>Teléfono *</label>
                  <input id="f-tel" name="telefono" type="tel" autoComplete="tel" required
                         value={form.telefono} onChange={handle("telefono")}
                         aria-invalid={touched && !form.telefono.trim()}
                         placeholder="+34 000 000 000"
                         className={inputBase} />
                </div>

                <div className="sm:col-span-2">
                  <label htmlFor="f-servicio" className={labelBase}>¿Qué servicio te interesa? *</label>
                  <select id="f-servicio" name="servicio" required
                          value={form.servicio} onChange={handle("servicio")}
                          aria-invalid={touched && !form.servicio}
                          className={inputBase + " appearance-none pr-8"}
                          style={{ backgroundImage: "url(\"data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='12' height='8' viewBox='0 0 12 8' fill='none'><path d='M1 1l5 5 5-5' stroke='%23161616' stroke-width='1.2'/></svg>\")",
                                   backgroundRepeat: "no-repeat",
                                   backgroundPosition: "right 4px center" }}>
                    <option value="" disabled>Selecciona una opción</option>
                    <option value="cejas">Cejas — VIBROWS &amp; Powder Brows</option>
                    <option value="labios">Micropigmentación de labios</option>
                    <option value="capilar">Densificación capilar</option>
                    <option value="correccion">Corrección / Neutralización</option>
                    <option value="academia">Formación — Masterclass</option>
                    <option value="otro">Otro / Tengo dudas</option>
                  </select>
                </div>

                <div className="sm:col-span-2">
                  <label htmlFor="f-mensaje" className={labelBase}>Mensaje</label>
                  <textarea id="f-mensaje" name="mensaje" rows="4"
                            value={form.mensaje} onChange={handle("mensaje")}
                            placeholder="Cuéntanos qué te gustaría conseguir o cualquier duda previa."
                            className={inputBase + " resize-none py-3"} />
                </div>

                <div className="sm:col-span-2 flex items-start gap-3">
                  <input id="f-rgpd" name="rgpd" type="checkbox" required
                         checked={form.rgpd} onChange={handle("rgpd")}
                         aria-invalid={touched && !form.rgpd}
                         className="mt-[5px] w-4 h-4 accent-ink shrink-0" />
                  <label htmlFor="f-rgpd" className="text-[12px] leading-[1.6] text-charcoal">
                    He leído y acepto la{" "}
                    <a href="#privacidad" className="text-ink underline underline-offset-2 hover:no-underline">Política de Privacidad</a>{" "}
                    y autorizo el tratamiento de mis datos para gestionar mi solicitud. *
                  </label>
                </div>

                {touched && !required && (
                  <p role="alert" className="sm:col-span-2 text-[12px] text-ink bg-cream border border-line/80 px-4 py-3">
                    Revisa los campos marcados con * antes de enviar.
                  </p>
                )}

                <div className="sm:col-span-2 flex flex-col sm:flex-row items-stretch sm:items-center justify-between gap-4 pt-4">
                  <p className="text-[11px] tracking-widest-2 uppercase text-mute">
                    Respuesta en menos de 24h
                  </p>
                  <button type="submit"
                          className="btn-primary inline-flex items-center justify-center gap-3 bg-ink text-ivory px-8 py-[18px] text-[12px] tracking-[0.22em] uppercase">
                    Enviar mensaje
                    <svg width="16" height="10" viewBox="0 0 16 10" fill="none" aria-hidden="true">
                      <path d="M1 5h13M10 1l4 4-4 4" stroke="currentColor" strokeWidth="1.2" strokeLinecap="square"/>
                    </svg>
                  </button>
                </div>
              </form>
            )}
          </div>
        </div>
      </div>
    </section>
  );
}

/* ===================== Footer ===================== */
function Footer({ onNavigate }) {
  const cols = [
    { title: "Navegación", links: [
      { label: "Inicio",    page: "inicio"    },
      { label: "Servicios", page: "servicios" },
      { label: "Academia",  page: "academia"  },
      { label: "Contacto",  page: "contacto"  },
    ]},
    { title: "Servicios", links: [
      { label: "VIBROWS & Powder Brows",  page: "servicios" },
      { label: "Micropigmentación Labios", page: "servicios" },
      { label: "Densificación Capilar",   page: "servicios" },
      { label: "Correcciones & Remoción", page: "servicios" },
    ]},
    { title: "Legal", links: [
      { label: "Aviso Legal",            href: "#aviso-legal" },
      { label: "Política de Privacidad", href: "#privacidad" },
      { label: "Política de Cookies",    href: "#cookies" },
      { label: "RGPD / LOPDGDD",         href: "#rgpd" },
    ]},
  ];

  function clickLink(l) {
    if (l.page) onNavigate(l.page);
  }

  return (
    <footer aria-labelledby="footer-title" className="bg-ink text-ivory on-dark">
      <h2 id="footer-title" className="sr-only">Pie de página</h2>
      <div className="mx-auto max-w-[1400px] px-6 md:px-10 lg:px-14 pt-20 md:pt-28 pb-10">

        <div className="grid grid-cols-12 gap-6 md:gap-10 pb-16 md:pb-20 border-b border-ivory/15">
          <div className="col-span-12 lg:col-span-8">
            <p className="font-serif-display text-ivory text-[40px] sm:text-[56px] md:text-[72px] lg:text-[88px] leading-[1.02] tracking-[-0.015em]">
              <em className="italic font-light">Vibelami<span className="text-nude">.</span></em>
              <br />
              Micropigmentación de alta costura.
            </p>
          </div>
          <div className="col-span-12 lg:col-span-4 lg:pt-4">
            <p className="text-[14px] leading-[1.75] text-ivory/70 max-w-[42ch]">
              Estudio y academia de micropigmentación dirigido por Bela &amp; Vivian. Castellón &amp; Valencia.
            </p>
            {pageHref("contacto") ? (
              <a href={pageHref("contacto")}
                 className="mt-8 inline-flex items-center gap-3 border border-ivory/80 text-ivory bg-transparent px-7 py-[16px] text-[11px] tracking-widest-2 uppercase transition-colors hover:bg-ivory hover:text-ink">
                Reserva tu valoración
                <svg width="14" height="10" viewBox="0 0 14 10" fill="none" aria-hidden="true">
                  <path d="M1 5h12M9 1l4 4-4 4" stroke="currentColor" strokeWidth="1.2" strokeLinecap="square"/>
                </svg>
              </a>
            ) : (
              <button onClick={() => clickLink({ page: "contacto" })}
                      className="mt-8 inline-flex items-center gap-3 border border-ivory/80 text-ivory bg-transparent px-7 py-[16px] text-[11px] tracking-widest-2 uppercase transition-colors hover:bg-ivory hover:text-ink">
                Reserva tu valoración
                <svg width="14" height="10" viewBox="0 0 14 10" fill="none" aria-hidden="true">
                  <path d="M1 5h12M9 1l4 4-4 4" stroke="currentColor" strokeWidth="1.2" strokeLinecap="square"/>
                </svg>
              </button>
            )}
          </div>
        </div>

        <div className="grid grid-cols-12 gap-y-12 gap-x-6 md:gap-x-10 pt-16 md:pt-20">
          <div className="col-span-12 md:col-span-6 lg:col-span-3">
            <Logo className="text-ivory" onClick={() => onNavigate("inicio")} />

            <div className="mt-10 space-y-6">
              <div>
                <p className="text-[10px] tracking-widest-2 uppercase text-ivory/55 mb-2">Castellón</p>
                <address className="not-italic text-[14px] leading-[1.6] text-ivory/85">
                  Av. del Mar, 00<br />12003 · Castellón de la Plana
                </address>
              </div>
              <div>
                <p className="text-[10px] tracking-widest-2 uppercase text-ivory/55 mb-2">Valencia</p>
                <address className="not-italic text-[14px] leading-[1.6] text-ivory/85">
                  C/ Colón, 00<br />46004 · Valencia
                </address>
              </div>
            </div>
          </div>

          {cols.map((c) => (
            <nav key={c.title} aria-label={c.title} className="col-span-6 sm:col-span-4 md:col-span-3 lg:col-span-2">
              <p className="text-[10px] tracking-widest-2 uppercase text-ivory/55 mb-5">{c.title}</p>
              <ul className="space-y-3">
                {c.links.map((l) => {
                  const href = l.page ? pageHref(l.page) : null;
                  return (
                    <li key={l.label}>
                      {href ? (
                        <a href={href} className="text-[14px] text-ivory/90 hover:text-ivory nav-link">{l.label}</a>
                      ) : l.page ? (
                        <button onClick={() => clickLink(l)}
                                className="text-[14px] text-ivory/90 hover:text-ivory nav-link bg-transparent text-left">
                          {l.label}
                        </button>
                      ) : (
                        <a href={l.href} className="text-[14px] text-ivory/90 hover:text-ivory nav-link">{l.label}</a>
                      )}
                    </li>
                  );
                })}
              </ul>
            </nav>
          ))}

          <div className="col-span-12 md:col-span-12 lg:col-span-3">
            <p className="text-[10px] tracking-widest-2 uppercase text-ivory/55 mb-5">Síguenos</p>
            <ul className="space-y-3">
              <li>
                <a href="https://instagram.com/vibelami"
                   target="_blank" rel="noopener noreferrer"
                   className="inline-flex items-center gap-3 text-[14px] text-ivory/90 hover:text-ivory group">
                  <span aria-hidden="true" className="inline-flex items-center justify-center w-9 h-9 border border-ivory/40 group-hover:border-ivory transition-colors">
                    <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4" aria-hidden="true">
                      <rect x="3" y="3" width="18" height="18" rx="5"/>
                      <circle cx="12" cy="12" r="4"/>
                      <circle cx="17.5" cy="6.5" r="0.9" fill="currentColor" stroke="none"/>
                    </svg>
                  </span>
                  <span>
                    <span className="block">Instagram</span>
                    <span className="block text-[11px] tracking-widest-2 uppercase text-ivory/55">@vibelami</span>
                  </span>
                </a>
              </li>
              <li>
                <a href="mailto:hola@vibelami.com" className="text-[14px] text-ivory/90 hover:text-ivory nav-link">
                  hola@vibelami.com
                </a>
              </li>
            </ul>
          </div>
        </div>

        {/* Publicidad obligatoria de la subvención — Next Generation EU */}
        <div className="mt-16 md:mt-20 pt-10 border-t border-ivory/15">
          <div className="flex flex-col sm:flex-row items-center sm:items-start gap-6 sm:gap-8">
            <img src={(window.VIBELAMI_BASE || "") + "media/emblema-ue.png"}
                 alt="Emblema de la Unión Europea"
                 loading="lazy"
                 className="h-12 sm:h-14 w-auto shrink-0"
                 onError={(e) => { e.currentTarget.style.display = "none"; }} />
            <img src={(window.VIBELAMI_BASE || "") + "media/logo-ue.png"}
                 alt="Plan de Recuperación, Transformación y Resiliencia"
                 loading="lazy"
                 className="h-12 sm:h-14 w-auto shrink-0"
                 onError={(e) => { e.currentTarget.style.display = "none"; }} />
            <p className="text-[11px] leading-[1.6] tracking-[0.02em] text-ivory/70 max-w-[52ch] sm:pt-1 text-center sm:text-left">
              Financiado por la Unión Europea – NextGenerationEU
            </p>
          </div>
        </div>

        <div className="mt-10 pt-8 border-t border-ivory/15 flex flex-col md:flex-row items-start md:items-center justify-between gap-4">
          <p className="text-[11px] tracking-widest-2 uppercase text-ivory/55">
            © 2026 Vibelami · Todos los derechos reservados
          </p>
          <p className="text-[11px] tracking-widest-2 uppercase text-ivory/55">
            Diseñado en Valencia · Hecho con cuidado
          </p>
        </div>
      </div>
    </footer>
  );
}

/* ===================== Chat Widget (premium) ===================== */
function ChatWidget() {
  const [open, setOpen] = useState(false);
  const [input, setInput] = useState("");
  const [history, setHistory] = useState([]); // local messages user has typed
  const inputRef = useRef(null);
  const scrollRef = useRef(null);
  const WA = "https://wa.me/34642606395?text=";

  useEffect(() => {
    if (open) setTimeout(() => inputRef.current && inputRef.current.focus(), 220);
  }, [open]);

  useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [history, open]);

  // Esc to close
  useEffect(() => {
    function onKey(e) { if (e.key === "Escape" && open) setOpen(false); }
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open]);

  function send(text) {
    const t = (text || "").trim();
    if (!t) return;
    setHistory((h) => [...h, { who: "me", text: t }]);
    const url = WA + encodeURIComponent(t);
    // small delay so the user sees their message in the chat before the tab opens
    setTimeout(() => window.open(url, "_blank", "noopener,noreferrer"), 220);
  }

  function onSubmit(e) {
    e.preventDefault();
    send(input);
    setInput("");
  }

  const chips = [
    { label: "Info Cejas",  msg: "¡Hola Vibelami! Me gustaría más información sobre las cejas (VIBROWS / Powder Brows)." },
    { label: "Info Labios", msg: "¡Hola Vibelami! Me gustaría más información sobre la micropigmentación de labios." },
    { label: "Academia",    msg: "¡Hola Vibelami! Me interesa la Masterclass. ¿Podríais darme detalles?" },
  ];

  return (
    <>
      <div role="dialog" aria-label="Chat con Vibelami" aria-hidden={!open}
           className={"chat-panel " + (open ? "is-open" : "")}>
        {/* Header */}
        <div className="bg-ink text-ivory px-5 py-4 flex items-center justify-between on-dark">
          <div className="flex items-center gap-3 min-w-0">
            <span aria-hidden="true"
                  className="inline-flex items-center justify-center w-10 h-10 rounded-full border border-ivory/30 font-serif-display text-[16px] shrink-0">
              V
            </span>
            <div className="min-w-0">
              <p className="font-serif-display text-[18px] leading-none">Vibelami</p>
              <p className="mt-1.5 text-[11px] tracking-[0.04em] text-ivory/75 flex items-center gap-1.5 truncate">
                <span aria-hidden="true" className="inline-block w-1.5 h-1.5 rounded-full bg-emerald-400"></span>
                En línea · Bela o Vivian te responderán pronto
              </p>
            </div>
          </div>
          <button type="button" onClick={() => setOpen(false)} aria-label="Cerrar chat"
                  className="w-9 h-9 inline-flex items-center justify-center rounded-full bg-transparent text-ivory hover:bg-ivory/10 transition-colors shrink-0">
            <svg width="14" height="14" viewBox="0 0 14 14" fill="none" aria-hidden="true">
              <path d="M2 2l10 10M12 2L2 12" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round"/>
            </svg>
          </button>
        </div>

        {/* Body */}
        <div ref={scrollRef} className="flex-1 overflow-y-auto px-5 py-6 space-y-4 bg-cream/50">
          {/* Bot intro */}
          <div className="flex items-start gap-3">
            <span aria-hidden="true" className="inline-flex items-center justify-center w-8 h-8 rounded-full bg-ink text-ivory font-serif-display text-[13px] shrink-0">V</span>
            <div className="max-w-[78%]">
              <div className="bg-ivory border border-line/80 rounded-2xl rounded-tl-sm px-4 py-3">
                <p className="text-[14px] leading-[1.55] text-charcoal">
                  ¡Hola! 👋 ¿En qué podemos ayudarte hoy? ¿Buscas información sobre tratamientos o sobre la academia?
                </p>
              </div>
              <p className="text-[10px] tracking-widest-2 uppercase text-mute mt-2 pl-1">Equipo Vibelami</p>
            </div>
          </div>

          {/* Chips */}
          <div className="pl-11 flex flex-wrap gap-2">
            {chips.map((c) => (
              <button key={c.label} type="button" onClick={() => send(c.msg)}
                      className="bg-transparent border border-ink/80 text-ink text-[12px] tracking-[0.04em] px-3.5 py-2 rounded-full hover:bg-ink hover:text-ivory transition-colors">
                {c.label}
              </button>
            ))}
          </div>

          {/* User messages */}
          {history.map((m, i) => (
            <div key={i} className="flex justify-end">
              <div className="bg-ink text-ivory rounded-2xl rounded-tr-sm px-4 py-3 max-w-[80%]">
                <p className="text-[14px] leading-[1.55]">{m.text}</p>
                <p className="text-[10px] tracking-widest-2 uppercase text-ivory/55 mt-2">Enviado · abriendo WhatsApp</p>
              </div>
            </div>
          ))}
        </div>

        {/* Input */}
        <form onSubmit={onSubmit} className="bg-ivory p-3 flex items-center gap-2">
          <input ref={inputRef} type="text" value={input}
                 onChange={(e) => setInput(e.target.value)}
                 placeholder="Escribe tu mensaje…"
                 aria-label="Escribe tu mensaje"
                 className="flex-1 bg-transparent border-0 px-3 py-2.5 text-[14px] text-ink placeholder:text-mute/70" />
          <button type="submit" aria-label="Enviar mensaje" disabled={!input.trim()}
                  className="w-10 h-10 inline-flex items-center justify-center rounded-full bg-ink text-ivory disabled:opacity-25 transition-all hover:bg-charcoal hover:translate-x-[1px]">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
              <path d="M22 2L11 13"/>
              <path d="M22 2l-7 20-4-9-9-4 20-7z"/>
            </svg>
          </button>
        </form>
        <p className="bg-ivory text-[10px] tracking-widest-2 uppercase text-mute text-center pb-3">
          Tu mensaje se abrirá en WhatsApp
        </p>
      </div>

      {!open && (
        <span className="chat-tip" aria-hidden="true">¡Hablemos!</span>
      )}

      <button type="button" onClick={() => setOpen((v) => !v)}
              aria-label={open ? "Cerrar chat" : "Abrir chat con Vibelami"}
              aria-expanded={open}
              className={"chat-fab " + (open ? "is-open" : "")}>
        {open ? (
          <svg width="18" height="18" viewBox="0 0 18 18" fill="none" aria-hidden="true">
            <path d="M3 3l12 12M15 3L3 15" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/>
          </svg>
        ) : (
          <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinejoin="round" aria-hidden="true">
            <path d="M21 12c0 4.4-4 8-9 8-1.3 0-2.5-.2-3.6-.7L3 21l1.7-4.2C3.6 15.6 3 13.9 3 12c0-4.4 4-8 9-8s9 3.6 9 8z"/>
          </svg>
        )}
      </button>
    </>
  );
}

/* Keep WhatsappFab as a backward-compatible alias */
const WhatsappFab = ChatWidget;

/* Expose globals for the other babel scripts */
Object.assign(window, {
  CustomCursor, Logo, TopStrip, Nav, Glyph, Contact, Footer, WhatsappFab,
  ChatWidget, ImgSlot, VideoSlot, Gallery
});
