/* Torre Auro — El Calendario (eventos del ecosistema) */

/* Helper: format ISO date to nice MX format */
function fmtMonth(iso) {
  const d = new Date(iso + 'T12:00:00');
  return d.toLocaleDateString('es-MX', { month:'long', year:'numeric' });
}
function fmtDay(iso) {
  const d = new Date(iso + 'T12:00:00');
  return d.toLocaleDateString('es-MX', { day:'numeric', month:'short' }).replace('.', '');
}
function fmtDayNum(iso) {
  return new Date(iso + 'T12:00:00').getDate();
}
function fmtMonthShort(iso) {
  return new Date(iso + 'T12:00:00').toLocaleDateString('es-MX', { month:'short' }).replace('.', '').toUpperCase();
}

/* Featured (apertura) ─── */
function FeaturedEvent({ event }) {
  const acc = NICHE_ACC[event.niche] || 'var(--gold)';
  return (
    <article className="ev-featured" onClick={() => navigate('/eventos/' + event.slug)}>
      <div className="ev-featured-grid">
        <div className="ev-featured-img">
          <div className={`bg-cover ${event.cover}`} aria-hidden="true" />
          <div className="ev-featured-overlay" />
          <span className="ev-featured-tag" style={{ color: acc }}>
            <span style={{width:6,height:6,background:acc,borderRadius:'50%'}}/>
            {STATUS_META[event.status]}
          </span>
        </div>
        <div className="ev-featured-body">
          <div className="ev-date-block">
            <span className="ev-date-day">{fmtDayNum(event.dateISO)}</span>
            <span className="ev-date-month">{fmtMonthShort(event.dateISO)}</span>
            <span className="ev-date-year">{new Date(event.dateISO).getFullYear()}</span>
          </div>
          <div className="ev-kind">{event.kind}</div>
          <h2>{event.title}</h2>
          <p>{event.short}</p>
          <div className="ev-meta">
            <div><span className="lbl">Fecha</span><span className="val">{event.dateNice || event.date}</span></div>
            {event.timeLabel && <div><span className="lbl">Horario</span><span className="val">{event.timeLabel}</span></div>}
            {event.capacity && <div><span className="lbl">Capacidad</span><span className="val">{event.capacity} personas</span></div>}
            <div><span className="lbl">Acceso</span><span className="val">{event.audience}</span></div>
          </div>
          <button className="btn btn-gold" style={{ marginTop:32 }}>
            Ver el evento <Icon n="ti-arrow-right" />
          </button>
        </div>
      </div>
    </article>
  );
}

/* Row ─── */
function EventRow({ event }) {
  const acc = NICHE_ACC[event.niche] || 'var(--gold)';
  return (
    <article
      className={`ev-row status-${event.status}`}
      onClick={() => navigate('/eventos/' + event.slug)}
    >
      <div className="ev-row-date">
        <span className="d">{fmtDayNum(event.dateISO)}</span>
        <span className="m">{fmtMonthShort(event.dateISO)}</span>
      </div>
      <div className="ev-row-niche">
        <span className="ev-niche-dot" style={{ background: acc }} />
        <span>{NICHE_LABEL[event.niche]}</span>
      </div>
      <div className="ev-row-main">
        <div className="ev-row-kind">{event.kind}</div>
        <h3>{event.title}</h3>
        <p>{event.short}</p>
      </div>
      <div className="ev-row-status">
        <span className="status-pill" data-status={event.status}>{STATUS_META[event.status]}</span>
        {event.capacity && <div className="ev-cap">{event.capacity} pers.</div>}
      </div>
      <div className="ev-row-arrow" aria-hidden="true">→</div>
    </article>
  );
}

/* Index ─── */
function EventosIndex() {
  const featured = EVENTS.find(e => e.status === 'featured');
  const upcoming = EVENTS
    .filter(e => e.status === 'upcoming')
    .sort((a, b) => a.dateISO.localeCompare(b.dateISO));
  const past = EVENTS
    .filter(e => e.status === 'past')
    .sort((a, b) => b.dateISO.localeCompare(a.dateISO));

  return (
    <div className="eventos-page">
      {/* Hero */}
      <section className="ed-hero">
        <div className="container">
          <div className="kicker">/ El calendario del ecosistema</div>
          <h1 className="ed-hero-title">
            La agenda de <em>Torre Auro.</em>
          </h1>
          <p className="ed-hero-sub">
            Conversaciones, cumbres, cócteles y sesiones cerradas a lo largo del año. La mayoría son por invitación o cupo limitado — el calendario es la conversación viva del ecosistema.
          </p>
          <div className="ed-hero-meta">
            <span>{upcoming.length + (featured ? 1 : 0)} próximos eventos</span>
            <span>·</span>
            <span>Apertura · Julio 2026</span>
          </div>
        </div>
      </section>

      {/* Featured · Apertura */}
      {featured && (
        <section className="ev-featured-section">
          <div className="container">
            <div className="kicker" style={{ marginBottom:28 }}>/ El evento del año</div>
            <FeaturedEvent event={featured} />
          </div>
        </section>
      )}

      {/* Upcoming */}
      <section className="section paper">
        <div className="container">
          <div className="section-head" style={{ marginBottom:48 }}>
            <div className="kicker">/ Próximos</div>
            <h2>Lo que <em>sigue.</em></h2>
            <p>Cada evento del calendario está pensado para uno de los cuatro ecosistemas — o para todos. La selección de asistentes es curada; algunos eventos son por invitación cerrada.</p>
          </div>

          <div className="ev-list">
            {upcoming.map(e => <EventRow key={e.id} event={e} />)}
          </div>
        </div>
      </section>

      {/* Past */}
      {past.length > 0 && (
        <section className="section cream">
          <div className="container">
            <div className="section-head" style={{ marginBottom:48 }}>
              <div className="kicker">/ Archivo</div>
              <h2>Lo que <em>ya pasó.</em></h2>
            </div>
            <div className="ev-list compact">
              {past.map(e => <EventRow key={e.id} event={e} />)}
            </div>
          </div>
        </section>
      )}

      {/* CTA */}
      <section className="close-banner">
        <div className="container close-inner">
          <div className="kicker light center" style={{ justifyContent:'center', marginBottom:24 }}>/ Invitaciones</div>
          <h2>¿Quieres recibir<br/>las <em>invitaciones</em>?</h2>
          <div className="close-actions" style={{ marginTop:36 }}>
            <button className="btn btn-gold" onClick={() => navigate('/contacto')}>
              Pedir invitación <Icon n="ti-arrow-right" />
            </button>
            <button className="btn btn-outline-light" onClick={() => navigate('/perspectiva')}>
              Leer Perspectiva
            </button>
          </div>
        </div>
      </section>
    </div>
  );
}

/* Detail ─── */
function EventoDetail({ event }) {
  const acc = NICHE_ACC[event.niche] || 'var(--gold)';
  const isFeat = event.status === 'featured';

  return (
    <div className="evento-detail">
      <section className="ed-post-cover">
        <div className={`bg-cover zoom ${event.cover}`} aria-hidden="true" />
        <div className="ed-post-cover-overlay" />
        <div className="container ed-post-cover-content">
          <button className="lvl-back" onClick={() => navigate('/eventos')}>
            <Icon n="ti-arrow-left" /> Volver al calendario
          </button>

          <div className="ev-tag-row">
            <span className="lvl-tag" style={{ color: acc, borderColor: acc }}>
              <span style={{width:6,height:6,background:acc,borderRadius:'50%'}}/>
              {NICHE_LABEL[event.niche]}
            </span>
            <span className="lvl-tag" style={{ color:'#fff', borderColor:'rgba(255,255,255,.4)' }}>
              {STATUS_META[event.status]}
            </span>
          </div>

          <div className="ev-detail-head">
            <div className="ev-date-block big">
              <span className="ev-date-day">{fmtDayNum(event.dateISO)}</span>
              <span className="ev-date-month">{fmtMonthShort(event.dateISO)}</span>
              <span className="ev-date-year">{new Date(event.dateISO).getFullYear()}</span>
            </div>
            <div>
              <div className="ev-kind light">{event.kind}</div>
              <h1>{event.title}</h1>
              <p className="desc">{event.desc}</p>
            </div>
          </div>
        </div>
      </section>

      {/* Meta strip */}
      <div style={{ background:'var(--cream)' }}>
        <div className="container">
          <div className="ev-detail-strip">
            <div>
              <div className="ev-strip-lbl">Fecha</div>
              <div className="ev-strip-val">{event.dateNice || event.date}</div>
            </div>
            {event.timeLabel && (
              <div>
                <div className="ev-strip-lbl">Horario</div>
                <div className="ev-strip-val">{event.timeLabel}</div>
              </div>
            )}
            {event.capacity && (
              <div>
                <div className="ev-strip-lbl">Capacidad</div>
                <div className="ev-strip-val">{event.capacity} personas</div>
              </div>
            )}
            <div>
              <div className="ev-strip-lbl">Acceso</div>
              <div className="ev-strip-val">{event.audience}</div>
            </div>
          </div>
        </div>
      </div>

      {/* Agenda */}
      {event.agenda && (
        <section className="section paper">
          <div className="container">
            <div className="section-head" style={{ marginBottom:48 }}>
              <div className="kicker">/ Agenda</div>
              <h2>El <em>recorrido.</em></h2>
            </div>
            <div className="agenda-list">
              {event.agenda.map((a, i) => (
                <div key={i} className="agenda-row">
                  <div className="agenda-hr">{a.hr}</div>
                  <div className="agenda-main">
                    <div className="agenda-label">{a.label}</div>
                    <div className="agenda-loc">{a.loc}</div>
                  </div>
                  <div className="agenda-num">{pad2(i + 1)}</div>
                </div>
              ))}
            </div>
          </div>
        </section>
      )}

      {/* Speaker */}
      {event.speaker && (
        <section className="section cream">
          <div className="container ev-speaker">
            <div className="kicker">/ Presencia de apertura</div>
            <h2 className="ev-speaker-title">{event.speaker.hint}</h2>
            <p className="ev-speaker-copy">{event.speaker.copy}</p>
          </div>
        </section>
      )}

      {/* CTA */}
      <section className="close-banner">
        <div className="container close-inner">
          <div className="kicker light center" style={{ justifyContent:'center', marginBottom:24 }}>/ Acceso</div>
          <h2>
            {event.status === 'featured'
              ? <>Pide tu <em>invitación</em>.</>
              : event.status === 'past'
                ? <>Suscríbete <em>a las próximas.</em></>
                : <>¿Te <em>interesa</em>?</>}
          </h2>
          <div className="close-actions" style={{ marginTop:36 }}>
            <button className="btn btn-gold" onClick={() => navigate('/contacto')}>
              {event.status === 'past' ? 'Recibir invitaciones' : 'Pedir invitación'} <Icon n="ti-arrow-right" />
            </button>
            <button className="btn btn-outline-light" onClick={() => navigate('/eventos')}>
              Ver el calendario
            </button>
          </div>
        </div>
      </section>
    </div>
  );
}

Object.assign(window, { EventosIndex, EventoDetail });
