/* Billboard AR Experience — UI kit shared helpers
   Reveal-on-scroll hook + wrapper, section shell, icon set. */

const { useEffect, useRef, useState } = React;

/* Expose design-system components as globals for the section files. */
Object.assign(window, window.BillboardARExperienceDesignSystem_6c41d9);

/* Reveal-on-scroll wrapper — CAPTURE / PRINT / NO-JS SAFE.
   The element starts HIDDEN (opacity 0 + slide) only when we will actually
   animate it (JS present, IntersectionObserver available, motion allowed) and
   transitions to visible once it scrolls into view — so there is NO flash /
   flicker. If we won't animate (reduced motion or no IO), it renders visible
   from the first paint. Everything here is React, so "no JS" = no element. */
function Reveal({ children, as = "div", delay = 0, style, ...rest }) {
  const ref = useRef(null);
  const reduce = typeof window !== "undefined" && window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
  const noIO = typeof window === "undefined" || !("IntersectionObserver" in window);
  const animate = !reduce && !noIO;
  const [inview, setInview] = useState(!animate); // visible immediately if we won't animate
  useEffect(() => {
    if (!animate) return;
    const el = ref.current;
    if (!el) return;
    let done = false;
    const reveal = () => { if (!done) { done = true; setInview(true); } };
    const inView = () => {
      const r = el.getBoundingClientRect();
      const vh = window.innerHeight || document.documentElement.clientHeight;
      return r.top < vh && r.bottom > 0;
    };
    // Already in the viewport at mount → reveal now, no IntersectionObserver
    // round-trip (deterministic; also covers backgrounded-tab loads).
    if (inView()) { reveal(); return; }
    const io = new IntersectionObserver((entries) => {
      if (entries.some((e) => e.isIntersecting)) { reveal(); io.disconnect(); }
    }, { threshold: 0.12, rootMargin: "0px 0px -8% 0px" });
    io.observe(el);
    // Safety: if loaded while the tab was hidden (IO throttled), re-check once
    // the page becomes visible and the element happens to be in view.
    const onVis = () => { if (!document.hidden && inView()) { reveal(); io.disconnect(); } };
    document.addEventListener("visibilitychange", onVis);
    return () => { io.disconnect(); document.removeEventListener("visibilitychange", onVis); };
  }, []);
  const Tag = as;
  const { className, ...restNoClass } = rest;
  const revealStyle = animate
    ? {
        opacity: inview ? 1 : 0,
        transform: inview ? "none" : "translateY(28px)",
        transition: "opacity 760ms var(--ease-out) " + delay + "ms, transform 760ms var(--ease-out) " + delay + "ms",
        willChange: inview ? "auto" : "opacity, transform",
      }
    : {};
  return (
    <Tag
      ref={ref}
      className={className || undefined}
      style={{ ...revealStyle, ...style }}
      {...restNoClass}
    >
      {children}
    </Tag>
  );
}

/* Section shell: handles tone (dark / light), vertical rhythm, centered column. */
function Section({ children, tone = "dark", id, style, inner, ...rest }) {
  const bg = tone === "light"
    ? "var(--grad-light)"
    : tone === "navy"
    ? "var(--surface-navy)"
    : "var(--surface-base)";
  const color = tone === "light" ? "var(--ink)" : "var(--white)";
  return (
    <section
      id={id}
      style={{ background: bg, color, paddingTop: "var(--section-y)", paddingBottom: "var(--section-y)", ...style }}
      {...rest}
    >
      <div style={{ width: "min(100% - calc(var(--gutter) * 2), var(--maxw))", marginInline: "auto", ...inner }}>
        {children}
      </div>
    </section>
  );
}

/* Lucide-style inline icons (1.75px stroke, currentColor). */
const ic = (paths) => (
  <svg viewBox="0 0 24 24" width="100%" height="100%" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round">{paths}</svg>
);
const Icons = {
  arrow: ic(<><path d="M5 12h14" /><path d="M13 6l6 6-6 6" /></>),
  chevronDown: ic(<path d="M6 9l6 6 6-6" />),
  graduation: ic(<><path d="M22 10L12 5 2 10l10 5 10-5z" /><path d="M6 12v5c0 1 2.7 2.5 6 2.5s6-1.5 6-2.5v-5" /></>),
  network: ic(<><circle cx="12" cy="5" r="2.5" /><circle cx="5" cy="19" r="2.5" /><circle cx="19" cy="19" r="2.5" /><path d="M10.5 7L6.5 16.5M13.5 7l4 9.5M7 19h10" /></>),
  camera: ic(<><path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z" /><circle cx="12" cy="13" r="4" /></>),
  star: ic(<path d="M12 2l3 7h7l-5.5 4.5L18.5 21 12 16.5 5.5 21l2-7.5L2 9h7z" />),
  mic: ic(<><rect x="9" y="2" width="6" height="12" rx="3" /><path d="M5 10a7 7 0 0 0 14 0M12 17v4M8 21h8" /></>),
  globe: ic(<><circle cx="12" cy="12" r="9" /><path d="M3 12h18M12 3c2.5 2.5 3.8 5.8 3.8 9s-1.3 6.5-3.8 9c-2.5-2.5-3.8-5.8-3.8-9S9.5 5.5 12 3z" /></>),
  badge: ic(<><circle cx="12" cy="9" r="6" /><path d="M9 14.5L8 22l4-2.2L16 22l-1-7.5" /></>),
  calendar: ic(<><rect x="3" y="4" width="18" height="18" rx="2" /><path d="M3 9h18M8 2v4M16 2v4" /></>),
  sparkles: ic(<><path d="M12 3l1.8 4.5L18 9l-4.2 1.5L12 15l-1.8-4.5L6 9l4.2-1.5z" /><path d="M18 14l.9 2.2L21 17l-2.1.8L18 20l-.9-2.2L15 17l2.1-.8z" /></>),
  briefcase: ic(<><rect x="2" y="7" width="20" height="14" rx="2" /><path d="M8 7V5a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2M2 13h20" /></>),
  users: ic(<><circle cx="9" cy="8" r="3.5" /><path d="M2.5 20a6.5 6.5 0 0 1 13 0M17 5.5a3.5 3.5 0 0 1 0 6.8M22 20a6.5 6.5 0 0 0-5-6.3" /></>),
  film: ic(<><rect x="2.5" y="4" width="19" height="16" rx="2" /><path d="M7 4v16M17 4v16M2.5 9h4.5M2.5 15h4.5M17 9h4.5M17 15h4.5" /></>),
  map: ic(<><path d="M12 21s7-6.3 7-11a7 7 0 1 0-14 0c0 4.7 7 11 7 11z" /><circle cx="12" cy="10" r="2.5" /></>),
  download: ic(<><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" /><path d="M7 10l5 5 5-5" /><path d="M12 15V3" /></>),
};

/* ---- Datos de contacto / redes ------------------------------ */
const BB = {
  WHATSAPP: "5491171647891",
  EMAIL: "experience@billboard.ar",
  BRAND_EMAIL: "brandpartnerships@billboard.ar",
  SITE: "https://www.billboard.ar",
};

/* ---- Firebase (compat) — persiste el lead para el bot de WhatsApp + dashboard.
   Config del Web App — proyecto billboard-experience. ---------- */
firebase.initializeApp({
  apiKey: "AIzaSyCKQ7zCP666SC3cgvvhzYkwhrmk3eRQl1U",
  authDomain: "billboard-experience.firebaseapp.com",
  projectId: "billboard-experience",
  storageBucket: "billboard-experience.firebasestorage.app",
  messagingSenderId: "330029000470",
  appId: "1:330029000470:web:54c542b958219567591237",
  measurementId: "G-8MEGQCSD8R", // Firebase Analytics (GA4) — propiedad "billboard-experience" en la cuenta Billboard AR
});
firebase.appCheck().activate("6Ld-hlMtAAAAAIxaZ976a7UdICjU_MIxqLhZVU9v", true);
const bbDb = firebase.firestore();

/* ---- Analytics (Firebase Analytics = GA4) --------------------
   Consent Mode default + sin banner de cookies. bbTrack() es no-op si Analytics
   no está disponible: measurementId placeholder, bloqueador, o init falla.
   Todo lo trackeado se espeja en window.__bbEvents para debug/verificación. */
let bbAnalytics = null;
(function bbInitAnalytics() {
  try {
    const mid = (firebase.app().options.measurementId || "");
    if (!mid || mid.indexOf("XXXX") !== -1) return; // placeholder → no-op
    bbAnalytics = firebase.analytics();
    bbAnalytics.setAnalyticsCollectionEnabled(true);
    try {
      bbAnalytics.setConsent({
        ad_storage: "denied",
        ad_user_data: "denied",
        ad_personalization: "denied",
        analytics_storage: "granted",
      });
    } catch (e) { /* setConsent no disponible en esta versión: defaults GA4 OK */ }
  } catch (e) {
    bbAnalytics = null;
  }
})();

function bbTrack(eventName, params) {
  try {
    if (bbAnalytics) bbAnalytics.logEvent(eventName, params || {});
  } catch (e) { /* no-op */ }
  (window.__bbEvents = window.__bbEvents || []).push({ e: eventName, p: params || {}, t: Date.now() });
}

/* Scroll depth 25/50/75/100 (una vez cada uno). */
(function bbScrollDepth() {
  const marks = [25, 50, 75, 100];
  const fired = {};
  const onScroll = function () {
    const doc = document.documentElement;
    const height = doc.scrollHeight - doc.clientHeight;
    if (height <= 0) return;
    const pct = Math.round(((doc.scrollTop || document.body.scrollTop) / height) * 100);
    marks.forEach(function (m) {
      if (pct >= m && !fired[m]) { fired[m] = true; bbTrack("scroll_depth", { percent: m }); }
    });
  };
  window.addEventListener("scroll", onScroll, { passive: true });
})();

/* matchKey: últimos 10 dígitos del teléfono, para correlacionar con el wa_id de WhatsApp. */
function bbMatchKey(tel) {
  const d = (tel || "").replace(/\D/g, "");
  return d.length < 10 ? "" : d.slice(-10);
}

/* Guarda el lead en Firestore (fire-and-forget desde el form). */
function saveLead(fields) {
  return bbDb.collection("leads").add({
    nombre: fields.nombre || "",
    email: fields.email || "",
    telefono: fields.telefono || "",
    estudias: fields.estudias || "",
    universidad: fields.universidad || "",
    mensaje: fields.mensaje || "",
    matchKey: bbMatchKey(fields.telefono),
    source: "landing",
    status: "formulario_enviado",
    createdAt: firebase.firestore.FieldValue.serverTimestamp(),
    updatedAt: firebase.firestore.FieldValue.serverTimestamp(),
    wa: { waId: null, lastMessageId: null, firstInboundAt: null, lastInboundAt: null, windowExpiresAt: null },
    flow: { intent: null, intentAt: null, duda: null, awaitingDuda: false },
    stages: {
      billboard: { status: "pending", by: null, at: null },
      agency: { status: "pending", by: null, at: null },
    },
    emailFlags: { welcomeSent: false, infoSent: false, reactivationSent: false },
  });
}

Object.assign(window, { Reveal, Section, Icons, BB, saveLead, bbTrack });
