﻿// ============================================================
// Page components: Agenda, Patrocinadores, Prensa
// ============================================================
const { useState: useStateP, useEffect: useEffectP, useRef: useRefP } = React;

// ---------- Shared PageHero ----------
function PageHero({ eyebrow, title, italic, sub, meta }) {
  const innerRef = useRefP(null);

  useEffectP(() => {
    let raf = 0;
    raf = requestAnimationFrame(() => {
      if (innerRef.current) innerRef.current.classList.add("is-loaded");
    });
    return () => cancelAnimationFrame(raf);
  }, []);

  const renderMaskedWords = (text) => (
    text.split(" ").map((word, i) => (
      <React.Fragment key={`${word}-${i}`}>
        {i > 0 ? " " : null}
        <span className="ph-word-mask">
          <span className="ph-word" style={{ animationDelay: `${0.14 + i * 0.07}s` }}>
            {word}
          </span>
        </span>
      </React.Fragment>
    ))
  );

  return (
    <section className="page-hero">
      <div className="hero-bg">
        <div className="hero-grain" />
        <div className="hero-orb hero-orb-1" />
        <div className="hero-orb hero-orb-2" />
      </div>
      <div ref={innerRef} className="page-hero-inner">
        <div className="section-eyebrow">
          <span className="eyebrow-line" />
          <span>{eyebrow}</span>
        </div>
        <h1 className="page-hero-title">
          {renderMaskedWords(title)}{" "}
          <em>{renderMaskedWords(italic)}</em>
        </h1>
        {sub && <p className="page-hero-sub" style={{ animationDelay: "0.34s" }}>{sub}</p>}
        {meta && (
          <div className="page-hero-meta" style={{ animationDelay: "0.42s" }}>
            {meta.map((m, i) => (
              <div key={i} className="page-hero-meta-item">
                <span className="page-hero-meta-label">{m.label}</span>
                <span className="page-hero-meta-val">{m.val}</span>
              </div>
            ))}
          </div>
        )}
      </div>
    </section>
  );
}

// ---------- Agenda ----------
function AgendaPage() {
  const [track, setTrack] = useStateP("todo");

  const sessions = [
    { time: "08:30", end: "09:00", type: "registro", title: "Registro y café de bienvenida", speaker: "—", room: "Hall principal", track: "todo" },
    { time: "09:00", end: "09:30", type: "apertura", title: "Apertura oficial del Foro Valor Emprendedor 2026", speaker: "Comité organizador", room: "Auditorio", track: "todo" },
    { time: "09:30", end: "10:30", type: "keynote", title: "El emprendedor del futuro: visión y resiliencia", speaker: "Marcos Urarte", role: "Consultor estratégico internacional", room: "Auditorio", track: "inspiracion" },
    { time: "10:30", end: "11:15", type: "keynote", title: "Cómo escalar un negocio en tiempos de incertidumbre", speaker: "Víctor Küppers", role: "Conferenciante y autor", room: "Auditorio", track: "negocio" },
    { time: "11:15", end: "11:45", type: "break", title: "Networking coffee break", speaker: "—", room: "Zona expo", track: "todo" },
    { time: "11:45", end: "12:45", type: "panel", title: "Galicia emprende: mesa redonda con founders locales", speaker: "4 fundadores gallegos", role: "Panel moderado", room: "Auditorio", track: "negocio" },
    { time: "12:45", end: "13:30", type: "keynote", title: "Marca personal y ventas: cómo vender sin vender", speaker: "Isra Bravo", role: "Copywriter y formador", room: "Auditorio", track: "marketing" },
    { time: "13:30", end: "15:00", type: "break", title: "Comida networking", speaker: "—", room: "Terraza Mar de Vigo", track: "todo" },
    { time: "15:00", end: "16:00", type: "keynote", title: "De cero a referente: construir una empresa con propósito", speaker: "Pau García-Milà", role: "Emprendedor tecnológico", room: "Auditorio", track: "inspiracion" },
    { time: "16:00", end: "16:45", type: "workshop", title: "Workshop: Finanzas claras para founders", speaker: "Gregorio Hernández", role: "Profesor de finanzas UNED", room: "Sala Atlántico", track: "negocio" },
    { time: "16:00", end: "16:45", type: "workshop", title: "Workshop: Growth marketing con IA", speaker: "Ronny Bendavid", role: "Growth advisor", room: "Sala Rías Baixas", track: "marketing" },
    { time: "16:45", end: "17:15", type: "break", title: "Break + zona inversores", speaker: "—", room: "Zona expo", track: "todo" },
    { time: "17:15", end: "18:15", type: "keynote", title: "Liderazgo humano: equipos que crean futuro", speaker: "Silvia Leal", role: "Experta en transformación", room: "Auditorio", track: "inspiracion" },
    { time: "18:15", end: "19:00", type: "panel", title: "Inversión en Galicia: fondos que apuestan por el norte", speaker: "Panel de inversores", role: "Moderado por José Luis Casal", room: "Auditorio", track: "negocio" },
    { time: "19:00", end: "19:45", type: "keynote", title: "Cierre magistral: el valor de emprender hoy", speaker: "Luis Galindo", role: "Conferenciante y coach", room: "Auditorio", track: "inspiracion" },
    { time: "19:45", end: "20:30", type: "cierre", title: "Cierre + cóctel de clausura", speaker: "—", room: "Terraza", track: "todo" },
  ];

  const filtered = track === "todo" ? sessions : sessions.filter(s => s.track === track || s.track === "todo");

  const tracks = [
    { k: "todo", l: "Todo el programa" },
    { k: "inspiracion", l: "Inspiración" },
    { k: "negocio", l: "Negocio" },
    { k: "marketing", l: "Marketing & Ventas" },
  ];

  const typeLabel = {
    registro: "Registro", apertura: "Apertura", keynote: "Ponencia",
    panel: "Mesa redonda", workshop: "Workshop", break: "Break", cierre: "Cierre"
  };

  return (
    <main>
      <PageHero
        eyebrow="Programa  26 septiembre 2026"
        title="Un día intenso,"
        italic={"dise\u00f1ado para ti."}
        sub="16 sesiones, 12 ponentes internacionales, 2 workshops paralelos y mucho networking. Este es el programa completo del foro."
        meta={[
          { label: "Inicio", val: "09:00" },
          { label: "Fin", val: "20:30" },
          { label: "Sesiones", val: "16" },
          { label: "Ponentes", val: "12" },
        ]}
      />

      <section className="agenda-section">
        <Reveal className="agenda-filters">
          {tracks.map(t => (
            <button key={t.k} className={`agenda-filter ${track === t.k ? "is-active" : ""}`} onClick={() => setTrack(t.k)} data-cursor="Filtrar">
              {t.l}
            </button>
          ))}
        </Reveal>

        <div className="agenda-list">
          {filtered.map((s, i) => (
            <Reveal key={i} className={`agenda-row type-${s.type}`} delay={i * 30}>
              <div className="agenda-time">
                <b>{s.time}</b>
                <span>{s.end}</span>
              </div>
              <div className="agenda-type">
                <span className={`agenda-chip chip-${s.type}`}>{typeLabel[s.type]}</span>
              </div>
              <div className="agenda-body">
                <h3 className="agenda-title">{s.title}</h3>
                {s.role && <p className="agenda-role">{s.role}</p>}
              </div>
              <div className="agenda-speaker">
                <b>{s.speaker}</b>
                <span>{s.room}</span>
              </div>
              <div className="agenda-arrow" data-cursor="Ver">
                <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="2"><path d="M7 17L17 7M9 7h8v8"/></svg>
              </div>
            </Reveal>
          ))}
        </div>

        <Reveal className="agenda-note" delay={120}>
          <span className="mono">// El programa puede sufrir modificaciones. Se notificará a los asistentes por email.</span>
        </Reveal>
      </section>
    </main>
  );
}

// ---------- Patrocinadores ----------
function PatrociniosPage() {
  const tiers = [
    {
      name: "Platinum",
      price: "Desde 15.000€",
      color: "#7ce565",
      highlights: [
        "Logotipo destacado en escenario principal",
        "2 entradas VIP al evento",
        "Zona promocional premium",
        "Presencia en todas las comunicaciones",
        "Branding en acreditaciones de asistentes",
        "Mención en apertura y cierre del foro",
        "Vídeo corporativo en pantalla principal",
        "Material en welcome pack",
      ],
      plazas: "2 plazas"
    },
    {
      name: "Oro",
      price: "Desde 8.000€",
      color: "#00b27b",
      highlights: [
        "Logotipo en escenario",
        "4 entradas PREMIUM al evento",
        "Zona promocional estándar",
        "Presencia en web y redes",
        "Mención en una sesión",
        "Material en welcome pack",
      ],
      plazas: "4 plazas"
    },
    {
      name: "Silver",
      price: "Desde 3.500€",
      color: "#0ee2a6",
      highlights: [
        "Logotipo en pantalla entre sesiones",
        "5 entradas básicas al evento",
        "Mesa expositora en zona networking",
        "Presencia en web",
        "Material en welcome pack",
      ],
      plazas: "8 plazas"
    },
    {
      name: "Colaborador",
      price: "Desde 1.000€",
      color: "#d6d669",
      highlights: [
        "Logotipo en web de patrocinadores",
        "2 entradas básicas al evento",
        "Material en welcome pack",
      ],
      plazas: "Ilimitadas"
    },
  ];

  const current = [
    { name: "Xunta de Galicia", tier: "Institucional" },
    { name: "Ayto. de Vigo", tier: "Institucional" },
    { name: "Abanca", tier: "Platinum" },
    { name: "Zona Franca", tier: "Platinum" },
    { name: "Gadisa", tier: "Gold" },
    { name: "Stellantis Vigo", tier: "Gold" },
    { name: "Inditex", tier: "Gold" },
    { name: "R Cable", tier: "Silver" },
    { name: "Congalsa", tier: "Silver" },
    { name: "CZFV", tier: "Silver" },
    { name: "AJE Galicia", tier: "Colaborador" },
    { name: "Confederación Empresarios", tier: "Colaborador" },
  ];

  return (
    <main>
      <PageHero
        eyebrow="Patrocinadores · Edición 2026"
        title="Impulsemos juntos"
        italic="el emprendimiento gallego."
        sub="Conectar con 1.425 emprendedores, autónomos y directivos en un solo día. Varias modalidades para acompañar el foro según tus objetivos."
      />

      <section className="pat-section">
        <div className="pat-intro">
          <Reveal className="section-eyebrow">
            <span className="eyebrow-line" />
            <span>Modalidades de patrocinio</span>
          </Reveal>
          <Reveal as="h2" className="section-title" delay={80}>
            Cuatro formatos para <em>formar parte</em> del foro.
          </Reveal>
        </div>

        <div className="pat-tiers">
          {tiers.map((t, i) => (
            <Reveal key={i} className="pat-tier" delay={i * 100}>
              <div className="pat-tier-head" style={{ background: t.color, color: "#072b1f" }}>
                <span className="pat-tier-name">{t.name}</span>
                <span className="pat-tier-plazas">{t.plazas}</span>
              </div>
              <div className="pat-tier-body">
                <div className="pat-tier-price">{t.price}</div>
                <ul className="pat-tier-list">
                  {t.highlights.map((h, j) => (
                    <li key={j}>
                      <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="2.5"><path d="M5 12l5 5L20 7"/></svg>
                      {h}
                    </li>
                  ))}
                </ul>
                <a href="/#contacto-reservas" className="btn btn-ghost" data-cursor="Solicitar">
                  Solicitar dossier
                  <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>
            </Reveal>
          ))}
        </div>
      </section>

      <section className="pat-current-section">
        <div className="pat-intro">
          <Reveal className="section-eyebrow">
            <span className="eyebrow-line" />
            <span>Ya confirmados · Edición 2026</span>
          </Reveal>
          <Reveal as="h2" className="section-title" delay={80}>
            Nos acompañan <em>grandes marcas</em>.
          </Reveal>
        </div>

        <div className="pat-grid">
          {current.map((c, i) => (
            <Reveal key={i} className="pat-card" delay={i * 40}>
              <div className="pat-logo-placeholder">
                <div className="stripes" />
                <span className="mono">// logo {c.name}</span>
              </div>
              <div className="pat-card-foot">
                <span className="pat-card-name">{c.name}</span>
                <span className="pat-card-tier">{c.tier}</span>
              </div>
            </Reveal>
          ))}
        </div>
      </section>

      <section className="pat-cta">
        <Reveal as="h2" className="section-title">
          Tu marca, <em>¿la siguiente?</em>
        </Reveal>
        <Reveal className="pat-cta-row" delay={120}>
          <a href="/#contacto-reservas" className="btn btn-primary btn-lg" data-cursor="Contactar">
            Solicitar dossier completo
            <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={CONTACT_MAILTO_URL} className="btn btn-ghost btn-lg" data-cursor="Email">
            {CONTACT_EMAIL}
          </a>
        </Reveal>
      </section>
    </main>
  );
}

// ---------- Prensa ----------
function PrensaPage() {
  const [form, setForm] = useStateP({ nombre: "", medio: "", email: "", telefono: "", acreditaciones: "1", motivacion: "" });
  const [sent, setSent] = useStateP(false);
  const [sending, setSending] = useStateP(false);
  const [sendError, setSendError] = useStateP("");

  const update = (k, v) => setForm({ ...form, [k]: v });
  const emailValid = /\S+@\S+\.\S+/.test(form.email);
  const canSend = form.nombre && form.medio && emailValid && form.motivacion.length > 4;

  const submit = async (e) => {
    e.preventDefault();
    if (!canSend) return;
    setSending(true);
    setSendError("");
    try {
      await submitInboxForm({
        formType: "acreditacion-prensa",
        nombre: form.nombre,
        medio: form.medio,
        email: form.email,
        telefono: form.telefono,
        acreditaciones: form.acreditaciones,
        motivacion: form.motivacion,
        origen: window.location.href,
      });
      setSent(true);
    } catch (error) {
      setSendError(error.message || "No se pudo enviar la acreditación.");
    } finally {
      setSending(false);
    }
  };

  const downloads = [
    { name: "Logotipo color (PNG)", sub: "3 MB  PNG 3000px", href: "assets/logo-color.png" },
    { name: "Logotipo blanco (PNG)", sub: "1.5 MB  PNG 3000px", href: "assets/logo-blanco.png" },
    { name: "Logotipo negro (PNG)", sub: "1.5 MB  PNG 3000px", href: "assets/logo-negro.png" },
    { name: "Manual de marca (PDF)", sub: "Próximamente", href: "#" },
    { name: "Paleta de colores (ASE)", sub: "Próximamente", href: "#" },
    { name: "Dossier de prensa 2026", sub: "Próximamente", href: "#" },
  ];

  const palette = [
    { hex: "#7ce565", name: "Lima", role: "Principal" },
    { hex: "#00b27b", name: "Medio", role: "Principal" },
    { hex: "#072b1f", name: "Oscuro", role: "Principal" },
    { hex: "#0ee2a6", name: "Menta", role: "Secundario" },
    { hex: "#d6f2e8", name: "Suave", role: "Secundario" },
    { hex: "#d6d669", name: "Oliva", role: "Secundario" },
    { hex: "#f9f4e5", name: "Crema", role: "Secundario" },
  ];

  return (
    <main>
      <PageHero
        eyebrow="Sala de prensa  2026"
        title="Información, logos y"
        italic="acreditaciones."
        sub="Todo lo que medios de comunicación, periodistas y creadores necesitan para cubrir el Foro Valor Emprendedor 2026."
      />

      <section className="prensa-section">
        <div className="prensa-grid">
          <div className="prensa-left">
            <Reveal className="section-eyebrow">
              <span className="eyebrow-line" />
              <span>Acreditación de prensa</span>
            </Reveal>
            <Reveal as="h2" className="section-title prensa-title" delay={80}>
              Solicita tu <em>acreditación</em> por correo.
            </Reveal>
            <Reveal className="prensa-desc" delay={160}>
              Rellena el formulario con los datos del medio. Revisamos cada
              solicitud en las 48 h siguientes y te enviamos la confirmación
              junto con el kit de prensa completo.
            </Reveal>

            <Reveal className="prensa-contact-block" delay={220}>
              <div>
                <span className="contact-info-label">Contacto prensa</span>
                <a className="contact-info-val contact-link" href={CONTACT_MAILTO_URL} data-cursor="Email">
                  {CONTACT_EMAIL}
                </a>
                <a className="contact-info-sub contact-link" href={CONTACT_WHATSAPP_URL} target="_blank" rel="noopener" data-cursor="WhatsApp">
                  {CONTACT_PHONE_DISPLAY}
                </a>
              </div>
              <div>
                <span className="contact-info-label">Plazo</span>
                <span className="contact-info-val">Hasta 19 sept 2026</span>
              </div>
            </Reveal>
          </div>

          <Reveal className="prensa-form-wrap" delay={120}>
            {!sent ? (
              <form className="contact-form" onSubmit={submit}>
                <div className="form-row">
                  <label className="form-field">
                    <span>Nombre y apellidos</span>
                    <input value={form.nombre} onChange={(e) => update("nombre", e.target.value)} placeholder="Ana Rodríguez" />
                  </label>
                  <label className="form-field">
                    <span>Medio</span>
                    <input value={form.medio} onChange={(e) => update("medio", e.target.value)} placeholder="La Voz de Galicia" />
                  </label>
                </div>
                <div className="form-row">
                  <label className="form-field">
                    <span>Email profesional</span>
                    <input type="email" value={form.email} onChange={(e) => update("email", e.target.value)} placeholder="ana@medio.com" />
                  </label>
                  <label className="form-field">
                    <span>Teléfono</span>
                    <input value={form.telefono} onChange={(e) => update("telefono", e.target.value)} placeholder="+34 611 941 368" />
                  </label>
                </div>
                <label className="form-field">
                  <span>Acreditaciones solicitadas</span>
                  <select value={form.acreditaciones} onChange={(e) => update("acreditaciones", e.target.value)}>
                    <option value="1">1 periodista</option>
                    <option value="2">2 personas</option>
                    <option value="3">3 personas (reportaje + cámara)</option>
                    <option value="4+">4 o más</option>
                  </select>
                </label>
                <label className="form-field">
                  <span>¿Qué tipo de cobertura tienes previsto?</span>
                  <textarea rows="4" value={form.motivacion} onChange={(e) => update("motivacion", e.target.value)} placeholder="Reportaje, entrevistas, emisión en directo…" />
                </label>
                <div className="form-footer">
                  <label className="form-check">
                    <input type="checkbox" defaultChecked />
                    <span>Acepto la política de privacidad y el tratamiento de mis datos para gestionar la acreditación.</span>
                  </label>
                  <button type="submit" className={`btn btn-primary btn-lg ${!canSend || sending ? "is-disabled" : ""}`} data-cursor="Enviar">
                    Solicitar acreditación
                    <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>
                  </button>
                </div>
                {sendError ? <p className="form-status is-error">{sendError}</p> : null}
              </form>
            ) : (
              <div className="contact-sent">
                <div className="contact-sent-icon">
                  <svg viewBox="0 0 24 24" width="32" height="32" fill="none" stroke="currentColor" strokeWidth="2.5"><path d="M5 12l5 5L20 7"/></svg>
                </div>
                <h3>¡Solicitud recibida!</h3>
                <p>Hemos registrado tu solicitud de prensa y la organizaciÃ³n ya la tiene para revisarla.</p>
                <div className="contact-sent-actions">
                  <a className="btn btn-ghost" href={CONTACT_MAILTO_URL} data-cursor="Email">
                    Escribir por email
                  </a>
                  <a className="btn btn-ghost" href={CONTACT_WHATSAPP_URL} target="_blank" rel="noopener" data-cursor="WhatsApp">
                    Abrir WhatsApp
                  </a>
                </div>
              </div>
            )}
          </Reveal>
        </div>
      </section>

      <section className="prensa-downloads-section">
        <div className="pat-intro">
          <Reveal className="section-eyebrow">
            <span className="eyebrow-line" />
            <span>Descargas</span>
          </Reveal>
          <Reveal as="h2" className="section-title" delay={80}>
            Logotipos y <em>materiales</em> de marca.
          </Reveal>
        </div>
        <div className="prensa-downloads">
          {downloads.map((d, i) => (
            <Reveal key={i} delay={i * 60}>
              <a className="prensa-download" href={d.href} download data-cursor="Descargar">
                <div className="prensa-download-preview">
                  <div className="stripes" />
                </div>
                <div className="prensa-download-info">
                  <b>{d.name}</b>
                  <span>{d.sub}</span>
                </div>
                <div className="prensa-download-icon">
                  <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="2"><path d="M12 4v12m-5-5l5 5 5-5M5 20h14"/></svg>
                </div>
              </a>
            </Reveal>
          ))}
        </div>
      </section>

      <section className="prensa-palette-section">
        <div className="pat-intro">
          <Reveal className="section-eyebrow">
            <span className="eyebrow-line" />
            <span>Identidad visual</span>
          </Reveal>
          <Reveal as="h2" className="section-title" delay={80}>
            Paleta de <em>colores</em> oficial.
          </Reveal>
        </div>
        <div className="palette-grid">
          {palette.map((p, i) => (
            <Reveal key={i} className="palette-card" delay={i * 50}>
              <div className="palette-swatch" style={{ background: p.hex }} />
              <div className="palette-info">
                <b>{p.name}</b>
                <span className="palette-hex">{p.hex}</span>
                <span className="palette-role">{p.role}</span>
              </div>
            </Reveal>
          ))}
        </div>
      </section>
    </main>
  );
}

Object.assign(window, { PageHero, AgendaPage, PatrociniosPage, PrensaPage });
