/* prototype/views/mastery.jsx
   LerenMasteryView — mastery dashboard: per vak + onderwerp.
   Route: /leren/beheersing
*/

(function () {
  const { useState } = React;

  /* ─── Mock data ───────────────────────────────────────────── */
  const MASTERY_DATA = [
    {
      subject: 'biologie',
      topics: [
        { name: 'Celdeling & mitose',       masteryLevel: 4, status: 'beheerst',      lastPracticed: 'vandaag · 14:30' },
        { name: 'Meiose & voortplanting',    masteryLevel: 3, status: 'in-de-groei',   lastPracticed: '1 dag geleden' },
        { name: 'Osmose & diffusie',         masteryLevel: 4, status: 'beheerst',      lastPracticed: 'vandaag · 14:32' },
        { name: 'Plantencel vs dierlijke cel', masteryLevel: 2, status: 'aandacht-nodig', lastPracticed: '5 dagen geleden' },
        { name: 'Organellen & functies',     masteryLevel: 3, status: 'in-de-groei',   lastPracticed: '2 dagen geleden' },
        { name: 'Fotosynthese basics',       masteryLevel: 4, status: 'beheerst',      lastPracticed: 'gisteren' },
      ],
    },
    {
      subject: 'wiskunde',
      topics: [
        { name: 'Kwadratische vergelijkingen', masteryLevel: 2, status: 'aandacht-nodig', lastPracticed: '6 dagen geleden' },
        { name: 'Asymptoten & limieten',       masteryLevel: 3, status: 'in-de-groei',   lastPracticed: '3 dagen geleden' },
        { name: 'ABC-formule',                 masteryLevel: 4, status: 'beheerst',      lastPracticed: 'gisteren' },
        { name: 'Functies & grafieken',        masteryLevel: 3, status: 'in-de-groei',   lastPracticed: '2 dagen geleden' },
        { name: 'Stelsels van vergelijkingen', masteryLevel: 1, status: 'aandacht-nodig', lastPracticed: '8 dagen geleden' },
      ],
    },
    {
      subject: 'engels',
      topics: [
        { name: 'Past Perfect tense',       masteryLevel: 3, status: 'in-de-groei',   lastPracticed: '1 dag geleden' },
        { name: 'Narrative tenses',         masteryLevel: 4, status: 'beheerst',      lastPracticed: 'vandaag · 09:15' },
        { name: 'Onregelmatige werkwoorden', masteryLevel: 4, status: 'beheerst',     lastPracticed: 'gisteren' },
        { name: 'Reading comprehension',    masteryLevel: 2, status: 'aandacht-nodig', lastPracticed: '7 dagen geleden' },
        { name: 'Woordenschat U5',          masteryLevel: 3, status: 'in-de-groei',   lastPracticed: '3 dagen geleden' },
        { name: 'Luistervaardigheid',       masteryLevel: 4, status: 'beheerst',      lastPracticed: 'gisteren' },
      ],
    },
    {
      subject: 'geschiedenis',
      topics: [
        { name: 'Industriële Revolutie — oorzaken', masteryLevel: 3, status: 'in-de-groei',   lastPracticed: '2 dagen geleden' },
        { name: 'Verlichting — kernideeën',          masteryLevel: 2, status: 'aandacht-nodig', lastPracticed: '9 dagen geleden' },
        { name: 'Napoleontische tijd',               masteryLevel: 4, status: 'beheerst',      lastPracticed: 'gisteren' },
        { name: 'Kolonialisme & handel',             masteryLevel: 1, status: 'aandacht-nodig', lastPracticed: '11 dagen geleden' },
        { name: 'Revoluties 1789–1848',              masteryLevel: 3, status: 'in-de-groei',   lastPracticed: '4 dagen geleden' },
        { name: 'Technologische veranderingen',      masteryLevel: 4, status: 'beheerst',      lastPracticed: 'gisteren' },
        { name: 'Sociale klassen 19e eeuw',          masteryLevel: 3, status: 'in-de-groei',   lastPracticed: '3 dagen geleden' },
      ],
    },
  ];

  // Global stats
  const allTopics = MASTERY_DATA.flatMap(v => v.topics);
  const totalTopics = allTopics.length;
  const beheerstCount = allTopics.filter(t => t.status === 'beheerst').length;
  const inDeGroeiCount = allTopics.filter(t => t.status === 'in-de-groei').length;
  const aandachtCount = allTopics.filter(t => t.status === 'aandacht-nodig').length;

  // Per-vak mastery percentages (beheerst + in-de-groei weighted)
  const vakProgress = MASTERY_DATA.map(v => {
    const pct = Math.round(
      (v.topics.filter(t => t.status === 'beheerst').length * 100
        + v.topics.filter(t => t.status === 'in-de-groei').length * 55)
      / v.topics.length
    );
    return { subject: v.subject, pct: Math.min(pct, 100) };
  });

  /* ─── Status helpers ──────────────────────────────────────── */
  function statusColor(status, dark) {
    switch (status) {
      case 'beheerst':      return dark ? '#22C55E' : '#15803D';
      case 'in-de-groei':   return dark ? '#FBBF24' : '#B45309';
      case 'aandacht-nodig': return dark ? '#F87171' : '#DC2626';
      default:              return dark ? '#94A3B8' : '#64748B';
    }
  }
  function statusLabel(status) {
    switch (status) {
      case 'beheerst':      return 'Beheerst';
      case 'in-de-groei':   return 'In de groei';
      case 'aandacht-nodig': return 'Aandacht nodig';
      default:              return status;
    }
  }
  function statusBg(status, dark) {
    switch (status) {
      case 'beheerst':      return dark ? 'rgba(34,197,94,0.12)'  : 'rgba(21,128,61,0.08)';
      case 'in-de-groei':   return dark ? 'rgba(251,191,36,0.12)' : 'rgba(180,83,9,0.08)';
      case 'aandacht-nodig': return dark ? 'rgba(248,113,113,0.12)' : 'rgba(220,38,38,0.08)';
      default:              return 'transparent';
    }
  }

  /* ─── MasteryDots (4-level) ───────────────────────────────── */
  function MasteryDotsInline({ t, level }) {
    const dark = t.mode === 'dark';
    const colors = ['#F87171','#FBBF24','#22C55E','#22D3EE'];
    return (
      <div style={{ display: 'flex', gap: 3 }}>
        {[1,2,3,4].map(i => (
          <span key={i} style={{
            width: 8, height: 8, borderRadius: 999,
            background: i <= level
              ? colors[level - 1]
              : (dark ? 'rgba(255,255,255,0.10)' : 'rgba(0,0,0,0.10)'),
            border: i <= level ? 'none' : `1px solid ${dark ? 'rgba(255,255,255,0.12)' : 'rgba(0,0,0,0.12)'}`,
          }} />
        ))}
      </div>
    );
  }

  /* ─── TopicRow ────────────────────────────────────────────── */
  function TopicRow({ t, topic, navigate }) {
    const dark = t.mode === 'dark';
    const sc = statusColor(topic.status, dark);
    const isAandacht = topic.status === 'aandacht-nodig';
    return (
      <div style={{
        display: 'flex', alignItems: 'center', gap: 10,
        padding: '10px 12px', borderRadius: 8,
        background: t.cardSunken, border: `1px solid ${t.border}`,
      }}>
        {isAandacht && (
          <PI name="alert-triangle" size={13} color={sc} strokeWidth={2.4} style={{ flexShrink: 0 }} />
        )}
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
            <span style={{ fontSize: 13, color: t.fg, fontWeight: 700, lineHeight: 1.3 }}>
              {topic.name}
            </span>
            <span style={{
              fontSize: 10, fontWeight: 800, letterSpacing: 0.3, textTransform: 'uppercase',
              color: sc, background: statusBg(topic.status, dark),
              border: `1px solid ${sc}30`,
              padding: '1px 7px', borderRadius: 999, whiteSpace: 'nowrap',
            }}>
              {statusLabel(topic.status)}
            </span>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 4 }}>
            <MasteryDotsInline t={t} level={topic.masteryLevel} />
            <span style={{ fontSize: 10.5, color: t.fgMute, fontWeight: 600 }}>
              {topic.lastPracticed}
            </span>
          </div>
        </div>
        <button
          onClick={() => navigate('review')}
          style={{
            flexShrink: 0,
            padding: '5px 11px', borderRadius: 7,
            background: 'transparent',
            border: `1px solid ${t.border}`,
            color: t.fgDim, fontSize: 11.5, fontWeight: 800,
            cursor: 'pointer', fontFamily: 'Nunito',
            whiteSpace: 'nowrap',
          }}>
          Oefen nu
        </button>
      </div>
    );
  }

  /* ─── VakBlock (expandable) ───────────────────────────────── */
  function VakBlock({ t, vak, navigate }) {
    const dark = t.mode === 'dark';
    const [open, setOpen] = useState(true);
    const subjectHex = (window.SUBJECTS && window.SUBJECTS[vak.subject]) || t.primary;
    const beheerstN = vak.topics.filter(top => top.status === 'beheerst').length;
    const totalN = vak.topics.length;

    return (
      <div style={{
        background: t.card, border: `1px solid ${t.border}`,
        borderRadius: 10, overflow: 'hidden',
      }}>
        {/* Header */}
        <button
          onClick={() => setOpen(v => !v)}
          style={{
            width: '100%', display: 'flex', alignItems: 'center', gap: 10,
            padding: '13px 16px',
            background: 'transparent', border: 'none', cursor: 'pointer',
            borderBottom: open ? `1px solid ${t.border}` : 'none',
            textAlign: 'left',
          }}>
          <SubjectChip t={t} subject={vak.subject} size="md" iconOnly />
          <span style={{
            fontFamily: 'Fredoka One', fontSize: 16, color: t.fg,
            lineHeight: 1.2, flex: 1, textTransform: 'capitalize',
          }}>
            {vak.subject.charAt(0).toUpperCase() + vak.subject.slice(1)}
          </span>
          <span style={{ fontSize: 11.5, color: t.fgMute, fontWeight: 700, marginRight: 8 }}>
            {beheerstN} / {totalN} beheerst
          </span>
          <PI
            name={open ? 'chevron-up' : 'chevron-down'}
            size={16} color={t.fgMute} strokeWidth={2.4}
          />
        </button>

        {/* Topics list */}
        {open && (
          <div style={{ padding: '12px 14px', display: 'flex', flexDirection: 'column', gap: 7 }}>
            {vak.topics.map((topic, i) => (
              <TopicRow key={i} t={t} topic={topic} navigate={navigate} />
            ))}
          </div>
        )}
      </div>
    );
  }

  /* ─── History chart (SVG line) ──────────────────────────── */
  function HistoryChart({ t }) {
    const dark = t.mode === 'dark';
    const points = [40, 48, 55, 62]; // beheerste onderwerpen over 4 weken
    const labels = ['4w geleden','3w geleden','2w geleden','nu'];
    const max = 80; const min = 20;
    const W = 320; const H = 80;
    const px = (i) => Math.round((i / (points.length - 1)) * (W - 32)) + 16;
    const py = (v) => Math.round(H - ((v - min) / (max - min)) * (H - 20)) - 4;

    const pathD = points.map((v, i) => `${i === 0 ? 'M' : 'L'} ${px(i)} ${py(v)}`).join(' ');
    const areaD = `M ${px(0)} ${H} ${points.map((v, i) => `L ${px(i)} ${py(v)}`).join(' ')} L ${px(points.length - 1)} ${H} Z`;

    return (
      <div style={{
        background: t.card, border: `1px solid ${t.border}`,
        borderRadius: 10, padding: '16px 18px',
        display: 'flex', flexDirection: 'column', gap: 12,
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <PI name="trending-up" size={14} color={t.fgDim} strokeWidth={2.4} />
          <span style={{ fontFamily: 'Fredoka One', fontSize: 14, color: t.fg }}>
            Voortgang afgelopen 4 weken
          </span>
        </div>
        <div style={{ position: 'relative', overflowX: 'auto' }}>
          <svg width={W} height={H} style={{ display: 'block' }}>
            <defs>
              <linearGradient id="chartFill" x1="0" y1="0" x2="0" y2="1">
                <stop offset="0%" stopColor={t.primary} stopOpacity={dark ? 0.28 : 0.18} />
                <stop offset="100%" stopColor={t.primary} stopOpacity={0.02} />
              </linearGradient>
            </defs>
            {/* Grid lines */}
            {[40, 60, 80].map(v => (
              <line key={v}
                x1={16} y1={py(v)} x2={W - 16} y2={py(v)}
                stroke={dark ? 'rgba(255,255,255,0.07)' : 'rgba(0,0,0,0.06)'}
                strokeDasharray="3,3"
              />
            ))}
            {/* Area fill */}
            <path d={areaD} fill="url(#chartFill)" />
            {/* Line */}
            <path d={pathD} fill="none" stroke={t.primary} strokeWidth={2.2} strokeLinejoin="round" strokeLinecap="round" />
            {/* Dots */}
            {points.map((v, i) => (
              <circle key={i} cx={px(i)} cy={py(v)} r={3.5}
                fill={t.primary} stroke={t.card} strokeWidth={2} />
            ))}
            {/* Value labels */}
            {points.map((v, i) => (
              <text key={i} x={px(i)} y={py(v) - 8}
                textAnchor="middle" fontSize={9} fontWeight="800"
                fill={dark ? '#7DD3FC' : '#0369A1'}>{v}</text>
            ))}
          </svg>
          <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 4 }}>
            {labels.map((l, i) => (
              <span key={i} style={{ fontSize: 9.5, color: t.fgMute, fontWeight: 700, textAlign: 'center', flex: 1 }}>
                {l}
              </span>
            ))}
          </div>
        </div>
        <div style={{ fontSize: 11.5, color: t.fgDim, fontWeight: 600 }}>
          Van 40 naar <b style={{ color: t.fg }}>62 beheerste onderwerpen</b> in 4 weken. Goed op weg!
        </div>
      </div>
    );
  }

  /* ─── History paywall (for Free users) ────────────────────── */
  function HistoryPaywall({ t }) {
    const dark = t.mode === 'dark';
    return (
      <div style={{
        background: t.card, border: `1px solid ${t.border}`,
        borderRadius: 10, padding: '20px 22px',
        display: 'flex', alignItems: 'center', gap: 16,
      }}>
        <div style={{
          width: 40, height: 40, borderRadius: 10, flexShrink: 0,
          background: t.primaryDim, color: t.primary,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <PI name="lock" size={18} color={t.primary} strokeWidth={2.2} />
        </div>
        <div style={{ flex: 1 }}>
          <div style={{ fontFamily: 'Fredoka One', fontSize: 16, color: t.fg, lineHeight: 1.25, marginBottom: 4 }}>
            Ontgrendel geschiedenis met Premium
          </div>
          <div style={{ fontSize: 12.5, color: t.fgDim, fontWeight: 600, lineHeight: 1.5 }}>
            Zie hoe je beheersing over de weken is gegroeid en ontdek patronen in je leergedrag.
          </div>
        </div>
        <button style={{
          padding: '8px 16px', borderRadius: 8,
          background: t.primary, border: 'none',
          color: dark ? '#0A0F1E' : '#FFFFFF',
          fontSize: 12, fontWeight: 800, cursor: 'pointer',
          fontFamily: 'Nunito', flexShrink: 0, whiteSpace: 'nowrap',
        }}>
          Naar Premium
        </button>
      </div>
    );
  }

  /* ─── MasteryProgressWidget (exportable for chapter view) ── */
  function MasteryProgressWidget({ t, subject, progress }) {
    const dark = t.mode === 'dark';
    const hex = (window.SUBJECTS && window.SUBJECTS[subject]) || t.primary;
    return (
      <div style={{
        display: 'flex', alignItems: 'center', gap: 10,
        padding: '8px 10px', borderRadius: 8,
        background: t.cardSunken, border: `1px solid ${t.border}`,
      }}>
        <SubjectChip t={t} subject={subject} size="sm" iconOnly />
        <div style={{ flex: 1 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 4 }}>
            <span style={{ fontSize: 11, color: t.fgMute, fontWeight: 800, letterSpacing: 0.3, textTransform: 'capitalize' }}>
              {subject}
            </span>
            <span style={{ fontSize: 12, fontFamily: 'Fredoka One', color: t.fg }}>{progress}%</span>
          </div>
          <div style={{
            height: 5, borderRadius: 999,
            background: dark ? 'rgba(255,255,255,0.08)' : 'rgba(0,0,0,0.07)',
            overflow: 'hidden',
          }}>
            <div style={{ width: `${progress}%`, height: '100%', background: hex, borderRadius: 999 }} />
          </div>
        </div>
      </div>
    );
  }

  /* ─── LerenMasteryView ────────────────────────────────────── */
  function LerenMasteryView({ t, navigate, hasFeature, plan }) {
    const dark = t.mode === 'dark';
    const canSeeHistory = typeof hasFeature === 'function'
      ? hasFeature('mastery-history')
      : plan === 'premium' || plan === 'premium-plus';

    const totalDone = beheerstCount + inDeGroeiCount;
    const subtitle = `${beheerstCount} van ${totalTopics} onderwerpen beheerst · 4 vakken`;

    const statCards = [
      { icon: 'check-circle', label: 'Beheerst',         value: beheerstCount,   sub: `van ${totalTopics} onderwerpen`, accent: dark ? '#22C55E' : '#15803D' },
      { icon: 'trending-up',  label: 'In de groei',      value: inDeGroeiCount,  sub: 'bijna beheerst',                 accent: dark ? '#FBBF24' : '#B45309' },
      { icon: 'alert-circle', label: 'Aandacht nodig',   value: aandachtCount,   sub: 'lagere beheersing',              accent: dark ? '#F87171' : '#DC2626' },
      { icon: 'calendar',     label: 'Sessies deze week', value: 14,             sub: '±8 min per sessie',              accent: t.primary },
    ];

    return (
      <LerenPage
        t={t}
        title="Beheersing"
        subtitle={subtitle}
        url="snapsnel.nl/leren/beheersing"
        activeNav="leren"
        snaps={1240} streak={12} level={7}
      >
        <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>

          {/* ── Hero stat cards ── */}
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12 }}>
            {statCards.map((s, i) => (
              <div key={i} style={{
                background: t.card, border: `1px solid ${t.border}`,
                borderRadius: 10, padding: '14px 16px',
                display: 'flex', flexDirection: 'column', gap: 6,
              }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
                  <PI name={s.icon} size={13} color={s.accent} strokeWidth={2.4} />
                  <span style={{ fontSize: 10, color: t.fgMute, fontWeight: 800, letterSpacing: 0.4, textTransform: 'uppercase' }}>
                    {s.label}
                  </span>
                </div>
                <div style={{
                  fontFamily: 'Fredoka One', fontSize: 26, color: s.accent,
                  letterSpacing: '-0.005em', lineHeight: 1.1,
                }}>{s.value}</div>
                <div style={{ fontSize: 11, color: t.fgDim, fontWeight: 600 }}>{s.sub}</div>
              </div>
            ))}
          </div>

          {/* ── Per-vak progress bars ── */}
          <div style={{
            background: t.card, border: `1px solid ${t.border}`,
            borderRadius: 10, padding: '16px 18px',
            display: 'flex', flexDirection: 'column', gap: 12,
          }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <PI name="bar-chart-2" size={14} color={t.fgDim} strokeWidth={2.4} />
              <span style={{ fontFamily: 'Fredoka One', fontSize: 14, color: t.fg }}>
                Beheersing per vak
              </span>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
              {vakProgress.map((v, i) => {
                const hex = (window.SUBJECTS && window.SUBJECTS[v.subject]) || t.primary;
                return (
                  <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                    <SubjectChip t={t} subject={v.subject} size="sm" iconOnly />
                    <span style={{ fontSize: 12, color: t.fg, fontWeight: 700, width: 90, textTransform: 'capitalize', flexShrink: 0 }}>
                      {v.subject.charAt(0).toUpperCase() + v.subject.slice(1)}
                    </span>
                    <div style={{
                      flex: 1, height: 7, borderRadius: 999,
                      background: dark ? 'rgba(255,255,255,0.08)' : 'rgba(0,0,0,0.07)',
                      overflow: 'hidden',
                    }}>
                      <div style={{ width: `${v.pct}%`, height: '100%', background: hex, borderRadius: 999 }} />
                    </div>
                    <span style={{ fontSize: 12, fontFamily: 'Fredoka One', color: t.fg, width: 36, textAlign: 'right', flexShrink: 0 }}>
                      {v.pct}%
                    </span>
                  </div>
                );
              })}
            </div>
          </div>

          {/* ── Per-vak expandable blocks ── */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            {MASTERY_DATA.map((vak, i) => (
              <VakBlock key={i} t={t} vak={vak} navigate={navigate} />
            ))}
          </div>

          {/* ── History chart or paywall ── */}
          {canSeeHistory
            ? <HistoryChart t={t} />
            : <HistoryPaywall t={t} />
          }

          {/* ── CTA row ── */}
          <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
            <BtnPrimary t={t} icon="repeat" onClick={() => navigate('review')}>
              Begin herhaling van aandacht-nodig-onderwerpen
            </BtnPrimary>
            <BtnGhost t={t} icon="book-open" onClick={() => navigate('library')}>
              Naar Bibliotheek
            </BtnGhost>
          </div>

        </div>
      </LerenPage>
    );
  }

  /* Expose widget for potential reuse by chapter view */
  window.MasteryProgressWidget = MasteryProgressWidget;
  window.LerenMasteryView = LerenMasteryView;
})();
