// Student Model · Knowledge Map · Weak Spots · Readiness

// -------- Student Model --------
function RadarChart({ values, size = 280 }) {
  const axes = values.length;
  const cx = size / 2, cy = size / 2, R = size * 0.40;
  const angle = i => -Math.PI/2 + i * 2*Math.PI/axes;
  const pt = (i, v) => [cx + Math.cos(angle(i)) * R * v, cy + Math.sin(angle(i)) * R * v];

  const rings = [0.25, 0.5, 0.75, 1.0];
  const poly = values.map((v, i) => pt(i, v.value/100).join(',')).join(' ');

  return <svg viewBox={`0 0 ${size} ${size}`} width={size} height={size}>
    {rings.map((r, i) => <polygon key={i}
      points={Array.from({length: axes}, (_, j) => pt(j, r).join(',')).join(' ')}
      fill="none" stroke="var(--border)" strokeWidth="1" />)}
    {values.map((_, i) => {
      const [x, y] = pt(i, 1);
      return <line key={i} x1={cx} y1={cy} x2={x} y2={y} stroke="var(--border)" strokeWidth="1" />;
    })}
    <polygon points={poly} fill="rgba(15,76,92,0.18)" stroke="var(--binah-deep-teal)" strokeWidth="2" />
    {values.map((v, i) => {
      const [x, y] = pt(i, v.value/100);
      return <circle key={i} cx={x} cy={y} r="4" fill="var(--binah-saffron)" />;
    })}
    {values.map((v, i) => {
      const [x, y] = pt(i, 1.15);
      return <text key={i} x={x} y={y+4} textAnchor="middle"
        style={{ fontFamily: 'var(--font-body)', fontSize: 11, fontWeight: 500, fill: 'var(--fg-2)' }}>
        {v.label}
      </text>;
    })}
  </svg>;
}

function StudentModel({ rtl, t }) {
  const traits = rtl ? [
    { label: 'הבנה מושגית', value: 78 }, { label: 'זיכרון', value: 62 },
    { label: 'חישוב', value: 85 }, { label: 'קריאה מהירה', value: 54 },
    { label: 'עברית', value: 92 }, { label: 'יישום', value: 71 },
  ] : [
    { label: 'Conceptual', value: 78 }, { label: 'Memory', value: 62 },
    { label: 'Calculation', value: 85 }, { label: 'Skim reading', value: 54 },
    { label: 'Hebrew', value: 92 }, { label: 'Application', value: 71 },
  ];

  const strengths = rtl
    ? ['דוגמאות מספריות לפני תאוריה', 'סכמות ויזואליות', 'סשני 25 דק’', 'שאלות קצרות מרובות']
    : ['Numerical examples before theory', 'Visual diagrams', '25-min focus sessions', 'Short, frequent questions'];
  const weaknesses = rtl
    ? ['טקסט ארוך ללא תתי-כותרות', 'שאלות מרובות-שלבים ארוכות', 'חומר חדש אחרי 22:00']
    : ['Long prose without sub-headers', 'Long multi-step questions', 'New material after 22:00'];

  return (
    <div style={{ padding: 32, maxWidth: 1240, margin: '0 auto' }}>
      <div style={{ marginBottom: 20 }}>
        <div className="binah-eyebrow">{t('updated', 'עודכן לאחרונה · 18.04.2026', 'LAST UPDATED · 18.04.2026')}</div>
        <h1 style={{ margin: '6px 0 0', fontSize: 30, fontWeight: 700,
                     fontFamily: rtl ? 'var(--font-he)' : 'var(--font-display)',
                     color: 'var(--fg-1)', letterSpacing: '-0.015em' }}>
          {t('title', 'מודל הסטודנט — סתיו א.', 'Student Model — Stav A.')}
        </h1>
        <p style={{ color: 'var(--fg-3)', fontSize: 14, margin: '6px 0 0',
                    fontFamily: rtl ? 'var(--font-he)' : 'var(--font-body)' }}>
          {t('sub', 'מודל חי של נקודות חוזק וחולשה. גרסה 10 · מבוסס על 124 אינטראקציות.', 'A living model of your strengths and weaknesses. Version 10 · 124 interactions.')}
        </p>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
        <Card padding={24}>
          <h3 style={{ margin: '0 0 12px', fontSize: 15, fontWeight: 600,
                       fontFamily: rtl ? 'var(--font-he)' : 'var(--font-display)' }}>
            {t('radar', 'פרופיל יכולות', 'Ability profile')}
          </h3>
          <div style={{ display: 'flex', justifyContent: 'center' }}>
            <RadarChart values={traits} size={300} />
          </div>
        </Card>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <Card padding={20}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
              <Badge variant="positive" dot>{t('str', 'מה עובד', 'What works')}</Badge>
            </div>
            <ul style={{ margin: 0, padding: 0, listStyle: 'none',
                         fontFamily: rtl ? 'var(--font-he)' : 'var(--font-body)' }}>
              {strengths.map(s => <li key={s} style={{ padding: '8px 0', borderTop: '1px solid var(--divider)',
                color: 'var(--fg-1)', fontSize: 14, display: 'flex', alignItems: 'center', gap: 10 }}>
                <Icon name="check" size={14} style={{ color: 'var(--positive-fg)' }} /> {s}
              </li>)}
            </ul>
          </Card>
          <Card padding={20}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
              <Badge variant="highlight" dot>{t('weak', 'מה עוד צריך עבודה', 'Still growing')}</Badge>
            </div>
            <ul style={{ margin: 0, padding: 0, listStyle: 'none',
                         fontFamily: rtl ? 'var(--font-he)' : 'var(--font-body)' }}>
              {weaknesses.map(s => <li key={s} style={{ padding: '8px 0', borderTop: '1px solid var(--divider)',
                color: 'var(--fg-1)', fontSize: 14, display: 'flex', alignItems: 'center', gap: 10 }}>
                <Icon name="activity" size={14} style={{ color: 'var(--highlight-fg)' }} /> {s}
              </li>)}
            </ul>
          </Card>
        </div>
      </div>
    </div>
  );
}

// -------- Knowledge Map --------
function KnowledgeMap({ rtl, t }) {
  const courses = rtl
    ? ['חשבונאות III', 'מיסים II', 'ביקורת', 'ניהולית', 'מימון']
    : ['Acc III', 'Taxation II', 'Auditing', 'Managerial', 'Finance'];
  const topics = rtl
    ? ['IFRS 16', 'Lessor', 'מדידה מחודשת', 'IAS 19', 'FX', 'פריטים השקעה', 'ECL', 'Dividends']
    : ['IFRS 16', 'Lessor', 'Re-meas.', 'IAS 19', 'FX', 'Inv. Items', 'ECL', 'Dividends'];

  // deterministic mastery grid
  const grid = [
    [100,85,65,20,40,85,75,90],
    [75,100,90,35,55,85,60,70],
    [100,85,45,40,55,75,80,60],
    [55,85,40,20,55,45,70,70],
    [85,55,20,45,45,20,40,60],
  ];
  const colour = v => {
    if (v >= 85) return '#0F4C5C';
    if (v >= 70) return '#9FD4C0';
    if (v >= 55) return '#D1EADF';
    if (v >= 40) return '#F4A261';
    if (v >= 25) return '#FBDBBF';
    return '#C96F53';
  };

  return (
    <div style={{ padding: 32, maxWidth: 1240, margin: '0 auto' }}>
      <div style={{ marginBottom: 20 }}>
        <h1 style={{ margin: 0, fontSize: 30, fontWeight: 700,
                     fontFamily: rtl ? 'var(--font-he)' : 'var(--font-display)',
                     color: 'var(--fg-1)', letterSpacing: '-0.015em' }}>
          {t('title', 'מפת הידע', 'Knowledge Map')}
        </h1>
        <p style={{ color: 'var(--fg-3)', fontSize: 14, margin: '6px 0 0',
                    fontFamily: rtl ? 'var(--font-he)' : 'var(--font-body)' }}>
          {t('sub', 'שליטה לפי קורס × נושא. לחץ על תא לפרטים.',
                    'Mastery by course × topic. Click a cell for details.')}
        </p>
      </div>
      <Card padding={24}>
        <div style={{ display: 'flex', gap: 10, direction: rtl ? 'rtl' : 'ltr' }}>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6, paddingTop: 34 }}>
            {courses.map(c => (
              <div key={c} style={{ height: 44, display: 'flex', alignItems: 'center',
                padding: '0 12px', fontSize: 12, fontWeight: 500, color: 'var(--fg-2)',
                fontFamily: rtl ? 'var(--font-he)' : 'var(--font-body)',
                justifyContent: rtl ? 'flex-start' : 'flex-end' }}>{c}</div>
            ))}
          </div>
          <div style={{ flex: 1, overflow: 'auto' }}>
            <div style={{ display: 'grid', gridTemplateColumns: `repeat(${topics.length}, 1fr)`, gap: 6, marginBottom: 6 }}>
              {topics.map(tpk => <div key={tpk} style={{
                fontSize: 11, color: 'var(--fg-3)', textAlign: 'center',
                padding: '8px 0', fontWeight: 500,
                fontFamily: rtl ? 'var(--font-he)' : 'var(--font-body)',
              }}>{tpk}</div>)}
            </div>
            {grid.map((row, i) => (
              <div key={i} style={{ display: 'grid', gridTemplateColumns: `repeat(${topics.length}, 1fr)`, gap: 6, marginBottom: 6 }}>
                {row.map((v, j) => (
                  <div key={j} style={{
                    height: 44, borderRadius: 8, background: colour(v),
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    color: v >= 55 && v < 85 ? 'var(--fg-1)' : (v >= 85 ? '#fff' : '#fff'),
                    fontFamily: 'var(--font-display)', fontVariantNumeric: 'tabular-nums',
                    fontSize: 11, fontWeight: 600, cursor: 'pointer',
                    transition: 'transform 200ms cubic-bezier(.2,.8,.2,1)',
                  }} onMouseEnter={e => e.currentTarget.style.transform='scale(1.08)'}
                     onMouseLeave={e => e.currentTarget.style.transform=''}>
                    {v}
                  </div>
                ))}
              </div>
            ))}
          </div>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 18,
                      fontSize: 11, fontFamily: 'var(--font-body)', color: 'var(--fg-3)' }}>
          <span>{t('weak', 'חלש', 'Weak')}</span>
          {['#C96F53','#FBDBBF','#F4A261','#D1EADF','#9FD4C0','#0F4C5C'].map(c =>
            <span key={c} style={{ width: 20, height: 10, borderRadius: 3, background: c }} />
          )}
          <span>{t('master', 'שליטה', 'Mastered')}</span>
        </div>
      </Card>
    </div>
  );
}

// -------- Weak Spots --------
function WeakSpots({ rtl, t }) {
  const items = rtl ? [
    { sev: 'hi',  tag: 'מיסים II',   title: 'שיעורי מס ופחת',         gap: 'חוזר על עצמו ב-3 קורסים שונים. פער מושגי ברור.', cat: 'מושגי', dt: '16.04' },
    { sev: 'med', tag: 'מיסים II',   title: 'החלפת נוסחאות פחת',        gap: 'בדרך-כלל מחליף בין דגם קו-ישר לדגם יורד.',   cat: 'זיכרון', dt: '14.04' },
    { sev: 'low', tag: 'מיסים II',   title: 'הבנת פסק-דין השקעה',       gap: 'פער קל בקריאה מהירה של סעיפים.',            cat: 'קריאה', dt: '12.04' },
    { sev: 'med', tag: 'ביקורת',     title: 'Sampling — PPS',           gap: 'חישוב אינטרוואל מבלבל כשערך אוכלוסיה גדול.',  cat: 'חישוב', dt: '09.04' },
  ] : [
    { sev: 'hi',  tag: 'Taxation II', title: 'Tax rates & depreciation', gap: 'Recurring across 3 courses — clear conceptual gap.', cat: 'concept', dt: '16.04' },
    { sev: 'med', tag: 'Taxation II', title: 'Depreciation formulas',    gap: 'Mixes up straight-line vs. declining-balance.',       cat: 'memory',  dt: '14.04' },
    { sev: 'low', tag: 'Taxation II', title: 'Investment-ruling parse',  gap: 'Minor slip in fast-reading clause language.',         cat: 'reading', dt: '12.04' },
    { sev: 'med', tag: 'Auditing',    title: 'Sampling — PPS',           gap: 'Interval calc slips when population is large.',       cat: 'calc',    dt: '09.04' },
  ];
  const sevDot  = { hi: '#C96F53', med: '#F4A261', low: '#9FD4C0' };
  const sevPill = { hi: 'danger', med: 'highlight', low: 'positive' };
  const sevText = { hi: t('hi','גבוה','High'), med: t('med','בינוני','Med'), low: t('low','נמוך','Low') };

  return (
    <div style={{ padding: 32, maxWidth: 1040, margin: '0 auto' }}>
      <div style={{ marginBottom: 20, display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between' }}>
        <div>
          <h1 style={{ margin: 0, fontSize: 30, fontWeight: 700,
                       fontFamily: rtl ? 'var(--font-he)' : 'var(--font-display)',
                       color: 'var(--fg-1)', letterSpacing: '-0.015em' }}>
            {t('title', 'נקודות חולשה — יומן', 'Weak Spots — Ledger')}
          </h1>
          <p style={{ color: 'var(--fg-3)', fontSize: 14, margin: '6px 0 0',
                      fontFamily: rtl ? 'var(--font-he)' : 'var(--font-body)' }}>
            {t('sub', 'יומן Append-Only. פערים לא נעלמים — הם נסגרים במפורש.',
                      'Append-only log. Gaps don’t disappear — they’re closed explicitly.')}
          </p>
        </div>
        <Button variant="highlight" iconLeft="sparkle">{t('plan', 'תכנן ספרינט סגירה', 'Plan closure sprint')}</Button>
      </div>

      <Card padding={16} style={{
        background: 'linear-gradient(135deg, rgba(244,162,97,0.14) 0%, rgba(15,76,92,0.06) 100%)',
        marginBottom: 16,
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <Icon name="activity" size={20} style={{ color: 'var(--highlight-fg)' }} />
          <div style={{ flex: 1 }}>
            <div style={{ fontFamily: rtl ? 'var(--font-he)' : 'var(--font-display)',
                          fontWeight: 600, fontSize: 14, color: 'var(--fg-1)' }}>
              {t('xc', 'דפוס חוצה-קורסים', 'Cross-course pattern')}
            </div>
            <div style={{ fontSize: 13, color: 'var(--fg-2)', marginTop: 2,
                          fontFamily: rtl ? 'var(--font-he)' : 'var(--font-body)' }}>
              {t('xcb',
                'בלבול בין Equity ל-Liability מופיע ב-3 קורסים. פתחו תוכנית תיקון 7-ימית.',
                'Equity vs. Liability confusion appears in 3 courses. Open a 7-day fix plan.')}
            </div>
          </div>
          <Button variant="secondary" size="sm">{t('open', 'פתח', 'Open')}</Button>
        </div>
      </Card>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        {items.map((it, i) => (
          <div key={i} style={{
            display: 'flex', gap: 14, background: 'var(--surface)',
            borderRadius: 16, padding: '14px 18px', boxShadow: 'var(--elev-1)',
            position: 'relative',
          }}>
            <div style={{ position: 'absolute', [rtl ? 'right' : 'left']: -4, top: 16,
              width: 8, height: 8, borderRadius: 999, background: sevDot[it.sev] }} />
            <div style={{ flex: 1 }}>
              <div style={{ display: 'flex', gap: 8, alignItems: 'center', marginBottom: 4 }}>
                <Badge variant="accent">{it.tag}</Badge>
                <span style={{ fontSize: 11, color: 'var(--fg-3)' }}>{it.dt}</span>
              </div>
              <div style={{ fontFamily: rtl ? 'var(--font-he)' : 'var(--font-display)',
                            fontSize: 15, fontWeight: 600, color: 'var(--fg-1)', marginTop: 4 }}>{it.title}</div>
              <div style={{ fontSize: 13, color: 'var(--fg-3)', marginTop: 4, lineHeight: 1.55,
                            fontFamily: rtl ? 'var(--font-he)' : 'var(--font-body)' }}>{it.gap}</div>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8, alignItems: 'flex-end' }}>
              <Badge variant={sevPill[it.sev]}>{sevText[it.sev]}</Badge>
              <span style={{ fontSize: 10, color: 'var(--fg-3)',
                             fontFamily: rtl ? 'var(--font-he)' : 'var(--font-body)' }}>{it.cat}</span>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

// -------- Readiness --------
function ReadinessDash({ rtl, t }) {
  const topics = rtl ? [
    { n: 'חלוקה בין-חברתית', v: 82, s: 'positive' },
    { n: 'Re-measurement', v: 55, s: 'highlight' },
    { n: 'FX Re-measurement', v: 38, s: 'highlight' },
    { n: 'הפסדים נצברים', v: 22, s: 'danger' },
    { n: 'פריטים השקעה', v: 71, s: 'positive' },
  ] : [
    { n: 'Inter-company dividends', v: 82, s: 'positive' },
    { n: 'Re-measurement', v: 55, s: 'highlight' },
    { n: 'FX Re-measurement', v: 38, s: 'highlight' },
    { n: 'Carried-forward losses', v: 22, s: 'danger' },
    { n: 'Investment items', v: 71, s: 'positive' },
  ];
  const colour = { positive: '#9FD4C0', highlight: '#F4A261', danger: '#C96F53' };

  return (
    <div style={{ padding: 32, maxWidth: 1140, margin: '0 auto' }}>
      <div style={{ marginBottom: 20 }}>
        <Badge variant="accent">Taxation II</Badge>
        <h1 style={{ margin: '8px 0 0', fontSize: 30, fontWeight: 700,
                     fontFamily: rtl ? 'var(--font-he)' : 'var(--font-display)',
                     color: 'var(--fg-1)', letterSpacing: '-0.015em' }}>
          {t('title', 'מוכנות לבחינה', 'Exam Readiness')}
        </h1>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 2fr', gap: 16 }}>
        <Card hero padding={28} style={{ background: 'var(--surface)', textAlign: 'center' }}>
          <div className="binah-eyebrow">{t('overall', 'מוכנות כוללת', 'Overall readiness')}</div>
          <div style={{ display: 'flex', justifyContent: 'center', marginTop: 14, marginBottom: 10 }}>
            <Ring value={73} size={200} stroke={14} gradient />
          </div>
          <div style={{ display: 'flex', justifyContent: 'center', gap: 14, fontSize: 13,
                        color: 'var(--fg-2)', fontFamily: rtl ? 'var(--font-he)' : 'var(--font-body)' }}>
            <span>{t('target', 'יעד', 'Target')}: <strong style={{ color: 'var(--accent)' }}>95%</strong></span>
            <span>·</span>
            <span>{t('exam', 'בחינה', 'Exam')}: <strong style={{ color: 'var(--fg-1)' }}>{t('days', 'בעוד 19 יום', 'in 19 days')}</strong></span>
          </div>
        </Card>

        <Card padding={24}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 14 }}>
            <h3 style={{ margin: 0, fontSize: 15, fontWeight: 600,
                         fontFamily: rtl ? 'var(--font-he)' : 'var(--font-display)' }}>
              {t('perTopic', 'לפי נושא', 'Per topic')}
            </h3>
            <Badge variant="neutral">{t('count', '5 נושאים', '5 topics')}</Badge>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            {topics.map(tp => (
              <div key={tp.n}>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 6,
                              fontFamily: rtl ? 'var(--font-he)' : 'var(--font-body)' }}>
                  <span style={{ fontSize: 13, color: 'var(--fg-1)', fontWeight: 500 }}>{tp.n}</span>
                  <span className="binah-tabular" style={{ fontSize: 13, color: 'var(--fg-2)', fontWeight: 600 }}>{tp.v}%</span>
                </div>
                <div style={{ height: 8, background: 'var(--bg-2)', borderRadius: 999, overflow: 'hidden' }}>
                  <div style={{ height: '100%', width: tp.v + '%', background: colour[tp.s], borderRadius: 999,
                    transition: 'width 600ms cubic-bezier(.2,.8,.2,1)' }} />
                </div>
              </div>
            ))}
          </div>
          <div style={{
            marginTop: 18, padding: 14, borderRadius: 12,
            background: 'var(--accent-soft)', display: 'flex', alignItems: 'center', gap: 10,
          }}>
            <Icon name="sparkle" size={16} style={{ color: 'var(--accent)' }} />
            <span style={{ fontSize: 13, color: 'var(--fg-1)',
                           fontFamily: rtl ? 'var(--font-he)' : 'var(--font-body)' }}>
              {t('plan', 'תוכנית סגירה ל-7 ימים הוכנה. 4 פומודורו ליום, יעד +22% מוכנות.',
                         '7-day closure plan ready. 4 pomodoros/day, target +22% readiness.')}
            </span>
            <Button variant="primary" size="sm" style={{ marginInlineStart: 'auto' }}>
              {t('see', 'ראה תוכנית', 'See plan')}
            </Button>
          </div>
        </Card>
      </div>
    </div>
  );
}

Object.assign(window, { StudentModel, KnowledgeMap, WeakSpots, ReadinessDash });
