// PreviewModal — full-viewport modal that mirrors the SCORM Player runtime.
//
// Replaces the old 540px slide-out PreviewPane: a ~95%×90% centered frame with
// a top-bar (title + language picker + close), a fluid canvas that renders the
// real per-layout renderer (preview-renderers.jsx · unchanged visual shape)
// with prev/next layout arrows, and a module-navigation footer.
//
// Interactivity (quiz answers, in-video interactions) is enabled by providing
// PreviewInteractiveContext=true around the renderer — the editor's small
// Module preview leaves it false, so its behaviour is unchanged.

function PreviewModal({ course, layoutDrafts, selectedLayoutId, onClose }) {
  const mods = course.modules || [];
  const langs = course.languages || ['en'];

  // Seed position from the currently-selected layout if it's in the course,
  // else module 0 / layout 0 (per Fix 2 defaults).
  const seed = React.useMemo(() => {
    for (let m = 0; m < mods.length; m++) {
      const l = mods[m].layouts.findIndex(x => x.id === selectedLayoutId);
      if (l >= 0) return { mi: m, li: l };
    }
    return { mi: 0, li: 0 };
  }, []); // eslint-disable-line

  const [mi, setMi] = React.useState(seed.mi);
  const [li, setLi] = React.useState(seed.li);
  const [lang, setLang] = React.useState(course.defaultLanguage || langs[0] || 'en');

  const mod = mods[mi] || mods[0] || { layouts: [] };
  const rawLayout = mod.layouts[li] || mod.layouts[0];

  const atFirst = mi === 0 && li === 0;
  const atLast = mi === mods.length - 1 && li === (mod.layouts.length - 1);

  const goPrev = React.useCallback(() => {
    setLi(prevLi => {
      if (prevLi > 0) return prevLi - 1;
      if (mi > 0) { const pm = mods[mi - 1]; setMi(mi - 1); return Math.max(0, pm.layouts.length - 1); }
      return prevLi;
    });
  }, [mi, mods]);
  const goNext = React.useCallback(() => {
    setLi(prevLi => {
      if (prevLi < mod.layouts.length - 1) return prevLi + 1;
      if (mi < mods.length - 1) { setMi(mi + 1); return 0; }
      return prevLi;
    });
  }, [mi, mods, mod.layouts.length]);
  const goModule = (j) => { setMi(j); setLi(0); };

  // Keyboard shortcuts while open (Fix 7).
  React.useEffect(() => {
    const h = (e) => {
      if (e.key === 'Escape') { e.preventDefault(); onClose(); }
      else if (e.key === 'ArrowLeft') { if (!atFirst) goPrev(); }
      else if (e.key === 'ArrowRight') { if (!atLast) goNext(); }
    };
    document.addEventListener('keydown', h);
    return () => document.removeEventListener('keydown', h);
  }, [atFirst, atLast, goPrev, goNext, onClose]);

  // Resolve the layout's content: sample content + inline layout + live draft.
  const layoutType = rawLayout?.type || 'fullscreen_text_and_image';
  const content = window.LAYOUT_CONTENT_SAMPLES?.[layoutType] || {};
  const draft = layoutDrafts?.[rawLayout?.id];
  const layout = { ...content, ...(rawLayout || {}), ...(draft || {}), type: layoutType };

  const Interactive = window.PreviewInteractiveContext;

  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, zIndex: 90,
      background: 'rgba(15, 23, 42, 0.6)', backdropFilter: 'blur(2px)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
    }}>
      <div onClick={e => e.stopPropagation()} className="slide-in" style={{
        // CSS-var-driven so the frame size is tweakable.
        ['--pv-w']: '95vw', ['--pv-h']: '90vh',
        width: 'var(--pv-w)', height: 'var(--pv-h)',
        maxWidth: 1600, maxHeight: 900,
        background: 'var(--surface)', borderRadius: 'var(--radius-lg)',
        boxShadow: 'var(--shadow-xl)', overflow: 'hidden',
        display: 'flex', flexDirection: 'column',
      }}>
        {/* Top-bar */}
        <div style={{ flexShrink: 0, height: 48, display: 'flex', alignItems: 'center',
          gap: 12, padding: '0 14px', borderBottom: '1px solid var(--border)',
          background: 'var(--surface)' }}>
          <I.Eye size={15} style={{ color: 'var(--text-muted)' }} />
          <span style={{ fontSize: 13, fontWeight: 600 }}>Preview</span>
          <span style={{ fontSize: 13, color: 'var(--text-muted)' }} className="truncate">
            · {course.title}
          </span>
          <div style={{ flex: 1 }} />
          {langs.length > 1 && (
            <PreviewLanguagePicker langs={langs} value={lang} onChange={setLang} />
          )}
          <div style={{ width: 1, height: 22, background: 'var(--border)' }} />
          <button className="btn sm ghost" onClick={onClose}
            title="Close preview (Esc) · Prev/next layout (← →)"
            style={{ width: 30, height: 30, padding: 0, justifyContent: 'center' }}>
            <I.X size={15} />
          </button>
        </div>

        {/* Canvas */}
        <div style={{ flex: 1, minHeight: 0, position: 'relative', background: '#000' }}>
          <div key={`${rawLayout?.id}:${lang}`} style={{ position: 'absolute', inset: 0, overflow: 'hidden' }}>
            <Interactive.Provider value={true}>
              <PlayerPreview layout={layout} frame="default" lang={lang} />
            </Interactive.Provider>
          </div>

          {/* Prev / next arrows */}
          <PreviewNavArrow dir="prev" disabled={atFirst} onClick={goPrev} />
          <PreviewNavArrow dir="next" disabled={atLast} onClick={goNext} />

          {/* Position chip */}
          <div style={{ position: 'absolute', top: 12, left: 12, zIndex: 5,
            padding: '3px 9px', borderRadius: 999, fontSize: 11, fontFamily: 'var(--font-mono)',
            background: 'rgba(15,23,42,.6)', color: '#fff', backdropFilter: 'blur(4px)',
            display: 'inline-flex', alignItems: 'center', gap: 6 }}>
            <span>{rawLayout?.id}</span>
            <span style={{ opacity: .6 }}>·</span>
            <span style={{ opacity: .85 }}>{layoutType}</span>
          </div>
        </div>

        {/* Module navigation footer */}
        <div style={{ flexShrink: 0, display: 'flex', alignItems: 'center', gap: 8,
          padding: '10px 14px', borderTop: '1px solid var(--border)',
          background: 'var(--surface-2)', overflowX: 'auto' }}>
          <span style={{ fontSize: 10.5, color: 'var(--text-faint)', fontWeight: 600,
            letterSpacing: '.06em', textTransform: 'uppercase', flexShrink: 0 }}>Modules</span>
          {mods.map((m, j) => (
            <ModulePill key={m.id} module={m} index={j} active={j === mi}
              layoutCount={m.layouts.length}
              activeLayoutIdx={j === mi ? li : null}
              onClick={() => goModule(j)} />
          ))}
        </div>
      </div>
    </div>
  );
}

// ─── Module pill ─────────────────────────────────────────────────────────────
function ModulePill({ module, index, active, layoutCount, activeLayoutIdx, onClick }) {
  return (
    <button onClick={onClick}
      style={{
        display: 'inline-flex', alignItems: 'center', gap: 8, flexShrink: 0,
        maxWidth: 240, height: 34, padding: '0 12px', cursor: 'default', fontFamily: 'inherit',
        background: active ? 'var(--accent-bg)' : 'var(--surface)',
        color: active ? 'var(--accent-text)' : 'var(--text)',
        border: '1px solid', borderColor: active ? 'var(--accent-border)' : 'var(--border)',
        borderRadius: 'var(--radius)', fontSize: 12.5, fontWeight: active ? 600 : 500,
      }}>
      <span style={{
        width: 18, height: 18, borderRadius: '50%', flexShrink: 0, fontSize: 10.5, fontWeight: 700,
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        background: active ? 'var(--accent)' : 'var(--surface-inset)',
        color: active ? '#fff' : 'var(--text-muted)',
      }}>{module.n ?? index + 1}</span>
      <span className="truncate" style={{ maxWidth: 150 }}>{locText(module.title)}</span>
      {active && (
        <span style={{ fontSize: 10.5, color: 'var(--accent-text)', fontFamily: 'var(--font-mono)',
          opacity: .8 }}>{(activeLayoutIdx ?? 0) + 1}/{layoutCount}</span>
      )}
    </button>
  );
}

// ─── Nav arrow ───────────────────────────────────────────────────────────────
function PreviewNavArrow({ dir, disabled, onClick }) {
  const Icon = dir === 'prev' ? I.ChevronLeft : I.ChevronRight;
  return (
    <button onClick={disabled ? undefined : onClick} disabled={disabled}
      aria-label={dir === 'prev' ? 'Previous layout' : 'Next layout'}
      style={{
        position: 'absolute', top: '50%', transform: 'translateY(-50%)', zIndex: 5,
        [dir === 'prev' ? 'left' : 'right']: 14,
        width: 44, height: 44, borderRadius: '50%', cursor: 'default',
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        background: 'rgba(15,23,42,.55)', color: '#fff',
        border: '1px solid rgba(255,255,255,.18)', backdropFilter: 'blur(4px)',
        opacity: disabled ? 0.25 : 1,
        transition: 'opacity 120ms, background 120ms',
      }}
      onMouseOver={e => { if (!disabled) e.currentTarget.style.background = 'rgba(15,23,42,.8)'; }}
      onMouseOut={e => { e.currentTarget.style.background = 'rgba(15,23,42,.55)'; }}>
      <Icon size={22} />
    </button>
  );
}

// ─── Language picker (Fix 8) ────────────────────────────────────────────────
// Segmented control when ≤ 3 languages, dropdown otherwise.
function PreviewLanguagePicker({ langs, value, onChange }) {
  const flag = l => window.LANG_FLAGS?.[l] || '';
  const name = l => window.LANG_NAMES?.[l] || l;
  if (langs.length <= 3) {
    return (
      <div style={{ display: 'inline-flex', gap: 3, padding: 3,
        background: 'var(--surface-inset)', border: '1px solid var(--border)',
        borderRadius: 'var(--radius)' }}>
        {langs.map(l => {
          const sel = l === value;
          return (
            <button key={l} onClick={() => onChange(l)}
              title={name(l)}
              style={{
                display: 'inline-flex', alignItems: 'center', gap: 5, padding: '3px 9px',
                fontSize: 11.5, fontFamily: 'inherit', cursor: 'default', borderRadius: 4, border: 0,
                background: sel ? 'var(--surface)' : 'transparent',
                color: sel ? 'var(--text)' : 'var(--text-muted)',
                fontWeight: sel ? 600 : 500, boxShadow: sel ? 'var(--shadow-sm)' : 'none',
              }}>
              <span style={{ fontSize: 13 }}>{flag(l)}</span>
              <span style={{ textTransform: 'uppercase', letterSpacing: '.03em' }}>{l}</span>
            </button>
          );
        })}
      </div>
    );
  }
  return (
    <select className="field select-elegant" value={value}
      onChange={e => onChange(e.target.value)}
      style={{ height: 30, fontSize: 12.5, paddingRight: 26 }}>
      {langs.map(l => <option key={l} value={l}>{flag(l)} {name(l)}</option>)}
    </select>
  );
}

Object.assign(window, { PreviewModal });
