const { useState: useDashSt, useContext: useDashCtx } = React;

/* ── Card dimensions (fixed per row type) ───────────────────────── */
const MODULE_CARD  = { w: 148, h: 222 };
const LESSON_CARD  = { w: 256, h: 144 };

/* ── Poster SVG backgrounds ─────────────────────────────────────── */
const posterBgs = [
  `<svg xmlns="http://www.w3.org/2000/svg" width="160" height="240" viewBox="0 0 160 240">
    <rect width="160" height="240" fill="#0d0b07"/>
    <rect width="160" height="240" fill="url(#g1)"/>
    <defs><radialGradient id="g1" cx="50%" cy="40%" r="65%"><stop offset="0%" stop-color="#C9A800" stop-opacity="0.18"/><stop offset="100%" stop-color="#0d0b07" stop-opacity="0"/></radialGradient></defs>
    <polygon points="80,40 108,80 80,120 52,80" fill="none" stroke="#C9A800" stroke-opacity="0.35" stroke-width="0.8"/>
    <polygon points="80,60 100,88 80,116 60,88" fill="none" stroke="#C9A800" stroke-opacity="0.18" stroke-width="0.6"/>
    <line x1="80" y1="40" x2="80" y2="200" stroke="#C9A800" stroke-opacity="0.1" stroke-width="0.5"/>
    <line x1="20" y1="80" x2="140" y2="80" stroke="#C9A800" stroke-opacity="0.1" stroke-width="0.5"/>
  </svg>`,
  `<svg xmlns="http://www.w3.org/2000/svg" width="160" height="240" viewBox="0 0 160 240">
    <rect width="160" height="240" fill="#0a0900"/>
    <rect width="160" height="240" fill="url(#g2)"/>
    <defs><radialGradient id="g2" cx="50%" cy="45%" r="60%"><stop offset="0%" stop-color="#C9A800" stop-opacity="0.22"/><stop offset="100%" stop-color="#0a0900" stop-opacity="0"/></radialGradient></defs>
    <circle cx="80" cy="100" r="22" fill="none" stroke="#C9A800" stroke-opacity="0.4" stroke-width="0.8"/>
    <circle cx="80" cy="100" r="42" fill="none" stroke="#C9A800" stroke-opacity="0.22" stroke-width="0.7"/>
    <circle cx="80" cy="100" r="62" fill="none" stroke="#C9A800" stroke-opacity="0.12" stroke-width="0.6"/>
    <circle cx="80" cy="100" r="82" fill="none" stroke="#C9A800" stroke-opacity="0.06" stroke-width="0.5"/>
  </svg>`,
  `<svg xmlns="http://www.w3.org/2000/svg" width="160" height="240" viewBox="0 0 160 240">
    <rect width="160" height="240" fill="#0c0b08"/>
    <rect width="160" height="240" fill="url(#g3)"/>
    <defs><radialGradient id="g3" cx="30%" cy="55%" r="65%"><stop offset="0%" stop-color="#C9A800" stop-opacity="0.2"/><stop offset="100%" stop-color="#0c0b08" stop-opacity="0"/></radialGradient></defs>
    <line x1="40" y1="0" x2="40" y2="240" stroke="#C9A800" stroke-opacity="0.1" stroke-width="0.5"/>
    <line x1="80" y1="0" x2="80" y2="240" stroke="#C9A800" stroke-opacity="0.1" stroke-width="0.5"/>
    <line x1="120" y1="0" x2="120" y2="240" stroke="#C9A800" stroke-opacity="0.1" stroke-width="0.5"/>
    <line x1="0" y1="60" x2="160" y2="60" stroke="#C9A800" stroke-opacity="0.1" stroke-width="0.5"/>
    <line x1="0" y1="120" x2="160" y2="120" stroke="#C9A800" stroke-opacity="0.1" stroke-width="0.5"/>
    <line x1="0" y1="180" x2="160" y2="180" stroke="#C9A800" stroke-opacity="0.1" stroke-width="0.5"/>
    <rect x="58" y="78" width="44" height="44" fill="none" stroke="#C9A800" stroke-opacity="0.35" stroke-width="0.8" rx="2"/>
  </svg>`,
  `<svg xmlns="http://www.w3.org/2000/svg" width="160" height="240" viewBox="0 0 160 240">
    <rect width="160" height="240" fill="#0b0901"/>
    <rect width="160" height="240" fill="url(#g4)"/>
    <defs><radialGradient id="g4" cx="70%" cy="35%" r="60%"><stop offset="0%" stop-color="#C9A800" stop-opacity="0.2"/><stop offset="100%" stop-color="#0b0901" stop-opacity="0"/></radialGradient></defs>
    <line x1="0" y1="60" x2="160" y2="220" stroke="#C9A800" stroke-opacity="0.08" stroke-width="0.5"/>
    <line x1="0" y1="30" x2="160" y2="190" stroke="#C9A800" stroke-opacity="0.08" stroke-width="0.5"/>
    <line x1="0" y1="90" x2="160" y2="250" stroke="#C9A800" stroke-opacity="0.08" stroke-width="0.5"/>
    <polygon points="80,52 112,110 48,110" fill="none" stroke="#C9A800" stroke-opacity="0.4" stroke-width="0.8"/>
  </svg>`,
  `<svg xmlns="http://www.w3.org/2000/svg" width="160" height="240" viewBox="0 0 160 240">
    <rect width="160" height="240" fill="#0c0a00"/>
    <rect width="160" height="240" fill="url(#g5)"/>
    <defs><radialGradient id="g5" cx="50%" cy="42%" r="62%"><stop offset="0%" stop-color="#C9A800" stop-opacity="0.25"/><stop offset="100%" stop-color="#0c0a00" stop-opacity="0"/></radialGradient></defs>
    <polygon points="80,50 106,65 106,95 80,110 54,95 54,65" fill="none" stroke="#C9A800" stroke-opacity="0.45" stroke-width="0.9"/>
    <polygon points="80,60 100,71 100,93 80,104 60,93 60,71" fill="none" stroke="#C9A800" stroke-opacity="0.2" stroke-width="0.6"/>
    <circle cx="80" cy="80" r="6" fill="#C9A800" fill-opacity="0.3"/>
  </svg>`,
];

const svgUrl = idx =>
  `data:image/svg+xml;charset=utf-8,${encodeURIComponent(posterBgs[idx % posterBgs.length])}`;

/* ── MODULE CARD (always poster shape) ──────────────────────────── */
const ModuleCard = ({ mod, modIdx, isSelected, completedLessons, onSelect }) => {
  const [hov, setHov] = useDashSt(false);
  const { w, h } = MODULE_CARD;
  const done  = mod.lessons.filter(l => completedLessons.has(l.id)).length;
  const pct   = Math.round((done / mod.lessons.length) * 100);
  const allDone = pct === 100;

  return (
    <div
      onClick={onSelect}
      onMouseEnter={() => setHov(true)}
      onMouseLeave={() => setHov(false)}
      style={{
        position: 'relative', flexShrink: 0,
        width: w, height: h, borderRadius: 10, overflow: 'hidden', cursor: 'pointer',
        border: `1.5px solid ${isSelected ? 'var(--gold)' : hov ? 'var(--border-h)' : 'var(--border)'}`,
        transform: hov && !isSelected ? 'scale(1.04)' : 'scale(1)',
        transition: 'transform 0.22s ease, border-color 0.18s',
        boxShadow: isSelected ? '0 0 0 1px var(--gold), 0 6px 24px rgba(0,0,0,0.5)'
                  : hov ? '0 8px 28px rgba(0,0,0,0.45)' : 'none',
      }}
    >
      <div style={{
        position: 'absolute', inset: 0,
        backgroundImage: `url("${svgUrl(modIdx)}")`,
        backgroundSize: 'cover', backgroundPosition: 'center',
      }} />
      <div style={{
        position: 'absolute', bottom: 0, left: 0, right: 0, height: '65%',
        background: 'linear-gradient(to top, rgba(0,0,0,0.95) 0%, rgba(0,0,0,0.5) 60%, transparent 100%)',
      }}/>

      {/* Module badge */}
      <div style={{
        position: 'absolute', top: 10, left: 10,
        background: 'rgba(0,0,0,0.6)', backdropFilter: 'blur(6px)',
        borderRadius: 5, padding: '3px 8px',
        fontSize: 9, fontWeight: 700, color: 'var(--gold)',
        letterSpacing: '0.1em', border: '1px solid rgba(201,168,0,0.22)',
      }}>
        M{mod.id}
      </div>

      {allDone && (
        <div style={{
          position: 'absolute', top: 10, right: 10,
          width: 20, height: 20, borderRadius: '50%',
          background: 'var(--gold)', display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <IconCheck size={10} color="#0A0A0A"/>
        </div>
      )}

      {/* Selected underline */}
      {isSelected && (
        <div style={{ position: 'absolute', bottom: 0, left: 0, right: 0, height: 3, background: 'var(--gold)' }}/>
      )}

      <div style={{ position: 'absolute', bottom: 0, left: 0, right: 0, padding: '0 11px 14px' }}>
        <p style={{
          fontSize: 12.5, fontWeight: 600, color: '#EFE9D8', lineHeight: 1.3, marginBottom: 4,
          display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden',
        }}>
          {mod.title}
        </p>
        <p style={{ fontSize: 10, color: 'rgba(201,168,0,0.80)', fontWeight: 500 }}>
          {allDone ? '✓ Concluído' : `${done} de ${mod.lessons.length} aulas`}
        </p>
      </div>
    </div>
  );
};

/* ── LESSON CARD (always wide shape) ────────────────────────────── */
const LessonCard = ({ lesson, modIdx, isCompleted, isCurrent, onClick }) => {
  const [hov, setHov] = useDashSt(false);
  const { w, h } = LESSON_CARD;

  return (
    <div
      onClick={onClick}
      onMouseEnter={() => setHov(true)}
      onMouseLeave={() => setHov(false)}
      style={{
        position: 'relative', flexShrink: 0,
        width: w, height: h, borderRadius: 8, overflow: 'hidden', cursor: 'pointer',
        border: `1px solid ${isCurrent ? 'var(--gold)' : hov ? 'var(--border-h)' : 'var(--border)'}`,
        transform: hov ? 'scale(1.03)' : 'scale(1)',
        transition: 'transform 0.2s ease, border-color 0.15s',
        boxShadow: hov ? '0 6px 22px rgba(0,0,0,0.45)' : 'none',
      }}
    >
      <div style={{
        position: 'absolute', inset: 0,
        backgroundImage: `url("${svgUrl(modIdx)}")`,
        backgroundSize: 'cover', backgroundPosition: 'center',
      }} />
      <div style={{
        position: 'absolute', bottom: 0, left: 0, right: 0, height: '62%',
        background: 'linear-gradient(to top, rgba(0,0,0,0.92) 0%, rgba(0,0,0,0.35) 65%, transparent 100%)',
      }}/>

      {isCompleted && (
        <div style={{
          position: 'absolute', top: 8, right: 8,
          width: 18, height: 18, borderRadius: '50%',
          background: 'var(--gold)', display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <IconCheck size={9} color="#0A0A0A"/>
        </div>
      )}
      {isCurrent && (
        <div style={{
          position: 'absolute', top: 8, left: 8,
          background: 'var(--gold)', borderRadius: 4, padding: '2px 6px',
          fontSize: 8, fontWeight: 700, color: '#0A0A0A', letterSpacing: '0.08em',
        }}>
          ATUAL
        </div>
      )}

      {hov && (
        <div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <div style={{
            width: 36, height: 36, borderRadius: '50%',
            background: 'rgba(201,168,0,0.88)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>
            <IconPlay size={14} color="#0A0A0A"/>
          </div>
        </div>
      )}

      <div style={{ position: 'absolute', bottom: 0, left: 0, right: 0, padding: '0 10px 9px' }}>
        <p style={{
          fontSize: 12, fontWeight: 600, color: '#EFE9D8', lineHeight: 1.3, marginBottom: 2,
          overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
        }}>
          {lesson.title}
        </p>
        <p style={{ fontSize: 10, color: 'rgba(201,168,0,0.75)' }}>{lesson.duration}</p>
      </div>
    </div>
  );
};

/* ── DASHBOARD ──────────────────────────────────────────────────── */
const Dashboard = ({ completedLessons, onEnterLesson, onViewCertificate }) => {
  const { user }   = useDashCtx(UserCtx);
  const studentName = user?.name || COURSE.student;
  const firstName   = studentName.split(' ')[0];
  const pct        = Math.round((completedLessons.size / COURSE.totalLessons) * 100);
  const nextLesson = COURSE.allLessons.find(l => !completedLessons.has(l.id));

  const [selectedModId, setSelectedModId] = useDashSt(
    () => nextLesson ? nextLesson.moduleId : COURSE.modules[0].id
  );
  const [animKey, setAnimKey] = useDashSt(0);

  const selectedMod = COURSE.modules.find(m => m.id === selectedModId);

  const handleSelectMod = id => {
    if (id === selectedModId) return;
    setSelectedModId(id);
    setAnimKey(k => k + 1);
  };

  const stats = [
    { label: 'Progresso geral',  value: `${pct}%`,              sub: `${completedLessons.size} de ${COURSE.totalLessons} aulas` },
    { label: 'Aulas concluídas', value: completedLessons.size,   sub: `de ${COURSE.totalLessons} no total` },
  ];

  return (
    <div style={{ paddingTop: 44, paddingBottom: 64 }}>

      {/* WELCOME */}
      <div style={{ maxWidth: 1080, margin: '0 auto', padding: '0 32px 36px' }}>
        <p style={{ fontSize: 12, color: 'var(--gold)', letterSpacing: '0.12em', textTransform: 'uppercase', marginBottom: 8 }}>
          Bem-vinda de volta
        </p>
        <h1 style={{ fontSize: 30, fontWeight: 600, color: 'var(--text)', lineHeight: 1.15, marginBottom: 6 }}>
          {firstName}
        </h1>
        <p style={{ fontSize: 14, color: 'var(--text2)' }}>
          Continue de onde parou — você está indo muito bem.
        </p>
      </div>

      {/* STATS + CONTINUE */}
      <div style={{ maxWidth: 1080, margin: '0 auto', padding: '0 32px', display: 'flex', gap: 14, marginBottom: 44 }}>
        {stats.map(s => (
          <div key={s.label} style={{
            background: 'var(--card)', border: '1px solid var(--border)',
            borderRadius: 12, padding: '20px 26px', flex: '0 0 auto',
          }}>
            <p style={{ fontSize: 11, color: 'var(--text2)', textTransform: 'uppercase', letterSpacing: '0.1em', marginBottom: 10 }}>
              {s.label}
            </p>
            <p style={{ fontSize: 30, fontWeight: 700, color: 'var(--gold)', lineHeight: 1 }}>{s.value}</p>
            <p style={{ fontSize: 11, color: 'var(--text3)', marginTop: 4 }}>{s.sub}</p>
          </div>
        ))}

        {nextLesson && (
          <div style={{
            flex: 1, background: 'var(--card)', border: '1px solid var(--border-h)',
            borderRadius: 12, padding: '18px 22px',
            display: 'flex', alignItems: 'center', gap: 16,
          }}>
            <div style={{
              width: 42, height: 42, borderRadius: 10, background: 'var(--gold)',
              display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
            }}>
              <IconPlay size={17} color="#0A0A0A"/>
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <p style={{ fontSize: 10, color: 'var(--text2)', textTransform: 'uppercase', letterSpacing: '0.12em', marginBottom: 3 }}>
                Continuar aprendendo
              </p>
              <p style={{ fontSize: 14, fontWeight: 600, color: 'var(--text)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                {nextLesson.title}
              </p>
              <p style={{ fontSize: 11, color: 'var(--text2)' }}>
                Módulo {nextLesson.moduleId} · {nextLesson.duration}
              </p>
            </div>
            <button onClick={() => onEnterLesson(nextLesson)} style={{
              background: 'var(--gold)', borderRadius: 7,
              padding: '9px 18px', fontSize: 12, fontWeight: 600,
              color: '#0A0A0A', flexShrink: 0,
            }}>
              Assistir
            </button>
          </div>
        )}
      </div>

      {/* ── ROW 1: MODULES (poster cards) ── */}
      <div style={{ marginBottom: 6 }}>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, padding: '0 32px', marginBottom: 14 }}>
          <h2 style={{ fontSize: 17, fontWeight: 600, color: 'var(--text)' }}>Módulos</h2>
          <span style={{ fontSize: 11, color: 'var(--text2)' }}>{COURSE.modules.length} módulos</span>
        </div>
        <div style={{
          display: 'flex', gap: 12, overflowX: 'auto',
          padding: '4px 32px 14px', scrollbarWidth: 'none',
        }}>
          {COURSE.modules.map((mod, idx) => (
            <ModuleCard
              key={mod.id}
              mod={mod}
              modIdx={idx}
              isSelected={mod.id === selectedModId}
              completedLessons={completedLessons}
              onSelect={() => handleSelectMod(mod.id)}
            />
          ))}
        </div>
      </div>

      {/* ── ROW 2: LESSONS of selected module (wide cards) ── */}
      {selectedMod && (
        <div key={animKey} style={{
          marginBottom: 44,
          animation: 'fadeSlideIn 0.28s ease',
        }}>
          <style>{`
            @keyframes fadeSlideIn {
              from { opacity: 0; transform: translateY(10px); }
              to   { opacity: 1; transform: translateY(0); }
            }
          `}</style>

          {/* Arrow connector */}
          <div style={{
            display: 'flex', alignItems: 'center', gap: 10, padding: '0 32px', marginBottom: 14,
          }}>
            <div style={{
              width: 0, height: 0,
              borderLeft: '7px solid transparent',
              borderRight: '7px solid transparent',
              borderBottom: '7px solid var(--gold)',
              opacity: 0.7, flexShrink: 0,
              marginLeft: (selectedModId - 1) * (MODULE_CARD.w + 12) + MODULE_CARD.w / 2 - 39,
            }}/>
          </div>

          <div style={{
            background: 'var(--bg2)', borderTop: '1px solid var(--border)',
            borderBottom: '1px solid var(--border)', padding: '18px 0',
          }}>
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, padding: '0 32px', marginBottom: 14 }}>
              <span style={{ fontSize: 10, fontWeight: 600, color: 'var(--gold)', textTransform: 'uppercase', letterSpacing: '0.12em' }}>
                Módulo {selectedMod.id}
              </span>
              <h3 style={{ fontSize: 15, fontWeight: 600, color: 'var(--text)' }}>
                {selectedMod.title}
              </h3>
            </div>
            <div style={{
              display: 'flex', gap: 12, overflowX: 'auto',
              padding: '2px 32px 8px', scrollbarWidth: 'none',
            }}>
              {selectedMod.lessons.map((l, lIdx) => (
                <LessonCard
                  key={l.id}
                  lesson={l}
                  modIdx={COURSE.modules.findIndex(m => m.id === selectedModId)}
                  isCompleted={completedLessons.has(l.id)}
                  isCurrent={nextLesson && l.id === nextLesson.id}
                  onClick={() => onEnterLesson({ ...l, moduleId: selectedMod.id, moduleTitle: selectedMod.title })}
                />
              ))}
            </div>
          </div>
        </div>
      )}

      {/* CERTIFICATE BANNER */}
      <div style={{ maxWidth: 1080, margin: '0 auto', padding: '0 32px' }}>
        {pct === 100 ? (
          <div style={{
            background: 'var(--gold-bg)', border: '1px solid var(--gold)',
            borderRadius: 14, padding: '22px 26px',
            display: 'flex', alignItems: 'center', gap: 18,
          }}>
            <IconAward size={30} color="var(--gold)"/>
            <div style={{ flex: 1 }}>
              <p style={{ fontSize: 14, fontWeight: 600, color: 'var(--gold)', marginBottom: 3 }}>Parabéns! Você concluiu o curso.</p>
              <p style={{ fontSize: 12, color: 'var(--text2)' }}>Seu certificado está pronto para download.</p>
            </div>
            <button onClick={onViewCertificate} style={{
              background: 'var(--gold)', borderRadius: 8,
              padding: '10px 18px', fontSize: 13, fontWeight: 600, color: '#0A0A0A',
            }}>
              Ver certificado
            </button>
          </div>
        ) : (
          <div style={{
            background: 'var(--card)', border: '1px solid var(--border)',
            borderRadius: 14, padding: '20px 26px',
            display: 'flex', alignItems: 'center', gap: 16, opacity: 0.5,
          }}>
            <IconAward size={26} color="var(--text3)"/>
            <div>
              <p style={{ fontSize: 14, fontWeight: 500, color: 'var(--text2)', marginBottom: 2 }}>Certificado de conclusão</p>
              <p style={{ fontSize: 12, color: 'var(--text3)' }}>
                Disponível após concluir todas as {COURSE.totalLessons} aulas · {pct}% concluído
              </p>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

window.Dashboard = Dashboard;
