// Agenda screens + event detail

const trackColor = (tag) => ({
  amber: { bg: 'rgba(245,166,35,0.14)', fg: '#FFB82E', border: 'rgba(245,166,35,0.3)' },
  blue: { bg: 'rgba(58,86,176,0.2)', fg: '#8AA4FF', border: 'rgba(58,86,176,0.35)' },
  purple: { bg: 'rgba(107,46,168,0.2)', fg: '#C699FF', border: 'rgba(107,46,168,0.4)' },
  green: { bg: 'rgba(15,168,155,0.18)', fg: '#4FE0C7', border: 'rgba(15,168,155,0.35)' },
})[tag] || { bg: 'rgba(255,255,255,0.06)', fg: '#fff', border: 'rgba(255,255,255,0.1)' };

const TrackBadge = ({ track, tag }) => {
  const c = trackColor(tag);
  return (
    <span style={{
      fontSize: 10, fontWeight: 600, letterSpacing: '0.1em', textTransform: 'uppercase',
      background: c.bg, color: c.fg, border: `1px solid ${c.border}`,
      padding: '4px 8px', borderRadius: 6,
      fontFamily: "'Geist Mono', monospace",
    }}>{track}</span>
  );
};

// --- Variation A: timeline layout ---
const AgendaTimeline = ({ events, subscribed, onToggle, onOpen }) => (
  <div style={{ padding: '4px 20px 24px' }}>
    {events.map((ev, i) => {
      const sub = subscribed.has(ev.id);
      return (
        <div key={ev.id} style={{ display: 'flex', gap: 14, position: 'relative' }}>
          <div style={{ width: 56, flexShrink: 0, paddingTop: 4 }}>
            <div className="mono" style={{ fontSize: 13, fontWeight: 600, color: '#fff' }}>{ev.time}</div>
            <div className="mono" style={{ fontSize: 10, color: 'var(--text-mute)', marginTop: 2 }}>{ev.duration}</div>
          </div>
          <div style={{ position: 'relative', width: 16, flexShrink: 0 }}>
            <div style={{
              position: 'absolute', top: 8, left: 7, width: 2, bottom: -12,
              background: 'var(--line)',
              display: i === events.length - 1 ? 'none' : 'block',
            }} />
            <div style={{
              width: 10, height: 10, borderRadius: '50%', marginTop: 8,
              background: sub ? 'var(--amber)' : 'var(--navy-700)',
              border: '2px solid #05080F',
              boxShadow: sub ? '0 0 0 2px rgba(245,166,35,0.3)' : 'none',
              position: 'relative', zIndex: 2, marginLeft: 3,
            }} />
          </div>
          <button onClick={() => onOpen(ev)} className="card" style={{
            flex: 1, marginBottom: 14, padding: 14, textAlign: 'left',
            background: 'rgba(255,255,255,0.03)', color: '#fff', font: 'inherit', cursor: 'pointer',
            border: '1px solid var(--line)',
          }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 8, gap: 8 }}>
              <TrackBadge track={ev.track} tag={ev.tag} />
              <button onClick={(e) => { e.stopPropagation(); onToggle(ev.id); }} style={{
                background: sub ? 'var(--amber)' : 'rgba(255,255,255,0.06)',
                border: `1px solid ${sub ? 'var(--amber)' : 'var(--line)'}`,
                color: sub ? '#05080F' : '#fff',
                borderRadius: 999, padding: '4px 10px', fontSize: 11, fontWeight: 600,
                cursor: 'pointer', font: 'inherit', display: 'flex', alignItems: 'center', gap: 4,
              }}>
                {sub ? <><IconCheck size={12} stroke={2.6} /> Inscrito</> : '+ Inscrever'}
              </button>
            </div>
            <div style={{ fontSize: 15, fontWeight: 600, lineHeight: 1.25, marginBottom: 6 }}>{ev.title}</div>
            <div style={{ fontSize: 12, color: 'var(--text-dim)', marginBottom: 10 }}>{ev.speaker}</div>
            <div style={{ display: 'flex', gap: 10, fontSize: 11, color: 'var(--text-mute)' }}>
              <span style={{ display: 'flex', alignItems: 'center', gap: 4 }}><IconMapPin size={12} /> {ev.room}</span>

            </div>
          </button>
        </div>
      );
    })}
  </div>
);

// --- Variation B: card list ---
const AgendaCards = ({ events, subscribed, onToggle, onOpen }) => (
  <div style={{ padding: '4px 20px 24px', display: 'flex', flexDirection: 'column', gap: 14 }}>
    {events.map(ev => {
      const sub = subscribed.has(ev.id);
      return (
        <button key={ev.id} onClick={() => onOpen(ev)} style={{
          background: 'rgba(255,255,255,0.03)',
          border: '1px solid var(--line)',
          borderRadius: 18, overflow: 'hidden', padding: 0, textAlign: 'left',
          color: '#fff', font: 'inherit', cursor: 'pointer',
        }}>
          <div style={{ position: 'relative' }}>
            <Placeholder gradient={ev.gradient} height={120} label={ev.track.toLowerCase()} />
            <div style={{ position: 'absolute', top: 10, left: 10 }}>
              <TrackBadge track={ev.track} tag={ev.tag} />
            </div>
            <div style={{
              position: 'absolute', bottom: 10, right: 10,
              background: 'rgba(5,8,15,0.7)', backdropFilter: 'blur(10px)',
              borderRadius: 10, padding: '6px 10px', display: 'flex', alignItems: 'center', gap: 6,
            }}>
              <IconClock size={12} />
              <span className="mono" style={{ fontSize: 12, fontWeight: 600 }}>{ev.time}</span>
            </div>
          </div>
          <div style={{ padding: 14 }}>
            <div style={{ fontSize: 16, fontWeight: 600, lineHeight: 1.25, marginBottom: 6 }}>{ev.title}</div>
            <div style={{ fontSize: 12, color: 'var(--text-dim)', marginBottom: 12 }}>{ev.speaker} · {ev.role}</div>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <div style={{ display: 'flex', gap: 10, fontSize: 11, color: 'var(--text-mute)' }}>
                <span style={{ display: 'flex', alignItems: 'center', gap: 4 }}><IconMapPin size={12} /> {ev.room}</span>
              </div>
              <button onClick={(e) => { e.stopPropagation(); onToggle(ev.id); }} style={{
                background: sub ? 'var(--amber)' : 'rgba(255,255,255,0.06)',
                border: `1px solid ${sub ? 'var(--amber)' : 'var(--line)'}`,
                color: sub ? '#05080F' : '#fff',
                borderRadius: 999, padding: '6px 12px', fontSize: 12, fontWeight: 600,
                cursor: 'pointer', font: 'inherit', display: 'flex', alignItems: 'center', gap: 4,
              }}>
                {sub ? <><IconCheck size={12} stroke={2.6} /> Inscrito</> : '+ Inscrever'}
              </button>
            </div>
          </div>
        </button>
      );
    })}
  </div>
);

// --- Variation C: compact list ---
const AgendaList = ({ events, subscribed, onToggle, onOpen }) => (
  <div style={{ padding: '4px 20px 24px' }}>
    {events.map((ev, i) => {
      const sub = subscribed.has(ev.id);
      const c = trackColor(ev.tag);
      return (
        <button key={ev.id} onClick={() => onOpen(ev)} style={{
          width: '100%', display: 'flex', gap: 14, alignItems: 'stretch',
          background: 'none', border: 'none', borderTop: i === 0 ? 'none' : '1px solid var(--line)',
          padding: '14px 0', textAlign: 'left', color: '#fff', font: 'inherit', cursor: 'pointer',
        }}>
          <div style={{ width: 48, flexShrink: 0 }}>
            <div className="mono" style={{ fontSize: 14, fontWeight: 600 }}>{ev.time}</div>
            <div className="mono" style={{ fontSize: 10, color: 'var(--text-mute)', marginTop: 2 }}>{ev.duration}</div>
          </div>
          <div style={{ width: 3, background: c.fg, borderRadius: 2, flexShrink: 0 }} />
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ display: 'flex', gap: 6, marginBottom: 4 }}>
              <span className="mono" style={{ fontSize: 9, color: c.fg, letterSpacing: '0.1em', textTransform: 'uppercase', fontWeight: 600 }}>{ev.track}</span>
            </div>
            <div style={{ fontSize: 14, fontWeight: 600, lineHeight: 1.3, marginBottom: 4 }}>{ev.title}</div>
            <div style={{ fontSize: 11, color: 'var(--text-mute)', display: 'flex', gap: 8 }}>
              <span>{ev.speaker}</span><span>·</span><span>{ev.room}</span>
            </div>
          </div>
          <button onClick={(e) => { e.stopPropagation(); onToggle(ev.id); }} style={{
            width: 32, height: 32, borderRadius: '50%', flexShrink: 0, alignSelf: 'center',
            background: sub ? 'var(--amber)' : 'transparent',
            border: `1.5px solid ${sub ? 'var(--amber)' : 'var(--line-strong)'}`,
            color: sub ? '#05080F' : '#fff',
            cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>
            {sub ? <IconCheck size={14} stroke={2.6} /> : <IconPlus size={16} />}
          </button>
        </button>
      );
    })}
  </div>
);

const AgendaScreen = ({ layout, subscribed, onToggle, onOpen, onFull }) => {
  const [dayId, setDayId] = React.useState('d3');
  const [scope, setScope] = React.useState('all'); // 'all' | 'mine'
  const baseEvents = scope === 'mine' ? EVENTS.filter(e => subscribed.has(e.id)) : EVENTS;
  const dayEvents = baseEvents.filter(e => e.day === dayId).sort((a, b) => a.time.localeCompare(b.time));
  const mineCount = subscribed.size;
  const dayHasMine = (dId) => EVENTS.some(e => e.day === dId && subscribed.has(e.id));

  return (
    <div className="screen">
      <StatusBar />
      <div style={{ padding: '0 20px 12px', display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end' }}>
        <div>
          <div className="mono" style={{ fontSize: 10, letterSpacing: '0.18em', color: 'var(--text-mute)', marginBottom: 6 }}>FORMA TOUR · SEMANA</div>
          <h1 style={{ fontSize: 28, margin: 0, fontWeight: 600, letterSpacing: '-0.02em' }}>Agenda</h1>
        </div>
        <button onClick={onFull} className="btn btn-nav" title="Ver agenda completa">
          <IconGrid size={18} />
        </button>
      </div>

      {/* Scope toggle: all vs mine */}
      <div style={{ display: 'flex', gap: 6, padding: '0 20px 14px' }}>
        <button onClick={() => setScope('all')} style={{
          flex: 1, padding: '10px 12px', cursor: 'pointer', font: 'inherit',
          background: scope === 'all' ? 'rgba(255,255,255,0.08)' : 'transparent',
          border: `1px solid ${scope === 'all' ? 'var(--line-strong)' : 'var(--line)'}`,
          color: scope === 'all' ? '#fff' : 'var(--text-dim)',
          borderRadius: 12, fontSize: 13, fontWeight: 500,
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
        }}>
          Todos os eventos
        </button>
        <button onClick={() => setScope('mine')} style={{
          flex: 1, padding: '10px 12px', cursor: 'pointer', font: 'inherit',
          background: scope === 'mine' ? 'var(--amber)' : 'transparent',
          border: `1px solid ${scope === 'mine' ? 'var(--amber)' : 'var(--line)'}`,
          color: scope === 'mine' ? '#05080F' : 'var(--text-dim)',
          borderRadius: 12, fontSize: 13, fontWeight: 600,
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
        }}>
          <IconCheck size={14} stroke={2.6} /> Meu calendário
          <span style={{
            fontSize: 11, padding: '1px 7px', borderRadius: 999,
            background: scope === 'mine' ? 'rgba(5,8,15,0.18)' : 'rgba(245,166,35,0.18)',
            color: scope === 'mine' ? '#05080F' : 'var(--amber)', fontWeight: 700,
          }}>{mineCount}</span>
        </button>
      </div>

      {/* Day selector */}
      <div style={{ display: 'flex', gap: 8, overflowX: 'auto', padding: '4px 20px 18px', scrollbarWidth: 'none' }}>
        {EVENT_DAYS.map(d => {
          const active = d.id === dayId;
          const hasMine = dayHasMine(d.id);
          return (
            <button key={d.id} onClick={() => setDayId(d.id)} style={{
              background: active ? 'var(--amber)' : 'rgba(255,255,255,0.04)',
              border: `1px solid ${active ? 'var(--amber)' : 'var(--line)'}`,
              color: active ? '#05080F' : '#fff',
              borderRadius: 14, padding: '10px 14px', cursor: 'pointer',
              font: 'inherit', flexShrink: 0, minWidth: 62,
              display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 2, position: 'relative',
            }}>
              <span className="mono" style={{ fontSize: 10, opacity: 0.7, letterSpacing: '0.1em' }}>{d.label}</span>
              <span style={{ fontSize: 18, fontWeight: 700, letterSpacing: '-0.02em' }}>{d.date}</span>
              {hasMine && !active && <span style={{ width: 5, height: 5, borderRadius: '50%', background: 'var(--amber)', position: 'absolute', bottom: 6 }} />}
              {d.today && !hasMine && !active && <span style={{ width: 4, height: 4, borderRadius: '50%', background: 'var(--text-mute)', position: 'absolute', bottom: 6 }} />}
            </button>
          );
        })}
      </div>

      {scope === 'mine' && dayEvents.length === 0 && (
        <div style={{ padding: '40px 32px', textAlign: 'center', color: 'var(--text-mute)' }}>
          <IconCalendar size={36} stroke={1.4} />
          <div style={{ marginTop: 14, fontSize: 14, color: 'var(--text-dim)', lineHeight: 1.5 }}>
            {mineCount === 0
              ? 'Você ainda não se inscreveu em nenhum evento.\nToque em “Todos os eventos” para explorar.'
              : 'Nenhum evento seu neste dia.\nOs dias com ponto âmbar têm inscrições suas.'}
          </div>
        </div>
      )}

      {layout === 'timeline' && dayEvents.length > 0 && <AgendaTimeline events={dayEvents} subscribed={subscribed} onToggle={onToggle} onOpen={onOpen} />}
      {layout === 'cards' && dayEvents.length > 0 && <AgendaCards events={dayEvents} subscribed={subscribed} onToggle={onToggle} onOpen={onOpen} />}
      {layout === 'list' && dayEvents.length > 0 && <AgendaList events={dayEvents} subscribed={subscribed} onToggle={onToggle} onOpen={onOpen} />}
    </div>
  );
};

const FullAgendaScreen = ({ subscribed, onToggle, onOpen, onBack }) => {
  const [filter, setFilter] = React.useState('all');
  const tracks = ['all', 'Keynote', 'Workshop', 'Talk', 'Feira', 'Tour'];
  const filtered = filter === 'all' ? EVENTS : EVENTS.filter(e => e.track === filter);

  const byDay = EVENT_DAYS.map(d => ({
    day: d,
    events: filtered.filter(e => e.day === d.id).sort((a, b) => a.time.localeCompare(b.time)),
  })).filter(g => g.events.length > 0);

  return (
    <div className="screen">
      <StatusBar />
      <ScreenHeader title="Agenda completa" onBack={onBack} />
      <div className="h-scroll" style={{ paddingBottom: 18 }}>
        {tracks.map(t => (
          <button key={t} onClick={() => setFilter(t)} className={'chip' + (filter === t ? ' active' : '')}>
            {t === 'all' ? 'Todos' : t}
          </button>
        ))}
      </div>

      <div style={{ padding: '0 20px 24px' }}>
        {byDay.map(({ day, events }) => (
          <div key={day.id} style={{ marginBottom: 24 }}>
            <div style={{
              display: 'flex', alignItems: 'baseline', gap: 10, marginBottom: 12,
              paddingBottom: 8, borderBottom: '1px solid var(--line)',
            }}>
              <h3 style={{ fontSize: 18, margin: 0, fontWeight: 600, letterSpacing: '-0.01em' }}>{day.weekday}</h3>
              <span className="mono" style={{ fontSize: 11, color: 'var(--text-mute)' }}>{day.fullDate}</span>
              {day.today && <span className="chip amber" style={{ padding: '2px 8px', fontSize: 10, marginLeft: 'auto' }}>hoje</span>}
            </div>
            {events.map(ev => {
              const sub = subscribed.has(ev.id);
              const c = trackColor(ev.tag);
              return (
                <button key={ev.id} onClick={() => onOpen(ev)} style={{
                  width: '100%', display: 'flex', gap: 12, padding: '12px 0',
                  background: 'none', border: 'none', textAlign: 'left',
                  color: '#fff', font: 'inherit', cursor: 'pointer',
                  borderBottom: '1px dashed var(--line)',
                }}>
                  <div className="mono" style={{ width: 40, fontSize: 12, fontWeight: 600, paddingTop: 2 }}>{ev.time}</div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 4, lineHeight: 1.3 }}>{ev.title}</div>
                    <div style={{ fontSize: 11, color: c.fg, fontFamily: "'Geist Mono', monospace", letterSpacing: '0.08em', textTransform: 'uppercase' }}>{ev.track} · {ev.room}</div>
                  </div>
                  {sub && <div style={{
                    width: 22, height: 22, borderRadius: '50%', background: 'var(--amber)',
                    color: '#05080F', display: 'flex', alignItems: 'center', justifyContent: 'center',
                    flexShrink: 0, alignSelf: 'center',
                  }}><IconCheck size={12} stroke={2.6} /></div>}
                </button>
              );
            })}
          </div>
        ))}
      </div>
    </div>
  );
};

const EventDetailScreen = ({ event, subscribed, onToggle, onBack, onOpenRoom }) => {
  const sub = subscribed.has(event.id);
  return (
    <div className="screen">
      <div style={{ position: 'relative' }}>
        <Placeholder gradient={event.gradient} height={280} label={event.track.toLowerCase()} />
        <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(180deg, rgba(5,8,15,0.5) 0%, transparent 30%, rgba(5,8,15,0.9) 100%)' }} />
        <div style={{ position: 'absolute', top: 0, left: 0, right: 0 }}>
          <StatusBar />
          <div style={{ padding: '8px 20px', display: 'flex', justifyContent: 'space-between' }}>
            <button className="btn btn-nav" onClick={onBack} style={{ background: 'rgba(5,8,15,0.5)', backdropFilter: 'blur(10px)' }}><IconChevronLeft size={18} /></button>
            <button className="btn btn-nav" style={{ background: 'rgba(5,8,15,0.5)', backdropFilter: 'blur(10px)' }}><IconShare size={16} /></button>
          </div>
        </div>
        <div style={{ position: 'absolute', bottom: 16, left: 20, right: 20 }}>
          <TrackBadge track={event.track} tag={event.tag} />
        </div>
      </div>

      <div style={{ padding: '16px 20px 100px' }}>
        <h2 style={{ fontSize: 24, margin: '0 0 12px', fontWeight: 600, lineHeight: 1.15, letterSpacing: '-0.02em' }}>{event.title}</h2>

        <div style={{ display: 'flex', gap: 16, flexWrap: 'wrap', marginBottom: 20, color: 'var(--text-dim)', fontSize: 13 }}>
          <span style={{ display: 'flex', alignItems: 'center', gap: 6 }}><IconClock size={14} /> {event.time} · {event.duration}</span>
          <span style={{ display: 'flex', alignItems: 'center', gap: 6 }}><IconMapPin size={14} /> {event.room}</span>
        </div>

        {/* Speaker */}
        <div className="card" style={{ padding: 14, display: 'flex', alignItems: 'center', gap: 12, marginBottom: 20 }}>
          <Avatar user={{ avatar: event.speaker.split(' ').map(w => w[0]).slice(0, 2).join(''), color: trackColor(event.tag).fg }} size={44} />
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 14, fontWeight: 600 }}>{event.speaker}</div>
            <div style={{ fontSize: 12, color: 'var(--text-mute)' }}>{event.role}</div>
          </div>
        </div>

        <p style={{ fontSize: 15, lineHeight: 1.55, color: 'var(--text-dim)', margin: '0 0 24px' }}>{event.summary}</p>

        {event.agenda.length > 0 && (
          <>
            <div className="mono" style={{ fontSize: 10, letterSpacing: '0.14em', color: 'var(--text-mute)', marginBottom: 10 }}>O QUE VEREMOS</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginBottom: 24 }}>
              {event.agenda.map((item, i) => (
                <div key={i} style={{ display: 'flex', gap: 10, fontSize: 14, color: 'var(--text-dim)' }}>
                  <span className="mono" style={{ color: 'var(--amber)', fontWeight: 600, width: 22, flexShrink: 0 }}>0{i + 1}</span>
                  <span>{item}</span>
                </div>
              ))}
            </div>
          </>
        )}

        {sub && (
          <button onClick={onOpenRoom} className="card" style={{
            width: '100%', textAlign: 'left', padding: 14, marginBottom: 24,
            cursor: 'pointer', font: 'inherit', color: '#fff',
            display: 'flex', alignItems: 'center', gap: 12,
            border: '1px solid rgba(245,166,35,0.25)',
            background: 'rgba(245,166,35,0.05)',
          }}>
            <div style={{
              width: 42, height: 42, borderRadius: 12, flexShrink: 0,
              background: 'rgba(245,166,35,0.14)', color: 'var(--amber)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}><IconMessage size={18} stroke={2} /></div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 2 }}>Sala de chat do evento</div>
              <div style={{ fontSize: 12, color: 'var(--text-dim)', lineHeight: 1.4 }}>
                Converse com quem também vai estar lá. Apenas inscritos.
              </div>
            </div>
            <IconChevronRight size={18} style={{ color: 'var(--text-mute)' }} />
          </button>
        )}

        {/* Sticky CTA */}
      </div>
      <div style={{
        position: 'absolute', left: 0, right: 0, bottom: 0,
        padding: '14px 20px 20px',
        background: 'linear-gradient(180deg, transparent, rgba(5,8,15,0.9) 30%, #05080F)',
      }}>
        <button onClick={() => onToggle(event.id)} className={sub ? 'btn btn-ghost' : 'btn btn-primary'} style={{ width: '100%' }}>
          {sub ? <><IconCheck size={18} stroke={2.2} /> Inscrito · toque para cancelar</> : <>Inscrever-se <IconArrowRight size={18} /></>}
        </button>
      </div>
    </div>
  );
};

Object.assign(window, { AgendaScreen, FullAgendaScreen, EventDetailScreen });
