// ============================================================
// Foro Valor Emprendedor ? Components
// ============================================================
const { useState, useEffect, useRef, useMemo } = React;

const CONTACT_EMAIL = "evento@fundacionvaloremprendedor.com";
const CONTACT_PHONE_DISPLAY = "+34 611 94 13 68";
const CONTACT_PHONE_RAW = "34611941368";
const CONTACT_WHATSAPP_URL = `https://wa.me/${CONTACT_PHONE_RAW}`;
const FLOAT_WHATSAPP_RAW = CONTACT_PHONE_RAW;
const FLOAT_WHATSAPP_URL = `https://wa.me/${FLOAT_WHATSAPP_RAW}`;
const CONTACT_MAILTO_URL = `mailto:${CONTACT_EMAIL}`;
const CONTACT_TEL_URL = `tel:+${CONTACT_PHONE_RAW}`;
const SOCIAL_X_URL = "https://x.com/ForoValor";
const SOCIAL_INSTAGRAM_URL = "https://www.instagram.com/forovaloremprendedor/";
const SOCIAL_LINKEDIN_URL = "https://www.linkedin.com/company/foro-valor-emprendedor/?viewAsMember=true";

async function submitInboxForm(payload) {
  const response = await fetch("/api/contact.php", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "Accept": "application/json",
    },
    body: JSON.stringify({
      formType: payload.formType || "Solicitud web",
      audience: payload.audience || "",
      nombre: payload.nombre || "",
      medio: payload.medio || "",
      email: payload.email || "",
      telefono: payload.telefono || "",
      empresa: payload.empresa || "",
      acreditaciones: payload.acreditaciones || "",
      mensaje: payload.mensaje || "",
      motivacion: payload.motivacion || "",
      origen: payload.origen || window.location.href,
    }),
  });

  let data = {};
  try {
    data = await response.json();
  } catch (error) {
    data = {};
  }

  if (!response.ok || !data.ok) {
    throw new Error(data.error || "No se pudo enviar el formulario.");
  }

  return data;
}

// ---------- Custom Cursor ----------
function CustomCursor() {
  const dotRef = useRef(null);
  const ringRef = useRef(null);
  const [label, setLabel] = useState("");
  const [hovering, setHovering] = useState(false);
  const hoverStateRef = useRef({ hovering: false, label: "" });

  useEffect(() => {
    if (window.matchMedia("(pointer: coarse)").matches) return undefined;

    let mx = window.innerWidth / 2, my = window.innerHeight / 2;
    let rx = mx, ry = my;
    let dx = mx, dy = my;
    let raf;

    const onMove = (e) => {
      mx = e.clientX; my = e.clientY;
    };
    const onOver = (e) => {
      const t = e.target.closest("[data-cursor]");
      const nextHovering = !!t;
      const nextLabel = t ? (t.getAttribute("data-cursor") || "") : "";
      const { hovering: prevHovering, label: prevLabel } = hoverStateRef.current;

      if (nextHovering !== prevHovering) {
        hoverStateRef.current.hovering = nextHovering;
        setHovering(nextHovering);
      }
      if (nextLabel !== prevLabel) {
        hoverStateRef.current.label = nextLabel;
        setLabel(nextLabel);
      }
    };

    const tick = () => {
      rx += (mx - rx) * 0.76;
      ry += (my - ry) * 0.76;
      dx += (mx - dx) * 0.92;
      dy += (my - dy) * 0.92;
      if (dotRef.current) dotRef.current.style.transform = `translate3d(${dx}px, ${dy}px, 0) translate(-50%, -50%)`;
      if (ringRef.current) {
        const scale = hoverStateRef.current.hovering ? 2.35 : 1;
        ringRef.current.style.transform = `translate3d(${rx}px, ${ry}px, 0) translate(-50%, -50%) scale(${scale})`;
      }
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);

    window.addEventListener("pointermove", onMove, { passive: true });
    window.addEventListener("mouseover", onOver);
    return () => {
      cancelAnimationFrame(raf);
      window.removeEventListener("pointermove", onMove);
      window.removeEventListener("mouseover", onOver);
    };
  }, []);

  return (
    <>
      <div ref={dotRef} className="cursor-dot" />
      <div ref={ringRef} className={`cursor-ring ${hovering ? "is-hover" : ""}`}>
        {label && <span className="cursor-label">{label}</span>}
      </div>
    </>
  );
}

Object.assign(window, {
  CONTACT_EMAIL,
  CONTACT_PHONE_DISPLAY,
  CONTACT_PHONE_RAW,
  CONTACT_WHATSAPP_URL,
  FLOAT_WHATSAPP_RAW,
  FLOAT_WHATSAPP_URL,
  CONTACT_MAILTO_URL,
  CONTACT_TEL_URL,
  SOCIAL_X_URL,
  SOCIAL_INSTAGRAM_URL,
  SOCIAL_LINKEDIN_URL,
  submitInboxForm,
});

// ---------- Floating WhatsApp ----------
function FloatingWhatsApp() {
  return (
    <a
      href={FLOAT_WHATSAPP_URL}
      className="wa-float"
      target="_blank"
      rel="noopener"
      aria-label="Abrir conversación de WhatsApp"
      data-cursor="WhatsApp"
    >
      <span className="wa-float-icon" aria-hidden="true">
        <svg viewBox="0 0 32 32" width="22" height="22" fill="currentColor">
          <path d="M19.11 17.27c-.26-.13-1.53-.75-1.77-.84-.24-.09-.41-.13-.58.13-.17.26-.67.84-.82 1.01-.15.17-.3.2-.56.07-.26-.13-1.08-.4-2.07-1.28-.76-.68-1.28-1.53-1.43-1.79-.15-.26-.02-.4.11-.53.12-.12.26-.3.39-.45.13-.15.17-.26.26-.43.09-.17.04-.32-.02-.45-.07-.13-.58-1.4-.8-1.92-.21-.5-.43-.43-.58-.44h-.5c-.17 0-.45.07-.69.32-.24.26-.91.89-.91 2.17s.93 2.52 1.06 2.69c.13.17 1.83 2.8 4.43 3.92.62.27 1.11.43 1.49.55.63.2 1.2.17 1.65.1.5-.07 1.53-.63 1.75-1.23.22-.6.22-1.11.15-1.23-.06-.11-.23-.17-.49-.3Z" />
          <path d="M16.03 3.2c-7.01 0-12.7 5.68-12.7 12.68 0 2.23.58 4.4 1.68 6.31L3.2 28.8l6.76-1.77a12.73 12.73 0 0 0 6.07 1.54h.01c7 0 12.69-5.69 12.69-12.69S23.04 3.2 16.03 3.2Zm0 23.24h-.01a10.57 10.57 0 0 1-5.39-1.47l-.39-.23-4.01 1.05 1.07-3.91-.25-.4a10.52 10.52 0 0 1-1.62-5.6c0-5.82 4.75-10.56 10.59-10.56 2.82 0 5.47 1.09 7.46 3.09a10.49 10.49 0 0 1 3.09 7.47c0 5.83-4.75 10.57-10.59 10.57Z" />
        </svg>
      </span>
      <span className="wa-float-label">Necesitas ayuda con algo?</span>
    </a>
  );
}

// ---------- Nav ----------
function Nav({ dark, current = "home" }) {
  const [scrolled, setScrolled] = useState(false);
  const [open, setOpen] = useState(false);

  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 40);
    window.addEventListener("scroll", onScroll);
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  const logo = dark ? "assets/logo-blanco.png" : "assets/logo-color.png";

  const homeSection = (anchor) => current === "home" ? anchor : `/${anchor}`;

  const links = [
    { href: "/", label: "Inicio", key: "home" },
    { href: homeSection("#ponentes-invitados"), label: "Ponentes", key: "ponentes" },
    { href: "/agenda/", label: "Agenda", key: "agenda" },
    { href: homeSection("#entradas-foro"), label: "Entradas", key: "entradas" },
    { href: "/patrocinadores/", label: "Patrocinadores", key: "patrocinadores" },
    { href: "/prensa/", label: "Prensa", key: "prensa" },
  ];

  const reservaHref = current === "home" ? "#contacto-reservas" : "/#contacto-reservas";

  const IconTW = () => (
    <svg viewBox="0 0 24 24" width="14" height="14" fill="currentColor"><path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-4.714-6.231-5.401 6.231H2.746l7.73-8.835L1.254 2.25H8.08l4.253 5.622 5.912-5.622zm-1.161 17.52h1.833L7.084 4.126H5.117z"/></svg>
  );
  const IconIG = () => (
    <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="2">
      <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.8" fill="currentColor"/>
    </svg>
  );
  const IconLI = () => (
    <svg viewBox="0 0 24 24" width="14" height="14" fill="currentColor"><path d="M16 8a6 6 0 0 1 6 6v7h-4v-7a2 2 0 0 0-2-2 2 2 0 0 0-2 2v7h-4v-7a6 6 0 0 1 6-6zM2 9h4v12H2zm2-5a2 2 0 1 1 0 4 2 2 0 0 1 0-4z"/></svg>
  );

  return (
    <header className={`nav ${scrolled ? "is-scrolled" : ""}`}>
      <a href="/" className="nav-logo" data-cursor="Inicio">
        <img src={logo} alt="Foro Valor Emprendedor" />
      </a>
      <nav className="nav-links">
        {links.map((l) => (
          <a key={l.key} href={l.href} className={current === l.key ? "is-active" : ""} data-cursor="Ir">
            <span>{l.label}</span>
            <span aria-hidden>{l.label}</span>
          </a>
        ))}
      </nav>
      <div className="nav-right">
        <a href={reservaHref} className="btn btn-primary btn-sm" data-cursor="Reservar">
          Reservar plaza
          <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="2.5"><path d="M5 12h14M13 5l7 7-7 7"/></svg>
        </a>
        <div className="nav-social">
          <a href={SOCIAL_X_URL} target="_blank" rel="noopener" className="nav-social-btn" data-cursor="X" aria-label="X">
            <IconTW />
          </a>
          <a href={SOCIAL_INSTAGRAM_URL} target="_blank" rel="noopener" className="nav-social-btn" data-cursor="Instagram" aria-label="Instagram">
            <IconIG />
          </a>
          <a href={SOCIAL_LINKEDIN_URL} target="_blank" rel="noopener" className="nav-social-btn" data-cursor="LinkedIn" aria-label="LinkedIn">
            <IconLI />
          </a>
        </div>
        <button className="nav-burger" onClick={() => setOpen(!open)} aria-label="Menú">
          <span /><span /><span />
        </button>
      </div>
      {open && (
        <div className="nav-mobile">
          {links.map((l) => (
            <a key={l.key} href={l.href} className={current === l.key ? "is-active" : ""} onClick={() => setOpen(false)}>{l.label}</a>
          ))}
          <a href={reservaHref} className="btn btn-primary" onClick={() => setOpen(false)}>
            Reservar plaza
          </a>
          <div className="nav-mobile-social">
            <a href={SOCIAL_X_URL} target="_blank" rel="noopener" className="nav-social-btn" aria-label="X"><IconTW /></a>
            <a href={SOCIAL_INSTAGRAM_URL} target="_blank" rel="noopener" className="nav-social-btn" aria-label="Instagram"><IconIG /></a>
            <a href={SOCIAL_LINKEDIN_URL} target="_blank" rel="noopener" className="nav-social-btn" aria-label="LinkedIn"><IconLI /></a>
          </div>
        </div>
      )}
    </header>
  );
}

// ---------- Hero ----------
function HeroOrbs() {
  const o1 = useRef(null);
  const o2 = useRef(null);
  useEffect(() => {
    let raf;
    const start = performance.now();
    const loop = (now) => {
      const t = (now - start) / 1000;
      if (o1.current) o1.current.style.transform = `translate(${Math.sin(t * 0.3) * 30}px, ${Math.cos(t * 0.2) * 20}px)`;
      if (o2.current) o2.current.style.transform = `translate(${Math.cos(t * 0.25) * 40}px, ${Math.sin(t * 0.35) * 30}px)`;
      raf = requestAnimationFrame(loop);
    };
    raf = requestAnimationFrame(loop);
    return () => cancelAnimationFrame(raf);
  }, []);
  return (
    <div className="hero-bg">
      <div className="hero-grain" />
      <div ref={o1} className="hero-orb hero-orb-1" />
      <div ref={o2} className="hero-orb hero-orb-2" />
    </div>
  );
}

function HeroCountdown() {
  const [cd, setCd] = useState(() => {
    const target = new Date("2026-09-26T09:00:00+02:00").getTime();
    const diff = Math.max(0, target - Date.now());
    return {
      d: Math.floor(diff / 86400000),
      h: Math.floor((diff % 86400000) / 3600000),
      m: Math.floor((diff % 3600000) / 60000),
    };
  });
  useEffect(() => {
    const id = setInterval(() => {
      const target = new Date("2026-09-26T09:00:00+02:00").getTime();
      const diff = Math.max(0, target - Date.now());
      setCd({
        d: Math.floor(diff / 86400000),
        h: Math.floor((diff % 86400000) / 3600000),
        m: Math.floor((diff % 3600000) / 60000),
      });
    }, 30000);
    return () => clearInterval(id);
  }, []);
  return (
    <div className="hero-count">
      <div className="hero-count-label">Empieza en</div>
      <div className="hero-count-grid">
        <div><b>{cd.d}</b><span>días</span></div>
        <div><b>{String(cd.h).padStart(2, "0")}</b><span>horas</span></div>
        <div><b>{String(cd.m).padStart(2, "0")}</b><span>min</span></div>
      </div>
    </div>
  );
}

function Hero() {
  return (
    <section className="hero" id="top">
      <HeroOrbs />

      <div className="hero-meta-top">
        <div className="hero-meta-item">
          <span className="dot-pulse" />
          Edición 2026 · Plazas abiertas
        </div>
        <div className="hero-meta-item hero-meta-item-alt">
          Auditorio Mar de Vigo · Galicia
        </div>
      </div>

      <div className="hero-content">
        <h1 className="hero-title">
          <span className="hero-line">
            <span className="hero-word">El foro</span>
          </span>
          <span className="hero-line">
            <span className="hero-word hero-word-outline">donde </span>
            <span className="hero-word hero-italic">Galicia</span>
          </span>
          <span className="hero-line">
            <span className="hero-word">emprende <em className="hero-amp">&</em> crece.</span>
          </span>
        </h1>

        <div className="hero-sub-row">
          <div className="hero-sub-col">
            <p className="hero-sub">
              Un día. Dieciocho ponentes del habla hispana. Cientos de emprendedores
              compartiendo clientes, aprendizajes y oportunidades reales.
            </p>
            <div className="hero-ctas">
              <a href="#contacto-reservas" className="btn btn-primary btn-lg magnetic" data-cursor="Reservar">
                Reservar mi plaza
                <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="2.5"><path d="M5 12h14M13 5l7 7-7 7"/></svg>
              </a>
              <a href="#ponentes-invitados" className="btn btn-ghost btn-lg" data-cursor="Ver">
                <span className="btn-play">
                  <svg viewBox="0 0 24 24" width="10" height="10" fill="currentColor"><path d="M8 5v14l11-7z"/></svg>
                </span>
                Ver ponentes
              </a>
            </div>
          </div>
        </div>
      </div>

      <div className="hero-bottom">
        <HeroCountdown />
        <div className="hero-organizers">
          <div className="hero-organizers-label">Organizadores</div>
          <a
            href="https://asesoriaemprendedor.es/"
            target="_blank"
            rel="noopener noreferrer"
            className="hero-organizers-card"
            data-cursor="Abrir"
            aria-label="Abrir web de Asesoría Emprendedor"
          >
            <img src="assets/asesoria-emprendedor-logo.png" alt="Asesoría Emprendedor" className="hero-organizers-logo" />
          </a>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { CustomCursor, FloatingWhatsApp, Nav, Hero });
