// ============================================================
// Video Course Library — paid, Vimeo player, progress + resume
// Self-contained (uses React.* directly to avoid scope clashes)
// ============================================================

(function () {
  const { useState, useEffect, useCallback } = React;

  // ---- tiny icon set ----
  const VIcon = ({ name, size = 18, stroke = 1.7 }) => {
    const p = { width: size, height: size, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', strokeWidth: stroke, strokeLinecap: 'round', strokeLinejoin: 'round' };
    const paths = {
      play: <path d="M7 5v14l11-7z" fill="currentColor" stroke="none" />,
      lock: <><rect x="5" y="11" width="14" height="9" rx="2" /><path d="M8 11V8a4 4 0 0 1 8 0v3" /></>,
      check: <path d="M5 12l4 4L19 7" />,
      clock: <><circle cx="12" cy="12" r="9" /><path d="M12 7v5l3 3" /></>,
      x: <><path d="M6 6l12 12" /><path d="M18 6L6 18" /></>,
      arrow: <><path d="M5 12h14" /><path d="M13 6l6 6-6 6" /></>,
      layers: <><path d="M12 2L2 7l10 5 10-5-10-5z" /><path d="M2 17l10 5 10-5" /><path d="M2 12l10 5 10-5" /></>,
      resume: <><circle cx="12" cy="12" r="9" /><path d="M10 9l5 3-5 3z" fill="currentColor" stroke="none" /></>
    };
    return <svg {...p}>{paths[name]}</svg>;
  };

  // ---- localStorage helpers ----
  const UNLOCK_KEY = 'pbi_vc_unlocked';
  const PROG_KEY = 'pbi_vc_progress';
  const ACCESS_CODE = 'PBI2026';

  const readJSON = (k) => {try {return JSON.parse(localStorage.getItem(k) || '{}');} catch (e) {return {};}};
  const writeJSON = (k, v) => {try {localStorage.setItem(k, JSON.stringify(v));} catch (e) {}};

  const durToSec = (d) => {const [m, s] = (d || '0:0').split(':').map(Number);return (m || 0) * 60 + (s || 0);};
  const courseHours = (c) => {
    const sec = c.lessons.reduce((a, l) => a + durToSec(l.duration), 0);
    return (sec / 3600).toFixed(1);
  };

  // ---- course card (library grid) ----
  const CourseTile = ({ c, t, unlocked, progress, onOpen }) => {
    const done = progress && progress.completed ? Object.keys(progress.completed).length : 0;
    const total = c.lessons.length;
    const pct = Math.round(done / total * 100);
    const started = done > 0 || progress && progress.last > 0;
    const cta = unlocked ? started ? t.resume : t.start : t.unlock;

    return (
      <button className="vc-tile" onClick={() => onOpen(c.id)} style={{ '--vc-hue': c.hue }}>
        <div className="vc-tile-cover">
          <span className="vc-tile-level mono">{c.level}</span>
          <span className="vc-tile-play"><VIcon name="play" size={22} /></span>
          {!unlocked && <span className="vc-tile-lock"><VIcon name="lock" size={13} /> {t.lockedBadge}</span>}
        </div>
        <div className="vc-tile-body">
          <h4 className="vc-tile-title">{c.title}</h4>
          <div className="vc-tile-meta mono">
            <span><VIcon name="layers" size={13} /> {total} {t.lessonsLabel}</span>
            <span className="vc-dot" />
            <span><VIcon name="clock" size={13} /> {courseHours(c)} {t.hoursLabel}</span>
          </div>
          {unlocked && started &&
          <div className="vc-tile-progress">
              <div className="vc-bar"><div className="vc-bar-fill" style={{ width: pct + '%' }} /></div>
              <span className="mono">{done}/{total} {t.progressDone}</span>
            </div>}
          <div className="vc-tile-foot">
            <span className="vc-tile-price mono">{unlocked ? <span className="vc-owned"><VIcon name="check" size={14} /> {t.markedComplete}</span> : <>{c.price} <small>{c.currency}</small></>}</span>
            <span className="vc-tile-cta mono">{cta} <VIcon name="arrow" size={14} /></span>
          </div>
        </div>
      </button>);

  };

  // ---- unlock panel (shown over player when locked) ----
  const UnlockPanel = ({ c, t, onUnlock }) => {
    const [code, setCode] = useState('');
    const [err, setErr] = useState(false);
    const redeem = () => {
      const expected = (c.accessCode || ACCESS_CODE).trim().toUpperCase();
      if (code.trim().toUpperCase() === expected) {setErr(false);onUnlock();} else
      setErr(true);
    };
    return (
      <div className="vc-unlock">
        <div className="vc-unlock-icon"><VIcon name="lock" size={26} /></div>
        <h4>{t.unlockTitle}</h4>
        <p>{t.unlockBody}</p>
        <div className="vc-unlock-price mono">{c.price} <small>{c.currency}</small></div>
        <button className="vc-btn vc-btn-primary" onClick={onUnlock}>{t.purchaseCta} <VIcon name="arrow" size={15} /></button>
        <div className="vc-code">
          <label className="mono">{t.codeLabel}</label>
          <div className="vc-code-row">
            <input className={`vc-code-input mono ${err ? 'err' : ''}`} value={code} placeholder={t.codePlaceholder}
            onChange={(e) => {setCode(e.target.value);setErr(false);}}
            onKeyDown={(e) => e.key === 'Enter' && redeem()} />
            <button className="vc-btn vc-btn-ghost" onClick={redeem}>{t.codeCta}</button>
          </div>
          {err && <span className="vc-code-err mono">{t.codeError}</span>}
        </div>
      </div>);

  };

  // ---- player modal ----
  const PlayerModal = ({ c, t, unlocked, progress, onClose, onUnlock, onProgress }) => {
    const [current, setCurrent] = useState(() => Math.min(progress.last || 0, c.lessons.length - 1));
    const completed = progress.completed || {};
    const lesson = c.lessons[current];
    const playable = unlocked || lesson.free;

    useEffect(() => {
      const onKey = (e) => {if (e.key === 'Escape') onClose();};
      document.addEventListener('keydown', onKey);
      document.body.style.overflow = 'hidden';
      return () => {document.removeEventListener('keydown', onKey);document.body.style.overflow = '';};
    }, []);

    const select = (i) => {setCurrent(i);onProgress({ ...progress, last: i, completed });};
    const markComplete = () => {
      const nc = { ...completed, [current]: true };
      const next = Math.min(current + 1, c.lessons.length - 1);
      onProgress({ completed: nc, last: next });
      setCurrent(next);
    };

    const doneCount = Object.keys(completed).length;
    const pct = Math.round(doneCount / c.lessons.length * 100);

    return (
      <div className="vc-modal" onMouseDown={(e) => {if (e.target === e.currentTarget) onClose();}}>
        <div className="vc-modal-panel" style={{ '--vc-hue': c.hue }}>
          <div className="vc-modal-head">
            <div>
              <div className="vc-modal-eyebrow mono">{c.level} · {c.lessons.length} {t.lessonsLabel}</div>
              <h3>{c.title}</h3>
            </div>
            <button className="vc-close" onClick={onClose} aria-label="Close"><VIcon name="x" size={20} /></button>
          </div>

          <div className="vc-modal-body">
            <div className="vc-stage">
              <div className="vc-video">
                {playable ?
                <iframe
                  key={c.id + '-' + current}
                  src={`https://player.vimeo.com/video/${lesson.vimeo}?title=0&byline=0&portrait=0&dnt=1`}
                  allow="autoplay; fullscreen; picture-in-picture"
                  allowFullScreen
                  title={lesson.title} /> :
                <UnlockPanel c={c} t={t} onUnlock={onUnlock} />}
              </div>
              <div className="vc-stage-foot">
                <div className="vc-now">
                  <div className="vc-now-label mono">{t.lessonOf} {current + 1} / {c.lessons.length}</div>
                  <div className="vc-now-title">{lesson.title}</div>
                </div>
                {playable &&
                <button className={`vc-btn ${completed[current] ? 'vc-btn-done' : 'vc-btn-primary'}`} onClick={markComplete}>
                    {completed[current] ? <><VIcon name="check" size={15} /> {t.markedComplete}</> : <>{t.markComplete} <VIcon name="arrow" size={15} /></>}
                  </button>}
              </div>
            </div>

            <div className="vc-list">
              <div className="vc-list-head">
                <div className="vc-bar"><div className="vc-bar-fill" style={{ width: pct + '%' }} /></div>
                <span className="mono">{doneCount}/{c.lessons.length} {t.progressDone}</span>
              </div>
              <div className="vc-list-scroll">
                {c.lessons.map((l, i) => {
                  const lk = !unlocked && !l.free;
                  return (
                    <button key={i} className={`vc-row ${i === current ? 'active' : ''}`} onClick={() => select(i)}>
                      <span className="vc-row-num">
                        {completed[i] ? <span className="vc-row-check"><VIcon name="check" size={13} /></span> :
                        lk ? <VIcon name="lock" size={13} /> :
                        <span className="mono">{String(i + 1).padStart(2, '0')}</span>}
                      </span>
                      <span className="vc-row-main">
                        <span className="vc-row-title">{l.title}</span>
                        <span className="vc-row-meta mono">
                          {l.free && <span className="vc-row-free">{t.previewTag}</span>}
                          <span>{l.duration}</span>
                        </span>
                      </span>
                      {i === current && <span className="vc-row-now"><VIcon name="play" size={12} /></span>}
                    </button>);

                })}
              </div>
            </div>
          </div>
        </div>
      </div>);

  };

  // ---- library (section) ----
  const VideoCourseLibrary = ({ t }) => {
    const vc = t.videoCourses;
    const [unlocked, setUnlocked] = useState(() => readJSON(UNLOCK_KEY));
    const [progressMap, setProgressMap] = useState(() => readJSON(PROG_KEY));
    const [openId, setOpenId] = useState(null);

    const open = vc.items.find((c) => c.id === openId);

    const unlock = (id) => {
      const next = { ...unlocked, [id]: true };
      setUnlocked(next);writeJSON(UNLOCK_KEY, next);
    };
    const setProgress = (id, p) => {
      const next = { ...progressMap, [id]: p };
      setProgressMap(next);writeJSON(PROG_KEY, next);
    };

    return (
      <div className="vc-wrap">
        <div className="vc-intro">
          <span className="eyebrow">{vc.eyebrow}</span>
          <h3 className="vc-heading">{vc.title}</h3>
          <p className="vc-sub" style={{ width: "800px" }}>{vc.subtitle}</p>
        </div>
        <div className="vc-grid">
          {vc.items.map((c) =>
          <CourseTile key={c.id} c={c} t={vc}
          unlocked={!!unlocked[c.id]}
          progress={progressMap[c.id] || {}}
          onOpen={setOpenId} />)}
        </div>
        {open &&
        <PlayerModal
          c={open} t={vc}
          unlocked={!!unlocked[open.id]}
          progress={progressMap[open.id] || { completed: {}, last: 0 }}
          onClose={() => setOpenId(null)}
          onUnlock={() => unlock(open.id)}
          onProgress={(p) => setProgress(open.id, p)} />}
      </div>);

  };

  window.VideoCourseLibrary = VideoCourseLibrary;
})();