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

/* ── YouTube helpers ─────────────────────────────────────────────── */
const getYtId = (url) => {
  if (!url) return null;
  try { return url.split('/embed/')[1]?.split('?')[0] || null; }
  catch { return null; }
};
const getYtThumb = (url) => {
  const id = getYtId(url);
  return id ? `https://img.youtube.com/vi/${id}/mqdefault.jpg` : null;
};

/* ── Star Rating ─────────────────────────────────────────────────── */
const StarRating = ({ lessonId }) => {
  const key = `dc_rating_${lessonId}`;
  const [rating, setRating] = useSt(() => Number(localStorage.getItem(key)) || 0);
  const [hover, setHover] = useSt(0);

  const rate = (n) => {
    const next = n === rating ? 0 : n;
    setRating(next);
    localStorage.setItem(key, next);
  };

  return (
    <div style={{ display: 'flex', gap: 2, alignItems: 'center' }}>
      {[1, 2, 3, 4, 5].map(n => (
        <button
          key={n}
          onClick={() => rate(n)}
          onMouseEnter={() => setHover(n)}
          onMouseLeave={() => setHover(0)}
          style={{
            background: 'none', padding: '2px 3px', fontSize: 22, lineHeight: 1,
            color: n <= (hover || rating) ? 'var(--gold)' : 'var(--border-h)',
            transition: 'color 0.12s',
          }}
        >★</button>
      ))}
    </div>
  );
};

/* ── Icon: Prev / Next ───────────────────────────────────────────── */
const IconSkipBack = ({ size = 14 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor"
    strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ display: 'block' }}>
    <polygon points="19 20 9 12 19 4 19 20"/><line x1="5" y1="19" x2="5" y2="5"/>
  </svg>
);
const IconSkipFwd = ({ size = 14 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor"
    strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ display: 'block' }}>
    <polygon points="5 4 15 12 5 20 5 4"/><line x1="19" y1="5" x2="19" y2="19"/>
  </svg>
);
const IconSearch = () => (
  <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor"
    strokeWidth="2" strokeLinecap="round" style={{ display: 'block', flexShrink: 0 }}>
    <circle cx="11" cy="11" r="8"/><path d="m21 21-4.35-4.35"/>
  </svg>
);

/* ── Sidebar lesson row ──────────────────────────────────────────── */
const SidebarLesson = ({ lesson, modIdx, isActive, isCompleted, onClick }) => {
  const [hov, setHov] = useSt(false);
  const thumb = getYtThumb(lesson.video);

  const modColors = ['#1c1400', '#001a0d', '#00101a', '#0d0016', '#1a0800'];
  const bg = modColors[modIdx % modColors.length];

  return (
    <button
      onClick={onClick}
      onMouseEnter={() => setHov(true)}
      onMouseLeave={() => setHov(false)}
      style={{
        width: '100%', display: 'flex', alignItems: 'center', gap: 10,
        padding: '10px 14px',
        background: isActive ? 'var(--gold-bg)' : hov ? 'var(--card)' : 'none',
        borderLeft: `3px solid ${isActive ? 'var(--gold)' : 'transparent'}`,
        borderBottom: '1px solid var(--border)',
        textAlign: 'left', transition: 'background 0.15s',
      }}
    >
      {/* Thumbnail */}
      <div style={{
        width: 84, height: 48, borderRadius: 5, overflow: 'hidden',
        flexShrink: 0, position: 'relative', background: bg,
        border: `1px solid ${isActive ? 'var(--gold)' : 'var(--border)'}`,
      }}>
        {thumb
          ? <img src={thumb} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
          : (
            <div style={{
              position: 'absolute', inset: 0,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>
              <IconPlay size={14} color="rgba(201,168,0,0.35)"/>
            </div>
          )
        }

        {/* "Tocando agora" overlay */}
        {isActive && (
          <div style={{
            position: 'absolute', inset: 0, background: 'rgba(0,0,0,0.55)',
            display: 'flex', flexDirection: 'column',
            alignItems: 'center', justifyContent: 'center', gap: 3,
          }}>
            <IconPlay size={13} color="var(--gold)"/>
            <span style={{ fontSize: 8, color: 'var(--gold)', fontWeight: 700, letterSpacing: '0.06em' }}>
              Tocando agora
            </span>
          </div>
        )}

        {/* Duration badge */}
        {!isActive && (
          <div style={{
            position: 'absolute', bottom: 3, right: 3,
            background: 'rgba(0,0,0,0.78)', borderRadius: 3,
            padding: '1px 4px', fontSize: 9, color: '#fff', fontWeight: 500,
          }}>
            {lesson.duration}
          </div>
        )}
      </div>

      {/* Title */}
      <p style={{
        flex: 1, fontSize: 12.5, lineHeight: 1.4,
        color: isActive ? 'var(--gold)' : 'var(--text)',
        fontWeight: isActive ? 500 : 400,
        overflow: 'hidden',
        display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical',
      }}>
        {lesson.title}
      </p>

      {/* Completion indicator */}
      <div style={{
        width: 20, height: 20, borderRadius: '50%', flexShrink: 0,
        background: isCompleted ? 'var(--gold)' : 'transparent',
        border: `1.5px solid ${isCompleted ? 'var(--gold)' : 'var(--border-h)'}`,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
        {isCompleted && <IconCheck size={10} color="#0A0A0A"/>}
      </div>
    </button>
  );
};

/* ── Player ──────────────────────────────────────────────────────── */
const Player = ({ lesson, completedLessons, onToggleComplete, onSelectLesson, onViewCertificate, onBack }) => {
  const { theme, toggleTheme } = useCtx(ThemeCtx);
  const [search, setSearch] = useSt('');
  const [infoOpen, setInfoOpen] = useSt(true);
  const [expandedMods, setExpandedMods] = useSt(() => new Set([lesson.moduleId]));

  const toggleMod = (id) => setExpandedMods(prev => {
    const s = new Set(prev);
    s.has(id) ? s.delete(id) : s.add(id);
    return s;
  });

  const isCompleted = completedLessons.has(lesson.id);
  const pct = Math.round((completedLessons.size / COURSE.totalLessons) * 100);

  /* Prev / Next */
  const allLessons = COURSE.allLessons;
  const currentIdx = allLessons.findIndex(l => l.id === lesson.id);
  const prevLesson = currentIdx > 0 ? allLessons[currentIdx - 1] : null;
  const nextLesson = currentIdx < allLessons.length - 1 ? allLessons[currentIdx + 1] : null;

  /* Filtered sidebar modules */
  const filteredModules = search.trim()
    ? COURSE.modules
        .map(m => ({ ...m, lessons: m.lessons.filter(l => l.title.toLowerCase().includes(search.toLowerCase())) }))
        .filter(m => m.lessons.length > 0)
    : COURSE.modules;

  /* (avatar é renderizado pelo <UserMenu/>) */

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100vh', overflow: 'hidden', background: 'var(--bg)' }}>

      {/* ── TOP BAR ── */}
      <div style={{
        height: 52, flexShrink: 0,
        background: 'var(--nav-bg)', backdropFilter: 'blur(18px)',
        borderBottom: '1px solid var(--border)',
        display: 'flex', alignItems: 'center', padding: '0 18px', gap: 10,
      }}>
        {/* Voltar */}
        <button onClick={onBack} style={{
          display: 'flex', alignItems: 'center', gap: 6, flexShrink: 0,
          background: 'none', color: 'var(--text2)',
          padding: '6px 10px', borderRadius: 7, fontSize: 13,
        }}>
          <IconArrowLeft size={14}/> Voltar
        </button>

        <div style={{ width: 1, height: 20, background: 'var(--border)', flexShrink: 0 }}/>

        {/* Prev / Next */}
        {[
          { icon: <IconSkipBack size={13}/>, lesson: prevLesson, title: 'Aula anterior' },
          { icon: <IconSkipFwd size={13}/>,  lesson: nextLesson, title: 'Próxima aula' },
        ].map(({ icon, lesson: target, title }) => (
          <button
            key={title}
            onClick={() => target && onSelectLesson(target)}
            disabled={!target}
            title={title}
            style={{
              width: 30, height: 30, borderRadius: 6, flexShrink: 0,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              background: 'none', border: '1px solid var(--border)',
              color: target ? 'var(--text2)' : 'var(--text3)',
              opacity: target ? 1 : 0.35,
            }}
          >{icon}</button>
        ))}

        {/* Course title */}
        <span style={{
          flex: 1, fontSize: 12, fontWeight: 600, color: 'var(--text2)',
          letterSpacing: '0.05em', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
        }}>
          {COURSE.title}
        </span>

        {/* Progress + theme toggle + avatar */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexShrink: 0 }}>
          <span style={{ fontSize: 12, color: 'var(--text2)', fontWeight: 500 }}>{pct}%</span>
          <ProgressBar value={pct} style={{ width: 68 }}/>

          <button onClick={toggleTheme} style={{
            width: 32, height: 32, borderRadius: '50%', flexShrink: 0,
            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>

          <UserMenu size={32}/>
        </div>
      </div>

      {/* ── BODY ── */}
      <div style={{ flex: 1, display: 'flex', overflow: 'hidden' }}>

        {/* ── MAIN ── */}
        <div style={{ flex: 1, overflowY: 'auto', minWidth: 0, display: 'flex', flexDirection: 'column' }}>

          {/* Lesson heading */}
          <div style={{ padding: '20px 32px 12px' }}>
            <p style={{
              fontSize: 11, color: 'var(--gold)',
              textTransform: 'uppercase', letterSpacing: '0.12em', marginBottom: 5,
            }}>
              {lesson.moduleTitle}
            </p>
            <h1 style={{ fontSize: 22, fontWeight: 600, color: 'var(--text)', lineHeight: 1.2 }}>
              {lesson.title}
            </h1>
          </div>

          {/* VIDEO */}
          <div style={{ position: 'relative', aspectRatio: '16/9', width: '100%', background: '#000', flexShrink: 0 }}>
            {lesson.video ? (
              <iframe
                key={lesson.id}
                src={`${lesson.video}?rel=0&modestbranding=1&color=white`}
                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,
                background: 'linear-gradient(135deg, #0a0a0a 0%, #1c1400 45%, #0a0a0a 100%)',
                display: 'flex', flexDirection: 'column',
                alignItems: 'center', justifyContent: 'center', gap: 10,
              }}>
                <div style={{
                  position: 'absolute', inset: 0, opacity: 0.04,
                  backgroundImage: 'linear-gradient(var(--gold) 1px, transparent 1px), linear-gradient(90deg, var(--gold) 1px, transparent 1px)',
                  backgroundSize: '40px 40px',
                }}/>
                <div style={{
                  width: 52, height: 52, borderRadius: '50%', zIndex: 1,
                  background: 'rgba(201,168,0,0.12)', border: '1.5px solid rgba(201,168,0,0.25)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                }}>
                  <IconPlay size={20} color="rgba(201,168,0,0.45)"/>
                </div>
                <p style={{ fontSize: 12, color: 'rgba(201,168,0,0.4)', zIndex: 1, letterSpacing: '0.05em' }}>
                  Vídeo em breve
                </p>
              </div>
            )}
          </div>

          {/* RATING + CONCLUÍDA */}
          <div style={{
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            padding: '12px 32px', borderBottom: '1px solid var(--border)',
          }}>
            <StarRating lessonId={lesson.id}/>
            <button
              onClick={() => onToggleComplete(lesson.id)}
              style={{
                display: 'flex', alignItems: 'center', gap: 7,
                background: isCompleted ? 'var(--gold)' : 'var(--card)',
                border: `1px solid ${isCompleted ? 'var(--gold)' : 'var(--border)'}`,
                borderRadius: 8, padding: '9px 18px',
                fontSize: 13, fontWeight: 600,
                color: isCompleted ? '#0A0A0A' : 'var(--text2)',
                transition: 'all 0.2s',
              }}
            >
              <IconCheck size={13} color={isCompleted ? '#0A0A0A' : 'var(--text3)'}/>
              {isCompleted ? 'Concluída' : 'Marcar como concluída'}
            </button>
          </div>

          {/* INFORMAÇÕES DA AULA */}
          <div>
            <button
              onClick={() => setInfoOpen(o => !o)}
              style={{
                width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                padding: '14px 32px', background: 'none', borderBottom: '1px solid var(--border)',
                fontSize: 13, fontWeight: 500, color: 'var(--text)',
              }}
            >
              <span>Informações da aula</span>
              <IconChevron size={14} dir={infoOpen ? 'down' : 'right'}/>
            </button>

            {infoOpen && (
              <div style={{ padding: '0 32px 40px' }}>
                {/* Tabs */}
                <div style={{ display: 'flex', borderBottom: '1px solid var(--border)', marginBottom: 20, marginTop: 4 }}>
                  <div style={{
                    padding: '10px 0', fontSize: 13, fontWeight: 500,
                    color: 'var(--gold)', borderBottom: '2px solid var(--gold)', marginBottom: -1,
                  }}>
                    Descrição
                  </div>
                </div>

                <p style={{ fontSize: 13.5, color: 'var(--text2)', lineHeight: 1.75 }}>
                  {lesson.desc || 'Nenhuma descrição disponível para esta aula.'}
                </p>

                {/* Certificado */}
                {pct === 100 && (
                  <div style={{
                    marginTop: 28, background: 'var(--gold-bg)', border: '1px solid var(--gold)',
                    borderRadius: 10, padding: '14px 18px',
                    display: 'flex', alignItems: 'center', gap: 12,
                  }}>
                    <IconAward size={22} color="var(--gold)"/>
                    <div style={{ flex: 1 }}>
                      <p style={{ fontSize: 13, fontWeight: 600, color: 'var(--gold)', marginBottom: 2 }}>Curso concluído!</p>
                      <p style={{ fontSize: 12, color: 'var(--text2)' }}>Seu certificado está disponível para download.</p>
                    </div>
                    <button onClick={onViewCertificate} style={{
                      background: 'var(--gold)', borderRadius: 7,
                      padding: '8px 14px', fontSize: 12, fontWeight: 600, color: '#0A0A0A',
                    }}>
                      Ver certificado
                    </button>
                  </div>
                )}
              </div>
            )}
          </div>
        </div>

        {/* ── SIDEBAR ── */}
        <div style={{
          width: 340, flexShrink: 0,
          borderLeft: '1px solid var(--border)',
          background: 'var(--bg2)',
          display: 'flex', flexDirection: 'column',
          overflow: 'hidden',
        }}>

          {/* Search */}
          <div style={{ padding: '12px 14px', borderBottom: '1px solid var(--border)', flexShrink: 0 }}>
            <div style={{
              display: 'flex', alignItems: 'center', gap: 8,
              background: 'var(--card)', border: '1px solid var(--border)',
              borderRadius: 8, padding: '7px 12px', color: 'var(--text3)',
            }}>
              <IconSearch/>
              <input
                type="text"
                placeholder="Buscar conteúdo"
                value={search}
                onChange={e => setSearch(e.target.value)}
                style={{
                  flex: 1, background: 'none', border: 'none', outline: 'none',
                  fontSize: 12.5, color: 'var(--text)', fontFamily: 'inherit',
                }}
              />
              {search && (
                <button
                  onClick={() => setSearch('')}
                  style={{ background: 'none', color: 'var(--text3)', fontSize: 14, lineHeight: 1, padding: 0 }}
                >✕</button>
              )}
            </div>
          </div>

          {/* Trilha de conhecimento header */}
          <div style={{ padding: '12px 14px 8px', borderBottom: '1px solid var(--border)', flexShrink: 0 }}>
            <p style={{
              fontSize: 10, fontWeight: 700, textTransform: 'uppercase',
              letterSpacing: '0.1em', color: 'var(--text3)', marginBottom: 3,
            }}>
              Trilha de conhecimento
            </p>
            <p style={{ fontSize: 13.5, fontWeight: 600, color: 'var(--text)' }}>{COURSE.title}</p>
          </div>

          {/* Módulos e aulas */}
          <div style={{ flex: 1, overflowY: 'auto' }}>
            {filteredModules.map((mod) => {
              const realIdx = COURSE.modules.findIndex(m => m.id === mod.id);
              const done = mod.lessons.filter(l => completedLessons.has(l.id)).length;
              const modPct = Math.round((done / mod.lessons.length) * 100);

              return (
                <div key={mod.id}>
                  {/* Module header */}
                  <button
                    onClick={() => toggleMod(mod.id)}
                    style={{
                      width: '100%', textAlign: 'left',
                      padding: '11px 14px 10px',
                      borderBottom: '1px solid var(--border)',
                      borderTop: realIdx > 0 ? '1px solid var(--border)' : 'none',
                      background: 'var(--bg3)',
                    }}
                  >
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 5 }}>
                      <p style={{
                        fontSize: 10, color: 'var(--gold)', fontWeight: 700,
                        textTransform: 'uppercase', letterSpacing: '0.1em',
                      }}>
                        Módulo {mod.id}
                      </p>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                        <span style={{ fontSize: 10, color: 'var(--text3)' }}>{done}/{mod.lessons.length}</span>
                        <IconChevron size={12} dir={expandedMods.has(mod.id) ? 'down' : 'right'}/>
                      </div>
                    </div>
                    <p style={{ fontSize: 12.5, fontWeight: 500, color: 'var(--text)', marginBottom: 7, lineHeight: 1.3 }}>
                      {mod.title}
                    </p>
                    <ProgressBar value={modPct} height={2}/>
                  </button>

                  {/* Aulas */}
                  {expandedMods.has(mod.id) && mod.lessons.map(l => (
                    <SidebarLesson
                      key={l.id}
                      lesson={l}
                      modIdx={realIdx}
                      isActive={l.id === lesson.id}
                      isCompleted={completedLessons.has(l.id)}
                      onClick={() => onSelectLesson({ ...l, moduleId: mod.id, moduleTitle: mod.title })}
                    />
                  ))}
                </div>
              );
            })}

            {filteredModules.length === 0 && (
              <div style={{ padding: 32, textAlign: 'center', color: 'var(--text3)', fontSize: 13 }}>
                Nenhuma aula encontrada para "{search}"
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

window.Player = Player;
