// Tutor Chat · Pomodoro · Conductor

// -------- Tutor Chat --------
function TutorChat({ rtl, t }) {
  const [input, setInput] = React.useState('');
  const [messages, setMessages] = React.useState(() => rtl ? [
    { who: 'user', body: 'הסבר לי ECL עם דוגמה מספרית, בבקשה' },
    { who: 'ai',   body: '**דוגמה מספרית קודם:**\n\nיתרת נכס: 50,000\nPD (הסתברות לכשל): 30%\nLGD (הפסד צפוי): 30%\n→ ECL = 50,000 × 30% × 30% = **4,500**\n\nעכשיו לתאוריה — ECL (Expected Credit Loss) הוא ההפרש בין תזרים החוזי לתזרים הריאלי שאנחנו צופים, מהוון לפי הריבית האפקטיבית.', html: true },
    { who: 'user', body: 'ואם ה-PD משתנה לאורך החיים?' },
  ] : [
    { who: 'user', body: 'Explain ECL to me with a numerical example, please.' },
    { who: 'ai',   body: '**Numerical example first:**\n\nAsset balance: 50,000\nPD (probability of default): 30%\nLGD (loss given default): 30%\n→ ECL = 50,000 × 30% × 30% = **4,500**\n\nNow the theory — ECL (Expected Credit Loss) is the difference between contractual cash flows and the realistic cash flows we expect, discounted at the effective interest rate.', html: true },
    { who: 'user', body: 'And if PD varies over the asset lifetime?' },
  ]);

  const send = () => {
    if (!input.trim()) return;
    setMessages(m => [...m, { who: 'user', body: input },
      { who: 'ai', body: rtl ? '**שאלה נהדרת.** בואו נבנה דוגמה מדורגת…' : '**Great question.** Let’s build a staged example…' }]);
    setInput('');
  };

  return (
    <div style={{ padding: 32, maxWidth: 1040, margin: '0 auto', height: 'calc(100vh - 65px)', display: 'flex', flexDirection: 'column' }}>
      <div style={{ marginBottom: 20, display: 'flex', alignItems: 'center', gap: 12 }}>
        <div style={{ width: 42, height: 42, borderRadius: 12, background: 'var(--grad-positive)',
          display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff' }}>
          <Icon name="grad" size={22} />
        </div>
        <div style={{ flex: 1 }}>
          <h1 style={{ margin: 0, fontSize: 20, fontWeight: 600,
                       fontFamily: rtl ? 'var(--font-he)' : 'var(--font-display)',
                       color: 'var(--fg-1)' }}>
            {t('title', 'מורה לחשבונאות מתקדמת III', 'Advanced Accounting III tutor')}
          </h1>
          <div style={{ fontSize: 12, color: 'var(--fg-3)',
                        fontFamily: rtl ? 'var(--font-he)' : 'var(--font-body)' }}>
            {t('sub', 'Course Specialist · דוגמה מספרית תמיד קודמת לתאוריה', 'Course Specialist · numerical example always before theory')}
          </div>
        </div>
        <Badge variant="accent" dot>{t('live', 'פעיל', 'Live')}</Badge>
      </div>

      <Card style={{ flex: 1, display: 'flex', flexDirection: 'column', padding: 0, overflow: 'hidden' }}>
        <div style={{ flex: 1, overflow: 'auto', padding: '20px 24px', display: 'flex', flexDirection: 'column', gap: 14 }}>
          {messages.map((m, i) => (
            <div key={i} style={{
              alignSelf: m.who === 'user' ? 'flex-end' : 'flex-start',
              maxWidth: '75%',
              padding: '12px 16px', borderRadius: 14,
              background: m.who === 'user' ? '#f4a261' : 'var(--bg-2)',
              color: m.who === 'user' ? '#fff' : 'var(--fg-1)',
              fontFamily: rtl ? 'var(--font-he)' : 'var(--font-body)', fontSize: 14, lineHeight: 1.6,
              whiteSpace: 'pre-wrap',
              [m.who === 'user' ? (rtl ? 'borderBottomRightRadius' : 'borderBottomLeftRadius') : (rtl ? 'borderBottomLeftRadius' : 'borderBottomRightRadius')]: 4,
            }} dangerouslySetInnerHTML={{ __html: m.body.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>').replace(/\n/g, '<br>') }} />
          ))}
          <div style={{ alignSelf: rtl ? 'flex-end' : 'flex-start', display: 'flex', gap: 6 }}>
            {[t('p1', 'הרחב דוגמה', 'Expand example'), t('p2', 'השווה ל-IAS 39', 'Compare to IAS 39'), t('p3', 'הוסף ל-Anki', 'Add to Anki')].map(p =>
              <button key={p} style={{
                padding: '6px 12px', borderRadius: 999, border: '1px solid var(--border)',
                background: 'var(--surface)', color: 'var(--fg-2)',
                fontFamily: rtl ? 'var(--font-he)' : 'var(--font-body)', fontSize: 12, cursor: 'pointer',
                transition: 'all 200ms cubic-bezier(.2,.8,.2,1)',
              }}>{p}</button>
            )}
          </div>
        </div>
        <div style={{ borderTop: '1px solid var(--divider)', padding: 16, display: 'flex', gap: 10 }}>
          <input value={input} onChange={e => setInput(e.target.value)}
            onKeyDown={e => e.key === 'Enter' && send()}
            placeholder={t('ph', 'שאל כל דבר על הקורס…', 'Ask anything about the course…')}
            style={{ flex: 1, padding: '12px 16px', borderRadius: 12, border: '1px solid var(--border)',
                     background: 'var(--surface)', color: 'var(--fg-1)',
                     fontFamily: rtl ? 'var(--font-he)' : 'var(--font-body)', fontSize: 14, outline: 'none' }} />
          <Button variant="primary" onClick={send} iconRight="send">{t('send', 'שלח', 'Send')}</Button>
        </div>
      </Card>
    </div>
  );
}

// -------- Pomodoro --------
function Pomodoro({ rtl, t }) {
  const [sec, setSec] = React.useState(924);
  React.useEffect(() => {
    const i = setInterval(() => setSec(s => s > 0 ? s - 1 : 0), 1000);
    return () => clearInterval(i);
  }, []);
  const mm = String(Math.floor(sec / 60)).padStart(2, '0');
  const ss = String(sec % 60).padStart(2, '0');
  const pct = sec / (25*60);
  const C = 2 * Math.PI * 120;

  const steps = rtl
    ? ['סקירה מרווחת', 'חומר חדש', 'תרגול', 'סיכום']
    : ['Spaced review', 'New material', 'Practice', 'Wrap-up'];

  return (
    <div style={{ padding: 32, maxWidth: 1040, 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', 'סשן פומודורו', 'Pomodoro session')}
        </h1>
        <p style={{ color: 'var(--fg-3)', fontSize: 14, margin: '6px 0 0',
                    fontFamily: rtl ? 'var(--font-he)' : 'var(--font-body)' }}>
          {t('sub', 'Managerial · Pomodoro #2 מתוך 4', 'Managerial · Pomodoro #2 of 4')}
        </p>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
        <Card hero padding={32} style={{ textAlign: 'center' }}>
          <div style={{ position: 'relative', width: 280, height: 280, margin: '0 auto' }}>
            <svg viewBox="0 0 280 280" width="280" height="280">
              <circle cx="140" cy="140" r="120" stroke="var(--bg-2)" strokeWidth="16" fill="none"/>
              <circle cx="140" cy="140" r="120" stroke="var(--binah-deep-teal)" strokeWidth="16" fill="none"
                strokeDasharray={C} strokeDashoffset={C * (1 - pct)} strokeLinecap="round"
                transform="rotate(-90 140 140)" style={{ transition: 'stroke-dashoffset 1s linear' }}/>
            </svg>
            <div style={{
              position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column',
              alignItems: 'center', justifyContent: 'center',
            }}>
              <div style={{ fontFamily: 'var(--font-display)', fontVariantNumeric: 'tabular-nums',
                fontWeight: 700, fontSize: 58, color: 'var(--fg-1)', letterSpacing: '-0.03em', lineHeight: 1 }}>
                {mm}:{ss}
              </div>
              <div className="binah-eyebrow" style={{ marginTop: 8 }}>{t('left', 'נותר', 'Remaining')}</div>
            </div>
          </div>
          <div style={{ display: 'flex', justifyContent: 'center', gap: 10, marginTop: 20 }}>
            <Button variant="primary" iconLeft="timer">{t('pause', 'השהה', 'Pause')}</Button>
            <Button variant="secondary">{t('end', 'סיים מוקדם', 'End early')}</Button>
            <Button variant="ghost">+5</Button>
          </div>
        </Card>

        <Card padding={24}>
          <h3 style={{ margin: '0 0 14px', fontSize: 15, fontWeight: 600,
                       fontFamily: rtl ? 'var(--font-he)' : 'var(--font-display)' }}>
            {t('agenda', 'סדר היום', 'Agenda')}
          </h3>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {steps.map((s, i) => {
              const state = i < 1 ? 'done' : i === 1 ? 'active' : 'todo';
              return <div key={s} style={{
                display: 'flex', alignItems: 'center', gap: 12,
                padding: '10px 14px', borderRadius: 12,
                background: state === 'active' ? 'var(--binah-saffron-200)' : 'var(--bg-2)',
                color: state === 'done' ? 'var(--fg-3)' : 'var(--fg-1)',
                fontFamily: rtl ? 'var(--font-he)' : 'var(--font-body)',
              }}>
                <div style={{
                  width: 26, height: 26, borderRadius: 999,
                  background: state === 'active' ? 'var(--binah-saffron)'
                            : state === 'done' ? 'rgba(159,212,192,0.4)' : 'var(--surface)',
                  color: state === 'active' ? '#fff' : state === 'done' ? 'var(--positive-fg)' : 'var(--fg-2)',
                  fontFamily: 'var(--font-display)', fontVariantNumeric: 'tabular-nums',
                  fontWeight: 700, fontSize: 12,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  flexShrink: 0,
                }}>
                  {state === 'done' ? <Icon name="check" size={12}/> : (i+1)}
                </div>
                <span style={{ fontSize: 14, fontWeight: state === 'active' ? 600 : 500 }}>{s}</span>
                {state === 'active' && <Badge variant="highlight" style={{ marginInlineStart: 'auto' }}>
                  {t('now', 'עכשיו', 'Now')}
                </Badge>}
              </div>;
            })}
          </div>
          <div style={{
            marginTop: 20, padding: '12px 14px', borderRadius: 12,
            border: '1px dashed var(--border-strong)', display: 'flex', gap: 10, alignItems: 'flex-start',
          }}>
            <Icon name="sparkle" size={16} style={{ color: 'var(--accent)', marginTop: 2 }} />
            <div>
              <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--fg-1)',
                            fontFamily: rtl ? 'var(--font-he)' : 'var(--font-body)' }}>
                {t('focus', 'מיקוד הסשן הזה', 'This session’s focus')}
              </div>
              <div style={{ fontSize: 12, color: 'var(--fg-3)', marginTop: 2,
                            fontFamily: rtl ? 'var(--font-he)' : 'var(--font-body)' }}>
                {t('focusBody', 'Contribution Margin vs. Gross Margin — סגירת פער מושגי',
                               'Contribution Margin vs. Gross Margin — closing a conceptual gap')}
              </div>
            </div>
          </div>
        </Card>
      </div>
    </div>
  );
}

// -------- Conductor --------
function ConductorView({ rtl, t }) {
  const agents = [
    { id: '01', name: t('a1', 'מודל סטודנט', 'Student Model'),        icon: 'users',     angle: -162 },
    { id: '02', name: t('a2', 'כותב שאלות',   'Question Writer'),     icon: 'pen',       angle: -126 },
    { id: '03', name: t('a3', 'מעריך תשובות', 'Answer Evaluator'),    icon: 'scale',     angle:  -90 },
    { id: '04', name: t('a4', 'המסביר',       'Explainer'),           icon: 'msg',       angle:  -54 },
    { id: '05', name: t('a5', 'מנתח חולשות',  'Weak-Spot Analyzer'),  icon: 'activity',  angle:  -18 },
    { id: '06', name: t('a6', 'מתזמן חזרות',  'Spaced Review'),       icon: 'calendar',  angle:   18 },
    { id: '07', name: t('a7', 'מעריך מוכנות', 'Readiness Assessor'),  icon: 'pie',       angle:   54 },
    { id: '08', name: t('a8', 'מתכנן סשן',    'Session Planner'),     icon: 'clipboard', angle:   90 },
    { id: '09', name: t('a9', 'מומחה קורס',   'Course Specialist'),   icon: 'grad',      angle:  126 },
    { id: '10', name: t('a0', 'בוחן זיכרון',  'Retention Tester'),    icon: 'refresh',   angle:  162 },
  ];
  const cx = 420, cy = 240, R = 180;

  return (
    <div style={{
      padding: 0, minHeight: 'calc(100vh - 65px)',
      background: 'linear-gradient(180deg, #0B1628 0%, #0F1B30 100%)',
      color: 'var(--binah-cloud)', position: 'relative', overflow: 'hidden',
    }}>
      <div style={{
        position: 'absolute', top: '30%', left: '50%', transform: 'translate(-50%, -50%)',
        width: 600, height: 600, borderRadius: '50%',
        background: 'radial-gradient(circle, rgba(244,162,97,0.20) 0%, transparent 60%)',
        pointerEvents: 'none',
      }} />
      <div style={{ padding: 32, position: 'relative', zIndex: 1 }}>
        <div className="binah-eyebrow" style={{ color: 'var(--binah-saffron)' }}>
          {t('eye', 'תזמור סוכנים חי', 'LIVE AGENT ORCHESTRATION')}
        </div>
        <h1 style={{ margin: '8px 0 0', fontSize: 30, fontWeight: 700,
                     fontFamily: rtl ? 'var(--font-he)' : 'var(--font-display)',
                     color: 'var(--binah-cloud)', letterSpacing: '-0.015em' }}>
          {t('title', 'המנצח', 'The Conductor')}
        </h1>
        <p style={{ color: 'var(--binah-cloud-2)', margin: '6px 0 0', fontSize: 14,
                    fontFamily: rtl ? 'var(--font-he)' : 'var(--font-body)' }}>
          {t('sub', 'סוכן מרכזי אחד מנתב את הבקשה שלך ל-10 מומחים. כל אינטראקציה מתועדת.',
                    'One central agent routes your request to 10 specialists. Every interaction is logged.')}
        </p>
      </div>

      <div style={{ position: 'relative', width: '100%', maxWidth: 840, height: 480, margin: '0 auto' }}>
        <svg viewBox="0 0 840 480" width="100%" height="480" preserveAspectRatio="xMidYMid meet" style={{ position: 'absolute', inset: 0 }}>
          {agents.map(a => {
            const x = cx + Math.cos(a.angle * Math.PI/180) * R;
            const y = cy + Math.sin(a.angle * Math.PI/180) * R;
            const active = a.id === '09' || a.id === '04';
            return <path key={a.id} d={`M ${cx} ${cy} L ${x} ${y}`}
              stroke={active ? 'var(--binah-saffron)' : 'var(--binah-sage-mint)'}
              strokeWidth={active ? 2 : 1} opacity={active ? 1 : 0.35} fill="none" />;
          })}
        </svg>

        {/* Conductor center */}
        <div style={{
          position: 'absolute', left: cx, top: cy, transform: 'translate(-50%,-50%)',
          width: 120, height: 120, borderRadius: '50%',
          background: 'radial-gradient(circle, #0F4C5C 0%, #0B1628 100%)',
          border: '2px solid var(--binah-sage-mint)',
          boxShadow: '0 0 60px rgba(244,162,97,0.5), 0 8px 32px rgba(0,0,0,0.5)',
          display: 'flex', alignItems: 'center', justifyContent: 'center', flexDirection: 'column',
          zIndex: 2,
        }}>
          <img src="../../assets/conductor-mark.svg" width="48" height="48" style={{ filter: 'brightness(1.3)' }} alt=""/>
          <div style={{ fontFamily: rtl ? 'var(--font-he)' : 'var(--font-display)',
                        fontSize: 11, fontWeight: 600, color: 'var(--binah-cloud)', marginTop: 2 }}>
            Conductor
          </div>
        </div>

        {agents.map(a => {
          const x = cx + Math.cos(a.angle * Math.PI/180) * R;
          const y = cy + Math.sin(a.angle * Math.PI/180) * R;
          const active = a.id === '09' || a.id === '04';
          return <div key={a.id} style={{
            position: 'absolute', left: x, top: y, transform: 'translate(-50%,-50%)',
            display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4,
          }}>
            <div style={{
              width: 56, height: 56, borderRadius: 999,
              background: active ? 'var(--binah-deep-teal)' : 'var(--binah-indigo-night-3)',
              border: active ? '2px solid var(--binah-saffron)' : '1px solid rgba(232,238,242,0.15)',
              display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--binah-cloud)',
              boxShadow: active ? '0 0 24px rgba(244,162,97,0.5)' : 'none',
            }}>
              <Icon name={a.icon} size={22} />
            </div>
            <div style={{
              fontSize: 11, fontWeight: active ? 600 : 500,
              color: active ? 'var(--binah-saffron)' : 'var(--binah-cloud-2)',
              fontFamily: rtl ? 'var(--font-he)' : 'var(--font-body)',
              textAlign: 'center', maxWidth: 90, lineHeight: 1.25,
            }}>
              <span style={{ opacity: 0.6, fontVariantNumeric: 'tabular-nums' }}>{a.id}</span> · {a.name}
            </div>
          </div>;
        })}
      </div>

      {/* Route panel (glassmorphism) — below the network */}
      <div style={{
        width: 'min(560px, calc(100% - 64px))', margin: '24px auto 48px', padding: 16,
        borderRadius: 16, background: 'rgba(21,37,64,0.6)',
        backdropFilter: 'blur(24px) saturate(140%)',
        WebkitBackdropFilter: 'blur(24px) saturate(140%)',
        border: '1px solid rgba(232,238,242,0.08)',
        boxShadow: '0 24px 48px rgba(0,0,0,0.4), inset 0 1px 0 rgba(255,255,255,0.04)',
      }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 10 }}>
          <div className="binah-eyebrow" style={{ color: 'var(--binah-saffron)' }}>
            {t('route', 'מסלול נוכחי', 'CURRENT ROUTE')}
          </div>
          <Badge variant="positive" dot>{t('live2', 'חי', 'Live')}</Badge>
        </div>
        {[
          { ts: '00:00', line: t('l1', 'משתמש שאל: "הסבר ECL"', 'User asked: "Explain ECL"'), on: true },
          { ts: '00:01', line: t('l2', '→ מומחה קורס (IFRS 9)', '→ Course Specialist (IFRS 9)'), on: true },
          { ts: '00:02', line: t('l3', '→ המסביר', '→ Explainer'), on: true },
          { ts: '00:03', line: t('l4', '→ מודל סטודנט (תעד)', '→ Student Model (logged)'), on: false },
        ].map((s, i) => (
          <div key={i} style={{
            display: 'flex', gap: 10, padding: '6px 0', fontSize: 12,
            fontFamily: rtl ? 'var(--font-he)' : 'var(--font-body)',
            color: s.on ? 'var(--binah-cloud)' : 'var(--binah-cloud-3)',
            borderTop: i ? '1px solid rgba(232,238,242,0.06)' : 'none',
          }}>
            <span style={{ fontFamily: 'var(--font-mono)', color: 'var(--binah-sage-mint)' }}>{s.ts}</span>
            <span>{s.line}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { TutorChat, Pomodoro, ConductorView });
