// app-lesson.jsx — Lesson player, course detail, and CivifyApp shell
// Depends on: app-data.js, app-icons.jsx, app-screens.jsx, logo.jsx
(function () {
  const { useState, useRef, useEffect, useCallback } = React;
  const D = window.CIVIFY_APP;
  const Icon = window.Icon;

  // ── FILL (drag-to-place) exercise ───────────────────────────
  function FillExercise({ step, slots, setSlots, locked }) {
    const blankRefs = useRef([]);
    const [drag, setDrag] = useState(null); // {chip, x, y, w, h, label}
    const [over, setOver] = useState(-1);

    const usedChips = slots.filter((s) => s !== null).map((s) => s.chip);

    const placeInSlot = (chipIdx, slotIdx) => {
      setSlots((prev) => {
        const next = prev.map((s) => (s && s.chip === chipIdx ? null : s)); // remove chip elsewhere
        next[slotIdx] = { chip: chipIdx, label: step.chips[chipIdx] };
        return next;
      });
    };
    const clickChip = (chipIdx) => {
      if (locked) return;
      setSlots((prev) => {
        if (prev.some((s) => s && s.chip === chipIdx)) return prev; // already placed
        const empty = prev.findIndex((s) => s === null);
        if (empty < 0) return prev;
        const next = prev.slice();
        next[empty] = { chip: chipIdx, label: step.chips[chipIdx] };
        return next;
      });
    };
    const clearSlot = (slotIdx) => {
      if (locked) return;
      setSlots((prev) => prev.map((s, i) => (i === slotIdx ? null : s)));
    };

    // pointer drag
    const startDrag = (e, chipIdx) => {
      if (locked || usedChips.includes(chipIdx)) return;
      const r = e.currentTarget.getBoundingClientRect();
      e.currentTarget.setPointerCapture?.(e.pointerId);
      setDrag({ chip: chipIdx, x: e.clientX, y: e.clientY, w: r.width, h: r.height, label: step.chips[chipIdx] });
    };
    useEffect(() => {
      if (!drag) return;
      const move = (e) => {
        setDrag((d) => (d ? { ...d, x: e.clientX, y: e.clientY } : d));
        let hit = -1;
        blankRefs.current.forEach((el, i) => {
          if (!el) return;
          const r = el.getBoundingClientRect();
          if (e.clientX >= r.left && e.clientX <= r.right && e.clientY >= r.top && e.clientY <= r.bottom) hit = i;
        });
        setOver(hit);
      };
      const up = (e) => {
        let hit = -1;
        blankRefs.current.forEach((el, i) => {
          if (!el) return;
          const r = el.getBoundingClientRect();
          if (e.clientX >= r.left && e.clientX <= r.right && e.clientY >= r.top && e.clientY <= r.bottom) hit = i;
        });
        if (hit >= 0) placeInSlot(drag.chip, hit);
        setDrag(null); setOver(-1);
      };
      window.addEventListener('pointermove', move);
      window.addEventListener('pointerup', up);
      return () => { window.removeEventListener('pointermove', move); window.removeEventListener('pointerup', up); };
    }, [drag]);

    let bi = -1;
    return (
      <div>
        <div className="cf-sent">
          {step.sentence.map((part, i) => {
            if (part === '{0}' || part === '{1}') {
              bi += 1;
              const idx = bi;
              const s = slots[idx];
              const correct = locked && s && s.label === step.blanks[idx];
              return (
                <span
                  key={i}
                  ref={(el) => (blankRefs.current[idx] = el)}
                  className={'cf-blank' + (s ? ' filled' : '') + (over === idx ? ' over' : '')}
                  style={locked && s ? { borderColor: correct ? '#2FA36B' : '#E25555', background: correct ? '#EAF7F0' : '#FCEBEB', color: correct ? '#2FA36B' : '#E25555' } : null}
                  onClick={() => s && clearSlot(idx)}
                >
                  {s ? s.label : ''}
                </span>
              );
            }
            return <span key={i}>{part}</span>;
          })}
        </div>
        <div className="cf-tray">
          {step.chips.map((w, i) => (
            <div
              key={i}
              className={'cf-word' + (usedChips.includes(i) ? ' used' : '')}
              onPointerDown={(e) => startDrag(e, i)}
              onClick={() => clickChip(i)}
            >
              {w}
            </div>
          ))}
        </div>
        {drag && (
          <div className="cf-word flying" style={{ left: drag.x, top: drag.y, width: drag.w, transform: 'translate(-50%,-50%) rotate(-3deg)' }}>
            {drag.label}
          </div>
        )}
      </div>
    );
  }

  // ── LESSON PLAYER ───────────────────────────────────────────
  function Lesson({ onClose, onDone }) {
    const L = D.lesson;
    const [idx, setIdx] = useState(0);
    const [checked, setChecked] = useState(false);
    const [choice, setChoice] = useState(null);
    const [tf, setTf] = useState(null);
    const [slots, setSlots] = useState([null, null]);
    const [done, setDone] = useState(false);

    const step = L.steps[idx];
    const progress = ((idx + (checked ? 1 : 0)) / L.steps.length) * 100;

    const reset = () => { setChecked(false); setChoice(null); setTf(null); setSlots([null, null]); };

    const isCorrect = () => {
      if (step.type === 'choice') return step.options[choice]?.correct;
      if (step.type === 'truefalse') return tf === step.answer;
      if (step.type === 'fill') return slots.every((s, i) => s && s.label === step.blanks[i]);
      return true;
    };

    const canCheck = () => {
      if (step.type === 'choice') return choice !== null;
      if (step.type === 'truefalse') return tf !== null;
      if (step.type === 'fill') return slots.every((s) => s !== null);
      return true;
    };

    const advance = () => {
      if (idx + 1 >= L.steps.length) { setDone(true); return; }
      setIdx(idx + 1); reset();
    };

    const onPrimary = () => {
      if (step.type === 'intro') { advance(); return; }
      if (!checked) { setChecked(true); return; }
      advance();
    };

    if (done) {
      return (
        <div className="cf-lesson">
          <div className="cf-done">
            <div className="tw"><Icon name="trophy" size={48} color="#fff" /></div>
            <h2>Lektion klar!</h2>
            <p>Snyggt jobbat — du behärskar EU:s institutioner.</p>
            <div className="cf-rew">
              <div><b>+{L.reward}</b><span>Poäng</span></div>
              <div><b>{D.user.streak + 1}</b><span>Streak</span></div>
            </div>
            <button className="cf-btn" onClick={onDone}>Fortsätt</button>
          </div>
        </div>
      );
    }

    const correct = checked && isCorrect();
    const wrong = checked && !isCorrect();

    return (
      <div className="cf-lesson">
        <div className="cf-ltop">
          <button className="cf-x" onClick={onClose}><Icon name="close" size={18} color="#8C7C6D" /></button>
          <div className="cf-pline"><i style={{ width: progress + '%' }} /></div>
        </div>
        <div className="cf-lbody">
          {step.type === 'intro' && (
            <>
              <div className="cf-kick">Introduktion</div>
              <div className="cf-prompt">{step.title}</div>
              <p style={{ fontSize: 16, lineHeight: 1.6, color: '#5d5046', fontWeight: 500 }}>{step.body}</p>
            </>
          )}
          {step.type === 'choice' && (
            <>
              <div className="cf-kick">Flerval</div>
              <div className="cf-prompt">{step.prompt}</div>
              {step.options.map((o, i) => {
                let cls = 'cf-opt';
                if (!checked && choice === i) cls += ' sel';
                if (checked && o.correct) cls += ' right';
                if (checked && choice === i && !o.correct) cls += ' wrong';
                return (
                  <button key={i} className={cls} onClick={() => !checked && setChoice(i)}>
                    <span className="dot" />{o.t}
                  </button>
                );
              })}
            </>
          )}
          {step.type === 'fill' && (
            <>
              <div className="cf-kick">Dra &amp; släpp</div>
              <div className="cf-prompt">{step.prompt}</div>
              <FillExercise step={step} slots={slots} setSlots={setSlots} locked={checked} />
            </>
          )}
          {step.type === 'truefalse' && (
            <>
              <div className="cf-kick">Sant eller falskt</div>
              <div className="cf-prompt">{step.prompt}</div>
              <div className="cf-tf">
                {[true, false].map((v) => {
                  let cls = '';
                  if (!checked && tf === v) cls = 'sel';
                  if (checked && step.answer === v) cls = 'right';
                  if (checked && tf === v && step.answer !== v) cls = 'wrong';
                  return <button key={String(v)} className={cls} onClick={() => !checked && setTf(v)}>{v ? 'Sant' : 'Falskt'}</button>;
                })}
              </div>
            </>
          )}
        </div>
        <div className="cf-foot">
          {checked && (
            <div className={'cf-fb ' + (correct ? 'ok' : 'no')}>
              <b>{correct ? 'Rätt!' : 'Inte riktigt'}</b>
              {correct ? step.explain : (step.explainWrong || step.explain)}
            </div>
          )}
          <button
            className={'cf-btn' + (correct ? ' ok' : '')}
            disabled={step.type !== 'intro' && !checked && !canCheck()}
            onClick={onPrimary}
          >
            {step.type === 'intro' ? 'Börja' : !checked ? 'Kontrollera' : (idx + 1 >= L.steps.length ? 'Slutför' : 'Fortsätt')}
          </button>
        </div>
      </div>
    );
  }

  // ── COURSE DETAIL ───────────────────────────────────────────
  function CourseDetail({ course, onBack, onStartLesson }) {
    return (
      <div className="cf-cd">
        <div className="cf-cdhead" style={{ background: `linear-gradient(150deg, ${course.color}, ${shade(course.color)})` }}>
          <button className="cf-back" onClick={onBack}><Icon name="arrowRight" size={18} color="#fff" style={{ transform: 'rotate(180deg)' }} /></button>
          <h2>{course.title}</h2>
          <p>{course.subtitle} · {course.lessonsDone}/{course.lessonsTotal} klara</p>
        </div>
        <div className="cf-path">
          {course.lessons.map((l, i) => {
            const playable = course.id === 'eu' && l.state === 'current';
            return (
              <div key={i} className="cf-unit">
                <span className="cf-node" style={{
                  background: l.state === 'locked' ? '#e5ddd3' : course.color,
                  color: l.state === 'locked' ? '#a89a8c' : '#fff',
                }}>
                  {l.state === 'done' ? <Icon name="check" size={20} color="#fff" /> : l.state === 'locked' ? <Icon name="lock" size={17} color="#a89a8c" /> : i + 1}
                </span>
                <div>
                  <div className="ut">{l.t}</div>
                  <div className="us">{l.state === 'done' ? 'Klar' : l.state === 'current' ? 'Pågår' : 'Låst'}</div>
                </div>
                {playable && <button className="cf-startbtn" onClick={onStartLesson}>Starta</button>}
              </div>
            );
          })}
        </div>
      </div>
    );
  }

  function shade(hex) {
    const n = parseInt(hex.slice(1), 16);
    let r = (n >> 16) & 255, g = (n >> 8) & 255, b = n & 255;
    r = Math.round(r * 0.78); g = Math.round(g * 0.74); b = Math.round(b * 0.7);
    return `rgb(${r},${g},${b})`;
  }

  // ── APP SHELL ───────────────────────────────────────────────
  function CivifyApp() {
    const [tab, setTab] = useState('learn');
    const [course, setCourse] = useState(null);
    const [lesson, setLesson] = useState(false);

    const Home = window.CivifyHome, Explore = window.CivifyExplore, Profile = window.CivifyProfile;

    const openCourse = (c) => setCourse(c);
    const startLesson = () => setLesson(true);

    return (
      <div className="cf-app">
        {tab === 'learn' && <Home onOpenCourse={openCourse} onStartLesson={startLesson} />}
        {tab === 'explore' && <Explore onOpenCourse={openCourse} />}
        {tab === 'profile' && <Profile />}

        {course && !lesson && (
          <CourseDetail course={course} onBack={() => setCourse(null)} onStartLesson={startLesson} />
        )}
        {lesson && (
          <Lesson onClose={() => setLesson(false)} onDone={() => { setLesson(false); setCourse(null); setTab('profile'); }} />
        )}

        {!lesson && (
          <div className="cf-tabs">
            {[['learn', 'home', 'Lär dig'], ['explore', 'compass', 'Utforska'], ['profile', 'person', 'Profil']].map(([k, ic, lbl]) => (
              <button key={k} className={'cf-tab' + (tab === k ? ' on' : '')} onClick={() => { setTab(k); setCourse(null); }}>
                <Icon name={ic} size={23} color={tab === k ? '#F2570A' : '#8C7C6D'} stroke={tab === k ? 2.4 : 2} />
                {lbl}
              </button>
            ))}
          </div>
        )}
      </div>
    );
  }

  window.CivifyApp = CivifyApp;
})();
