// CourseMap.jsx — ruta del curso con bloqueo/desbloqueo. window.CourseMap
const { useState: useStateM } = React;

function notaStr(score, total) {
  if (score === null || score === undefined) return '—';
  return ((Math.round((score / total) * 100) / 10).toFixed(1)).replace('.', ',');
}

function StateDot({ kind }) {
  // kind: done | open | lock
  const map = {
    done: { bg: 'var(--success)', ch: '✓', col: '#fff' },
    open: { bg: 'var(--terracotta)', ch: '', col: '#fff' },
    lock: { bg: 'var(--bg-deep)', ch: '🔒', col: 'var(--ink-3)' },
  };
  const s = map[kind] || map.lock;
  return <span style={{ width: 22, height: 22, borderRadius: '50%', background: s.bg, color: s.col, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', font: '600 11px/1 var(--font-mono)', flexShrink: 0 }}>{s.ch}</span>;
}

function CourseMap({ onOpenProgress, user }) {
  const S = window.CourseStore;
  const units = S.units();
  const [open, setOpen] = useStateM(() => {
    // abrir la primera unidad no completada y desbloqueada
    const u = units.find(x => S.unitUnlocked(x.slug) && !S.unitCompleted(x.slug));
    return u ? u.slug : (units[0] && units[0].slug);
  });
  const [quiz, setQuiz] = useStateM(null);
  const [expl, setExpl] = useStateM(null);
  const [, setTick] = useStateM(0);
  const refresh = () => setTick(t => t + 1);

  const launchPartial = (unit, part) => setQuiz({ slug: unit.slug, partKey: part.n, bank: part.bank, n: S.PARTIAL.N, min: S.PARTIAL.MIN, title: part.title, subtitle: unit.ud + ' · Parte ' + part.n });
  const launchFinal = (unit) => setQuiz({ slug: unit.slug, partKey: 'final', bank: unit.finalBank, n: S.FINAL.N, min: S.FINAL.MIN, title: 'Cuestionario final', subtitle: unit.ud + ' · ' + unit.topic });

  const done = S.unitsCompletedCount();
  const pct = Math.round((done / units.length) * 100);

  return (
    <main style={{ maxWidth: 920, margin: '0 auto', padding: '28px var(--pad-page) 80px' }}>
      {/* encabezado de progreso */}
      <section style={{ marginBottom: 28, display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 16, flexWrap: 'wrap' }}>
        <div>
          <div style={{ font: 'var(--type-label)', letterSpacing: 'var(--tracking-label)', textTransform: 'uppercase', color: 'var(--ink-3)' }}>Curso · Matemáticas 4º ESO</div>
          <h1 style={{ font: 'var(--type-h1)', letterSpacing: 'var(--tracking-tight)', margin: '6px 0 0' }}>Hola, {user.display || user.name}</h1>
        </div>
        <button onClick={onOpenProgress} style={{ background: 'var(--bg-surface)', border: '1px solid var(--line)', borderRadius: 'var(--r-md)', padding: '10px 16px', font: 'var(--type-ui-sm)', color: 'var(--ink)', cursor: 'pointer' }}>Mi progreso →</button>
      </section>

      <div style={{ background: 'var(--bg-surface)', border: '1px solid var(--line)', borderRadius: 'var(--r-lg)', padding: '16px 20px', marginBottom: 28, display: 'flex', alignItems: 'center', gap: 16 }}>
        <div style={{ flex: 1 }}>
          <div style={{ height: 8, background: 'var(--bg-deep)', borderRadius: 999, overflow: 'hidden' }}>
            <div style={{ height: '100%', width: pct + '%', background: 'var(--forest)', transition: 'width var(--t-slow) var(--ease)' }} />
          </div>
        </div>
        <div style={{ font: 'var(--type-ui-sm)', color: 'var(--ink-2)', whiteSpace: 'nowrap' }}>{done} / {units.length} unidades</div>
      </div>

      {/* ruta de unidades */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
        {units.map((unit, idx) => {
          const unlocked = S.unitUnlocked(unit.slug);
          const completed = S.unitCompleted(unit.slug);
          const isOpen = open === unit.slug;
          const pr = S.getProgress()[unit.slug];
          return (
            <div key={unit.slug} style={{ background: 'var(--bg-surface)', border: '1px solid', borderColor: isOpen ? 'var(--line-strong)' : 'var(--line)', borderRadius: 'var(--r-lg)', overflow: 'hidden', opacity: unlocked ? 1 : 0.62 }}>
              {/* cabecera de unidad */}
              <button onClick={() => unlocked && setOpen(isOpen ? null : unit.slug)} style={{ width: '100%', display: 'flex', alignItems: 'center', gap: 14, padding: '16px 20px', background: 'transparent', border: 0, cursor: unlocked ? 'pointer' : 'default', textAlign: 'left' }}>
                <StateDot kind={completed ? 'done' : (unlocked ? 'open' : 'lock')} />
                <div style={{ flex: 1 }}>
                  <div style={{ font: 'var(--type-ui-sm)', color: 'var(--ink-3)' }}>{unit.ud}</div>
                  <div style={{ font: 'var(--type-h4)', color: 'var(--ink)' }}>{unit.topic}</div>
                </div>
                {!unlocked && <span style={{ font: 'var(--type-meta)', color: 'var(--ink-3)' }}>Supera la unidad anterior</span>}
                {completed && <span style={{ font: 'var(--type-ui-sm)', color: 'var(--success)' }}>Completada · nota {notaStr(pr.final.best, S.FINAL.N)}</span>}
                {unlocked && <span style={{ marginLeft: 8, color: 'var(--ink-3)', transform: isOpen ? 'rotate(90deg)' : 'none', transition: 'transform var(--t-fast)' }}>›</span>}
              </button>

              {/* cuerpo expandido */}
              {isOpen && unlocked && (
                <div style={{ borderTop: '1px solid var(--line)', padding: '8px 20px 18px' }}>
                  {unit.parts.map(part => {
                    const pUn = S.partUnlocked(unit.slug, part.n);
                    const pPassed = pr.parts[part.n].passed;
                    return (
                      <div key={part.n} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 0', borderBottom: '1px dashed var(--line)' }}>
                        <StateDot kind={pPassed ? 'done' : (pUn ? 'open' : 'lock')} />
                        <div style={{ flex: 1, minWidth: 0 }}>
                          <div style={{ font: 'var(--type-body-sm)', color: 'var(--ink)', fontWeight: 600 }}>Parte {part.n} · {part.title}</div>
                          {pPassed
                            ? <div style={{ font: 'var(--type-meta)', color: 'var(--ink-3)' }}>Superada · mejor nota {notaStr(pr.parts[part.n].best, S.PARTIAL.N)} · {pr.parts[part.n].attempts} intento(s)</div>
                            : <div style={{ font: 'var(--type-meta)', color: 'var(--ink-3)' }}>{pUn ? 'Cuestionario de ' + S.PARTIAL.N + ' preguntas · aprobado al 50%' : 'Aprueba la parte anterior'}</div>}
                        </div>
                        {pUn && <button onClick={() => setExpl({ href: part.expl, title: 'Parte ' + part.n + ' · ' + part.title })} style={{ background: 'transparent', border: 0, font: 'var(--type-ui-sm)', color: 'var(--terracotta-deep)', whiteSpace: 'nowrap', cursor: 'pointer', textDecoration: 'underline', textUnderlineOffset: 2 }}>Explicación</button>}
                        {pUn && (
                          <button onClick={() => launchPartial(unit, part)} style={{ background: pPassed ? 'var(--bg-surface)' : 'var(--terracotta)', color: pPassed ? 'var(--ink-2)' : '#fff', border: pPassed ? '1px solid var(--line)' : 0, borderRadius: 'var(--r-md)', padding: '8px 14px', font: 'var(--type-ui-sm)', cursor: 'pointer', whiteSpace: 'nowrap' }}>
                            {pPassed ? 'Repetir' : 'Cuestionario'}
                          </button>
                        )}
                      </div>
                    );
                  })}
                  {/* final */}
                  {(() => {
                    const fUn = S.finalUnlocked(unit.slug);
                    const fPassed = pr.final.passed;
                    return (
                      <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '14px 0 4px' }}>
                        <StateDot kind={fPassed ? 'done' : (fUn ? 'open' : 'lock')} />
                        <div style={{ flex: 1, minWidth: 0 }}>
                          <div style={{ font: 'var(--type-body-sm)', color: 'var(--ink)', fontWeight: 600 }}>Cuestionario final</div>
                          {fPassed
                            ? <div style={{ font: 'var(--type-meta)', color: 'var(--success)' }}>Superado · mejor nota {notaStr(pr.final.best, S.FINAL.N)} · abre {idx + 1 < units.length ? units[idx + 1].ud : 'el final del curso'}</div>
                            : <div style={{ font: 'var(--type-meta)', color: 'var(--ink-3)' }}>{fUn ? S.FINAL.N + ' preguntas · aprobado al 50% · abre la siguiente unidad' : 'Supera las 4 partes primero'}</div>}
                        </div>
                        {fUn && (
                          <button onClick={() => launchFinal(unit)} style={{ background: fPassed ? 'var(--bg-surface)' : 'var(--forest)', color: fPassed ? 'var(--ink-2)' : '#FBF8F0', border: fPassed ? '1px solid var(--line)' : 0, borderRadius: 'var(--r-md)', padding: '8px 16px', font: 'var(--type-ui-sm)', cursor: 'pointer', whiteSpace: 'nowrap' }}>
                            {fPassed ? 'Repetir' : 'Examen final'}
                          </button>
                        )}
                      </div>
                    );
                  })()}
                </div>
              )}
            </div>
          );
        })}
      </div>

      {quiz && (
        <window.Quiz
          title={quiz.title} subtitle={quiz.subtitle} bank={quiz.bank} n={quiz.n} min={quiz.min}
          onResult={({ score, total }) => { S.recordResult(quiz.slug, quiz.partKey, score, total); refresh(); }}
          onClose={() => { setQuiz(null); refresh(); }}
        />
      )}

      {expl && (
        <div style={{ position: 'fixed', inset: 0, zIndex: 60, background: 'var(--bg-canvas)', display: 'flex', flexDirection: 'column' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '12px 20px', borderBottom: '1px solid var(--line)', background: 'var(--bg-surface)' }}>
            <button onClick={() => setExpl(null)} style={{ background: 'var(--forest)', color: '#FBF8F0', border: 0, borderRadius: 'var(--r-md)', padding: '8px 16px', font: 'var(--type-ui-sm)', cursor: 'pointer', whiteSpace: 'nowrap' }}>← Volver al curso</button>
            <div style={{ font: 'var(--type-h4)', color: 'var(--ink)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{expl.title}</div>
          </div>
          <iframe src={expl.href} title={expl.title} style={{ flex: 1, width: '100%', border: 0 }} />
        </div>
      )}
    </main>
  );
}

window.CourseMap = CourseMap;
