const { useState: useSt, useContext: useCtx } = React;

/* ── Formata data ────────────────────────────────────────────────── */
const fmtDate = (dateStr, timeStr) => {
  const [y, m, d] = dateStr.split('-').map(Number);
  const months = ['Jan','Fev','Mar','Abr','Mai','Jun','Jul','Ago','Set','Out','Nov','Dez'];
  const days   = ['Dom','Seg','Ter','Qua','Qui','Sex','Sáb'];
  const dt = new Date(y, m - 1, d);
  return `${days[dt.getDay()]}, ${d} ${months[m-1]} ${y} · ${timeStr}h`;
};

/* ── Status badge ────────────────────────────────────────────────── */
const StatusBadge = ({ status }) => {
  const cfg = {
    live:     { label: '● AO VIVO',  bg: '#dc2626',           color: '#fff'     },
    upcoming: { label: '● EM BREVE', bg: 'rgba(201,168,0,0.9)',color: '#0A0A0A'  },
    recorded: { label: '▶ GRAVAÇÃO', bg: 'rgba(0,0,0,0.72)',   color: 'var(--gold)' },
  }[status] || { label: status, bg: 'var(--card)', color: 'var(--text)' };

  return (
    <span style={{
      padding: '4px 10px', borderRadius: 20, fontSize: 9.5,
      fontWeight: 800, letterSpacing: '0.1em',
      background: cfg.bg, color: cfg.color,
    }}>
      {cfg.label}
    </span>
  );
};

/* ── Modal de gravação ───────────────────────────────────────────── */
const VideoModal = ({ event, onClose }) => (
  <div
    onClick={onClose}
    style={{
      position: 'fixed', inset: 0, zIndex: 1000,
      background: 'rgba(0,0,0,0.88)', backdropFilter: 'blur(6px)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      padding: 24,
    }}
  >
    <div onClick={e => e.stopPropagation()} style={{ width: '100%', maxWidth: 860 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
        <h3 style={{ fontSize: 15, fontWeight: 600, color: '#fff' }}>{event.title}</h3>
        <button onClick={onClose} style={{
          background: 'rgba(255,255,255,0.1)', border: 'none', color: '#fff',
          width: 32, height: 32, borderRadius: '50%', fontSize: 16, cursor: 'pointer',
        }}>✕</button>
      </div>
      <div style={{ position: 'relative', aspectRatio: '16/9', borderRadius: 10, overflow: 'hidden', background: '#000' }}>
        {event.recordingUrl
          ? <iframe
              src={`${event.recordingUrl}?autoplay=1&rel=0`}
              style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', border: 'none' }}
              allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; fullscreen"
              allowFullScreen
            />
          : <div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <p style={{ color: 'rgba(255,255,255,0.4)', fontSize: 14 }}>Gravação em breve</p>
            </div>
        }
      </div>
    </div>
  </div>
);

/* ── LiveCard ────────────────────────────────────────────────────── */
const LiveCard = ({ event, onPlay }) => {
  const [hov, setHov] = useSt(false);
  const isRecorded = event.status === 'recorded';
  const isLive     = event.status === 'live';
  const hasAction  = isRecorded || event.liveUrl;

  const handleClick = () => {
    if (isRecorded) onPlay(event);
    else if (event.liveUrl) window.open(event.liveUrl, '_blank');
  };

  return (
    <div
      style={{
        background: 'var(--card)', border: `1px solid ${hov ? 'var(--border-h)' : 'var(--border)'}`,
        borderRadius: 14, overflow: 'hidden', display: 'flex', flexDirection: 'column',
        transition: 'border-color 0.2s, transform 0.2s, box-shadow 0.2s',
        transform: hov && hasAction ? 'translateY(-3px)' : 'none',
        boxShadow: hov && hasAction ? '0 12px 32px rgba(0,0,0,0.35)' : 'none',
        cursor: hasAction ? 'pointer' : 'default',
      }}
      onMouseEnter={() => setHov(true)}
      onMouseLeave={() => setHov(false)}
      onClick={hasAction ? handleClick : undefined}
    >
      {/* Thumbnail */}
      <div style={{
        position: 'relative', aspectRatio: '16/9', flexShrink: 0,
        background: 'linear-gradient(135deg, #1c1400 0%, #2d2000 35%, #0d1520 70%, #0a0a0a 100%)',
        overflow: 'hidden',
      }}>
        {event.thumbnail
          ? <img src={event.thumbnail} alt={event.title}
              style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }}/>
          : (
            <svg style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', opacity: 0.12 }}
              viewBox="0 0 400 225" preserveAspectRatio="xMidYMid slice">
              <circle cx="100" cy="112" r="90"  fill="none" stroke="var(--gold)" strokeWidth="1"/>
              <circle cx="300" cy="112" r="70"  fill="none" stroke="var(--gold)" strokeWidth="1"/>
              <circle cx="200" cy="20"  r="60"  fill="none" stroke="var(--gold)" strokeWidth="0.5"/>
            </svg>
          )
        }

        {/* Badge */}
        <div style={{ position: 'absolute', top: 10, left: 10 }}>
          <StatusBadge status={event.status}/>
        </div>

        {/* Duration badge (recorded) */}
        {isRecorded && event.duration && (
          <div style={{
            position: 'absolute', bottom: 8, right: 8,
            background: 'rgba(0,0,0,0.78)', borderRadius: 4,
            padding: '3px 7px', fontSize: 11, color: '#fff', fontWeight: 500,
          }}>
            {event.duration}
          </div>
        )}

        {/* Hover overlay */}
        {hasAction && hov && (
          <div style={{
            position: 'absolute', inset: 0,
            background: 'rgba(0,0,0,0.5)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>
            <div style={{
              width: 52, height: 52, borderRadius: '50%',
              background: isLive ? 'rgba(220,38,38,0.9)' : 'var(--gold)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>
              <svg width="18" height="18" viewBox="0 0 24 24" fill={isLive ? '#fff' : '#0A0A0A'}>
                <polygon points="5 3 19 12 5 21 5 3"/>
              </svg>
            </div>
          </div>
        )}
      </div>

      {/* Info */}
      <div style={{ padding: '14px 16px 18px', flex: 1, display: 'flex', flexDirection: 'column' }}>
        <p style={{ fontSize: 11, color: 'var(--gold)', fontWeight: 600, marginBottom: 6, letterSpacing: '0.03em' }}>
          {fmtDate(event.date, event.time)}
        </p>
        <h3 style={{
          fontSize: 15, fontWeight: 600, color: 'var(--text)', lineHeight: 1.35,
          marginBottom: 8, flex: 1,
        }}>
          {event.title}
        </h3>
        {event.desc && (
          <p style={{ fontSize: 12.5, color: 'var(--text2)', lineHeight: 1.65, marginBottom: 14 }}>
            {event.desc}
          </p>
        )}

        {/* CTA */}
        {isRecorded && (
          <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 12.5, fontWeight: 600, color: 'var(--gold)' }}>
            <svg width="13" height="13" viewBox="0 0 24 24" fill="currentColor"><polygon points="5 3 19 12 5 21 5 3"/></svg>
            Ver gravação
          </div>
        )}
        {!isRecorded && event.liveUrl && (
          <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 12.5, fontWeight: 600, color: isLive ? '#dc2626' : 'var(--gold)' }}>
            {isLive ? '● Entrar na aula ao vivo' : '→ Acessar transmissão'}
          </div>
        )}
        {!isRecorded && !event.liveUrl && (
          <p style={{ fontSize: 12, color: 'var(--text3)', fontStyle: 'italic' }}>
            Link disponível em breve
          </p>
        )}
      </div>
    </div>
  );
};

/* ── Section header ──────────────────────────────────────────────── */
const SectionTitle = ({ label, count }) => (
  <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 20 }}>
    <h2 style={{ fontSize: 16, fontWeight: 700, color: 'var(--text)' }}>{label}</h2>
    {count > 0 && (
      <span style={{
        background: 'var(--gold-bg)', border: '1px solid var(--border-h)',
        borderRadius: 20, padding: '1px 9px', fontSize: 11, fontWeight: 700, color: 'var(--gold)',
      }}>{count}</span>
    )}
    <div style={{ flex: 1, height: 1, background: 'var(--border)' }}/>
  </div>
);

/* ── LivePage ────────────────────────────────────────────────────── */
const LivePage = ({ onBack }) => {
  const { theme, toggleTheme } = useCtx(ThemeCtx);
  const isMob = typeof useIsMobile === 'function' ? useIsMobile() : false;
  const [modal, setModal] = useSt(null);

  const live     = LIVE_EVENTS.filter(e => e.status === 'live');
  const upcoming = LIVE_EVENTS.filter(e => e.status === 'upcoming');
  const recorded = LIVE_EVENTS.filter(e => e.status === 'recorded');

  /* Grid: 1 col no mobile, auto-fill no desktop */
  const gridStyle = {
    display: 'grid',
    gridTemplateColumns: isMob ? '1fr' : 'repeat(auto-fill, minmax(300px, 1fr))',
    gap: isMob ? 16 : 20,
  };

  return (
    <div style={{
      minHeight: '100vh', background: 'var(--bg)',
      paddingBottom: isMob ? 90 : 0,
    }}>

      {/* ── TOP BAR ── */}
      <div style={{
        height: isMob ? 'auto' : 58,
        background: isMob ? 'transparent' : 'var(--nav-bg)',
        backdropFilter: isMob ? 'none' : 'blur(18px)',
        borderBottom: isMob ? 'none' : '1px solid var(--border)',
        display: 'flex', alignItems: 'center',
        padding: isMob ? 'calc(env(safe-area-inset-top, 0px) + 12px) 16px 6px' : '0 24px',
        gap: 12,
        position: isMob ? 'relative' : 'sticky', top: 0, zIndex: 100,
      }}>
        <button onClick={onBack} style={{
          display: 'flex', alignItems: 'center', gap: 6, background: 'none',
          color: 'var(--text2)', padding: '6px 10px', borderRadius: 7, fontSize: 13,
        }}>
          <IconArrowLeft size={14}/> Voltar
        </button>

        {!isMob && (
          <>
            <div style={{ flex: 1 }}>
              <span style={{ fontSize: 12, fontWeight: 700, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--gold)' }}>
                Aulas ao Vivo
              </span>
            </div>

            <button onClick={toggleTheme} style={{
              width: 34, height: 34, borderRadius: '50%',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              background: 'var(--gold-bg)', border: '1px solid var(--border)', color: 'var(--gold)',
            }}>
              {theme === 'dark' ? <IconSun size={15}/> : <IconMoon size={15}/>}
            </button>
            <NotificationBell/>
            <UserMenu size={33}/>
          </>
        )}
      </div>

      {/* ── CONTEÚDO ── */}
      <div style={{
        maxWidth: 1100, margin: '0 auto',
        padding: isMob ? '12px 16px 40px' : '40px 24px 60px',
      }}>

        {/* Título mobile */}
        {isMob && (
          <h1 style={{
            fontSize: 22, fontWeight: 700, color: 'var(--text)',
            marginBottom: 6, letterSpacing: '-0.01em',
          }}>
            Aulas ao Vivo
          </h1>
        )}

        {/* AO VIVO AGORA */}
        {live.length > 0 && (
          <div style={{ marginBottom: 48 }}>
            <SectionTitle label="Acontecendo agora" count={live.length}/>
            <div style={gridStyle}>
              {live.map(e => <LiveCard key={e.id} event={e} onPlay={setModal}/>)}
            </div>
          </div>
        )}

        {/* PRÓXIMAS */}
        {upcoming.length > 0 && (
          <div style={{ marginBottom: 48 }}>
            <SectionTitle label="Próximas aulas" count={upcoming.length}/>
            <div style={gridStyle}>
              {upcoming.map(e => <LiveCard key={e.id} event={e} onPlay={setModal}/>)}
            </div>
          </div>
        )}

        {/* GRAVAÇÕES */}
        {recorded.length > 0 && (
          <div style={{ marginBottom: 48 }}>
            <SectionTitle label="Gravações" count={recorded.length}/>
            <div style={gridStyle}>
              {recorded.map(e => <LiveCard key={e.id} event={e} onPlay={setModal}/>)}
            </div>
          </div>
        )}

        {LIVE_EVENTS.length === 0 && (
          <div style={{ textAlign: 'center', padding: '80px 0', color: 'var(--text3)' }}>
            <p style={{ fontSize: 32, marginBottom: 12 }}>📡</p>
            <p style={{ fontSize: 15, fontWeight: 500 }}>Nenhuma aula ao vivo agendada ainda.</p>
          </div>
        )}
      </div>

      {/* Modal de gravação */}
      {modal && <VideoModal event={modal} onClose={() => setModal(null)}/>}
    </div>
  );
};

window.LivePage = LivePage;
