/* ============================================================
   TechManager — LEARNING PATH + MODULE READER
   ============================================================ */

/* ---- content-block renderers ---- */
const VideoBlock = ({ b, color }) => {
  const [playing, setPlaying] = useState(false);
  return (
    <div className="card" style={{ overflow: 'hidden' }}>
      <div onClick={() => setPlaying(true)} style={{ position: 'relative', aspectRatio: '16/8', cursor: 'pointer',
        background: `radial-gradient(circle at 30% 20%, ${color}44, transparent 60%), linear-gradient(135deg, var(--panel-3), var(--bg-soft))`,
        display: 'grid', placeItems: 'center' }}>
        {!playing ? (
          <>
            <div style={{ width: 66, height: 66, borderRadius: '50%', background: 'rgba(255,255,255,0.12)', backdropFilter: 'blur(6px)', display: 'grid', placeItems: 'center', border: '1px solid rgba(255,255,255,0.3)' }}>
              <Icon name="play" size={26} style={{ color: '#fff', marginLeft: 3 }} />
            </div>
            <span className="chip" style={{ position: 'absolute', bottom: 12, right: 12, fontSize: 12 }}><Icon name="clock" size={13} /> {b.duration}</span>
          </>
        ) : (
          <div style={{ textAlign: 'center', color: 'var(--muted)' }}>
            <div className="spin" style={{ width: 30, height: 30, border: '3px solid rgba(255,255,255,0.15)', borderTopColor: 'var(--blue-2)', borderRadius: '50%', margin: '0 auto 10px' }} />
            <span style={{ fontSize: 13 }}>Streaming "{b.title}"…</span>
          </div>
        )}
      </div>
      <div className="between" style={{ padding: '14px 18px' }}>
        <span className="center gap-8" style={{ fontWeight: 600, fontSize: 14.5 }}><Icon name="play" size={14} style={{ color }} /> {b.title}</span>
        <span className="dim" style={{ fontSize: 12.5 }}>Video lesson</span>
      </div>
    </div>
  );
};

const Diagram = ({ kind, color }) => {
  const c = color || 'var(--blue-2)';
  if (kind === 'bars') return (
    <svg viewBox="0 0 240 110" style={{ width: '100%', maxWidth: 320 }}>
      {[40, 70, 55, 92, 64].map((h, i) => (
        <rect key={i} x={18 + i * 44} y={100 - h} width="28" height={h} rx="4" fill={c} opacity={0.4 + i * 0.12} />
      ))}
      <line x1="8" y1="100" x2="232" y2="100" stroke="var(--border-strong)" />
    </svg>
  );
  if (kind === 'tree') return (
    <svg viewBox="0 0 260 120" style={{ width: '100%', maxWidth: 320 }}>
      <line x1="130" y1="26" x2="60" y2="78" stroke={c} strokeWidth="2" />
      <line x1="130" y1="26" x2="200" y2="78" stroke={c} strokeWidth="2" />
      <line x1="60" y1="78" x2="36" y2="106" stroke={c} strokeWidth="2" opacity="0.6" />
      <line x1="60" y1="78" x2="84" y2="106" stroke={c} strokeWidth="2" opacity="0.6" />
      {[[130, 26], [60, 78], [200, 78], [36, 106], [84, 106]].map(([x, y], i) => <circle key={i} cx={x} cy={y} r={i === 0 ? 12 : 9} fill={c} opacity={i === 0 ? 1 : 0.7} />)}
    </svg>
  );
  return ( // flow
    <svg viewBox="0 0 320 80" style={{ width: '100%', maxWidth: 360 }}>
      {[0, 1, 2].map((i) => (
        <g key={i}>
          <rect x={10 + i * 110} y={24} width="84" height="34" rx="8" fill="none" stroke={c} strokeWidth="2" />
          {i < 2 && <line x1={94 + i * 110} y1={41} x2={120 + i * 110} y2={41} stroke={c} strokeWidth="2" markerEnd="url(#ah)" />}
        </g>
      ))}
      <defs><marker id="ah" markerWidth="8" markerHeight="8" refX="6" refY="3" orient="auto"><path d="M0 0l6 3-6 3z" fill={c} /></marker></defs>
    </svg>
  );
};

const ExampleQuestion = ({ b }) => {
  const [picked, setPicked] = useState(null);
  return (
    <div className="card" style={{ padding: 22, borderColor: 'rgba(47,125,246,0.25)' }}>
      <div className="center gap-8" style={{ marginBottom: 12 }}>
        <span className="badge" style={{ background: 'rgba(47,125,246,0.14)', color: 'var(--blue-2)', border: '1px solid rgba(47,125,246,0.3)' }}><Icon name="target" size={12} /> Example question</span>
        <span className="dim" style={{ fontSize: 12 }}>Practice — not graded</span>
      </div>
      <p style={{ fontWeight: 600, fontSize: 16, marginTop: 0 }}>{b.prompt}</p>
      <div className="grid gap-8" style={{ marginTop: 6 }}>
        {b.options.map((o, i) => {
          const isAns = i === b.correct, chosen = picked === i;
          let style = { textAlign: 'left', padding: '12px 14px', borderRadius: 10, border: '1px solid var(--border-strong)', background: 'var(--bg-soft)', color: 'var(--text-2)', fontSize: 14.5, transition: 'all .15s' };
          if (picked !== null && isAns) style = { ...style, borderColor: 'var(--green)', background: 'rgba(52,211,153,0.1)', color: '#d1fae5' };
          else if (chosen && !isAns) style = { ...style, borderColor: 'var(--red)', background: 'rgba(248,113,113,0.1)', color: '#fecaca' };
          return (
            <button key={i} onClick={() => picked === null && setPicked(i)} style={style}>
              <span className="between"><span>{o}</span>{picked !== null && isAns && <Icon name="check" size={16} style={{ color: 'var(--green)' }} />}{chosen && !isAns && <Icon name="x" size={16} style={{ color: 'var(--red)' }} />}</span>
            </button>
          );
        })}
      </div>
      {picked !== null && <p className="muted" style={{ fontSize: 13.5, marginTop: 12, marginBottom: 0 }}>{picked === b.correct ? 'Correct — ' : 'Not quite. '} The model answer is highlighted above.</p>}
    </div>
  );
};

const Block = ({ b, color }) => {
  if (b.type === 'video') return <VideoBlock b={b} color={color} />;
  if (b.type === 'example-question') return <ExampleQuestion b={b} />;
  if (b.type === 'text') return (
    <div className="card" style={{ padding: 24 }}>
      {b.heading && <h4 className="display" style={{ fontSize: 18, marginBottom: 8 }}>{b.heading}</h4>}
      <p className="muted" style={{ margin: 0, fontSize: 15.5, lineHeight: 1.65 }}>{b.body}</p>
    </div>
  );
  if (b.type === 'image') return (
    <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
      <div style={{ aspectRatio: '16/7', background: 'repeating-linear-gradient(45deg, var(--panel-2), var(--panel-2) 14px, var(--panel-3) 14px, var(--panel-3) 28px)', display: 'grid', placeItems: 'center', color: 'var(--dim)' }}>
        <div style={{ textAlign: 'center' }}><Icon name="image" size={30} /><div style={{ fontSize: 12.5, marginTop: 6 }}>Image placeholder</div></div>
      </div>
      <div style={{ padding: '12px 18px', fontSize: 13.5 }} className="muted">{b.caption}</div>
    </div>
  );
  if (b.type === 'diagram') return (
    <div className="card" style={{ padding: 24, textAlign: 'center' }}>
      <Diagram kind={b.kind} color={color} />
      <div className="muted" style={{ fontSize: 13.5, marginTop: 12 }}>{b.caption}</div>
    </div>
  );
  return null;
};

/* ---- Module reader ---- */
const ModuleReader = ({ cert, mod, idx, total, onBack, onPrev, onNext }) => (
  <div className="fadein wrap section tight">
    <button className="btn btn-soft btn-sm" onClick={onBack}><Icon name="arrowL" size={15} /> Back to modules</button>
    <div className="between" style={{ marginTop: 20, flexWrap: 'wrap', gap: 12 }}>
      <div>
        <div className="dim" style={{ fontSize: 13, fontWeight: 700, letterSpacing: '.04em' }}>MODULE {idx + 1} OF {total} · {cert.name}</div>
        <h1 className="display" style={{ fontSize: 'clamp(28px,3.4vw,40px)', marginTop: 8 }}>{mod.title}</h1>
        <p className="lede" style={{ marginTop: 8 }}>{mod.summary}</p>
      </div>
    </div>
    <div className="grid gap-16" style={{ marginTop: 28 }}>
      {mod.blocks.map((b, i) => <Block key={i} b={b} color={cert.color} />)}
    </div>
    <div className="between" style={{ marginTop: 28 }}>
      <button className="btn btn-soft" onClick={onPrev} disabled={idx === 0}><Icon name="arrowL" size={15} /> Previous</button>
      {idx < total - 1
        ? <button className="btn btn-primary" onClick={onNext}>Next module <Icon name="arrow" size={15} /></button>
        : <button className="btn btn-primary" onClick={onBack}>Finish <Icon name="check" size={15} /></button>}
    </div>
  </div>
);

/* ---- Learning path overview ---- */
const LearningPath = ({ cert, db, go, startExam }) => {
  const [openIdx, setOpenIdx] = useState(null);
  const earned = db.user.certificates.includes(cert.id);
  const attempts = db.user.attempts.filter((a) => a.certId === cert.id);

  if (openIdx !== null) {
    return <ModuleReader cert={cert} mod={cert.modules[openIdx]} idx={openIdx} total={cert.modules.length}
      onBack={() => setOpenIdx(null)} onPrev={() => setOpenIdx((i) => Math.max(0, i - 1))} onNext={() => setOpenIdx((i) => Math.min(cert.modules.length - 1, i + 1))} />;
  }

  return (
    <div className="fadein wrap section tight">
      <button className="btn btn-soft btn-sm" onClick={() => go('certs')}><Icon name="arrowL" size={15} /> All certifications</button>

      {/* cert header */}
      <div className="card" style={{ padding: 30, marginTop: 20, position: 'relative', overflow: 'hidden' }}>
        <div style={{ position: 'absolute', inset: 0, background: `radial-gradient(500px 200px at 90% -30%, ${cert.color}33, transparent)`, pointerEvents: 'none' }} />
        <div className="between" style={{ flexWrap: 'wrap', gap: 24, position: 'relative' }}>
          <div className="flex gap-24" style={{ alignItems: 'center' }}>
            <Orb cert={cert} size={92} />
            <div>
              <div className="flex gap-12" style={{ alignItems: 'center', marginBottom: 8 }}>
                <StatusBadge status={cert.status} />
                {earned && <span className="badge badge-pass"><Icon name="award" size={12} /> Earned</span>}
              </div>
              <h1 className="display" style={{ fontSize: 'clamp(26px,3vw,38px)' }}>{cert.name}</h1>
              <p className="muted" style={{ margin: '6px 0 0', maxWidth: '52ch' }}>{cert.description}</p>
            </div>
          </div>
          <div className="card" style={{ padding: 20, minWidth: 230, background: 'var(--bg-soft)' }}>
            <div className="grid gap-12" style={{ fontSize: 13.5 }}>
              <div className="between"><span className="muted center gap-8"><Icon name="book" size={15} /> Modules</span><strong>{cert.modules.length}</strong></div>
              <div className="between"><span className="muted center gap-8"><Icon name="target" size={15} /> Areas</span><strong>{cert.areas.length}</strong></div>
              <div className="between"><span className="muted center gap-8"><Icon name="clock" size={15} /> Exam time</span><strong>{cert.examConfig.timeMinutes} min</strong></div>
              <div className="between"><span className="muted center gap-8"><Icon name="checkCircle" size={15} /> Pass mark</span><strong>{cert.examConfig.passGrade}%</strong></div>
            </div>
            <button className="btn btn-primary btn-block" style={{ marginTop: 16 }} onClick={() => startExam(cert)}>
              <Icon name="lock" size={15} /> {attempts.length ? 'Retake exam' : 'Take the exam'}
            </button>
          </div>
        </div>
      </div>

      {/* areas */}
      <div style={{ marginTop: 28 }}>
        <div className="field-label">Domains this credential covers</div>
        <div className="flex gap-8" style={{ flexWrap: 'wrap' }}>
          {cert.areas.map((a) => <span key={a} className="chip">{a}</span>)}
        </div>
      </div>

      {/* modules */}
      <h2 className="display" style={{ fontSize: 26, marginTop: 40, marginBottom: 6 }}>Study modules</h2>
      <p className="muted" style={{ marginTop: 0 }}>Work through each module before sitting the exam. Each mixes video, reading, diagrams, and practice questions.</p>
      <div className="grid gap-12" style={{ marginTop: 20 }}>
        {cert.modules.length === 0 && <div className="card muted" style={{ padding: 28, textAlign: 'center' }}>Modules for this certification are still being authored.</div>}
        {cert.modules.map((m, i) => (
          <button key={m.id} className="card card-hover" onClick={() => setOpenIdx(i)} style={{ padding: 20, textAlign: 'left', display: 'flex', alignItems: 'center', gap: 18 }}>
            <div style={{ width: 44, height: 44, flex: '0 0 44px', borderRadius: 12, background: `linear-gradient(135deg, ${cert.color}, ${cert.color2})`, display: 'grid', placeItems: 'center', fontWeight: 800, fontFamily: 'var(--display)' }}>{i + 1}</div>
            <div style={{ flex: 1 }}>
              <div style={{ fontWeight: 700, fontSize: 16.5 }}>{m.title}</div>
              <div className="muted" style={{ fontSize: 13.5, marginTop: 2 }}>{m.summary}</div>
              <div className="flex gap-12" style={{ marginTop: 8 }}>
                {[...new Set(m.blocks.map((b) => b.type))].map((t) => (
                  <span key={t} className="dim center gap-8" style={{ fontSize: 12 }}>
                    <Icon name={{ video: 'play', text: 'book', image: 'image', diagram: 'diagram', 'example-question': 'target' }[t]} size={13} />
                    {{ video: 'Video', text: 'Reading', image: 'Image', diagram: 'Diagram', 'example-question': 'Practice' }[t]}
                  </span>
                ))}
              </div>
            </div>
            <Icon name="chevR" size={20} style={{ color: 'var(--dim)' }} />
          </button>
        ))}
      </div>

      {/* attempts history for this cert */}
      {attempts.length > 0 && (
        <div style={{ marginTop: 40 }}>
          <h2 className="display" style={{ fontSize: 22, marginBottom: 14 }}>Your attempts</h2>
          <div className="grid gap-12">
            {attempts.map((a) => (
              <div key={a.id} className="card between" style={{ padding: '14px 18px' }}>
                <span className="center gap-12"><span className={'badge ' + (a.passed ? 'badge-pass' : 'badge-fail')}>{a.passed ? 'Passed' : 'Not passed'}</span><span className="muted" style={{ fontSize: 13 }}>{new Date(a.date).toLocaleDateString()}</span></span>
                <strong>{a.score}%</strong>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
};

Object.assign(window, { Block, Diagram, ExampleQuestion, VideoBlock, ModuleReader, LearningPath });
