const AITUTOR_SEED = [
  { role: 'user', text: 'What is the difference between star and delta connection in a three-phase motor?', hi: 'तीन-चरण मोटर में स्टार और डेल्टा कनेक्शन में क्या अंतर है?' },
  { role: 'ai', text: 'Great question, Rahul! Let me explain with a quick visual comparison.',
    cards: [
      { kind: 'diagram', title: 'Star (Y) connection', body: 'Line voltage = √3 × Phase voltage · Line current = Phase current · Used for starting to reduce inrush current.' },
      { kind: 'diagram', title: 'Delta (Δ) connection', body: 'Line voltage = Phase voltage · Line current = √3 × Phase current · Used at running/full load for maximum torque.' },
    ],
    followup: [
      'Show me a 3D animation of the winding connections',
      'When does a star-delta starter switch over?',
      'What are typical starting current values?',
    ],
  },
  { role: 'user', text: 'Show me a 3D animation of the winding connections' },
  { role: 'ai', text: 'Here you go — I have found the exact 3D lesson in your Electrician trade library. It shows the winding termination inside the terminal box.',
    lesson: { title: 'L07 · Star-Delta Winding Termination', dur: '4:12', trade: 'Electrician · Sem 4' },
  },
];

// Canned tutor replies keyed by intent — keeps the demo responsive offline.
function aiReplyFor(q) {
  const s = (q || '').toLowerCase();
  if (s.includes('3d') || s.includes('animation') || s.includes('winding')) {
    return { role: 'ai', text: 'Here you go — I have found the matching 3D lesson in your Electrician trade library. It shows the winding termination inside the terminal box.',
      lesson: { title: 'L07 · Star-Delta Winding Termination', dur: '4:12', trade: 'Electrician · Sem 4' } };
  }
  if (s.includes('star') || s.includes('delta')) {
    return { role: 'ai', text: 'Star vs Delta — here is the quick comparison you can revise before your viva.',
      cards: [
        { kind: 'diagram', title: 'Star (Y) connection', body: 'Line voltage = √3 × Phase voltage · Line current = Phase current · Used for starting to reduce inrush current.' },
        { kind: 'diagram', title: 'Delta (Δ) connection', body: 'Line voltage = Phase voltage · Line current = √3 × Phase current · Used at running/full load for maximum torque.' },
      ],
      followup: ['Show me a 3D animation of the winding connections', 'When does a star-delta starter switch over?', 'What are typical starting current values?'] };
  }
  if (s.includes('viva')) {
    return { role: 'ai', text: 'Let us prepare for viva. Try answering: (1) Why is a star-delta starter used? (2) State the relation between line and phase current in delta. (3) Name one protection device on a 3-phase motor. Reply and I will grade you.' };
  }
  if (s.includes('example') || s.includes('practical')) {
    return { role: 'ai', text: 'Practical example: a 5 HP induction motor started in star draws ~1/3 of the delta starting current, protecting the windings. Once it reaches ~75% speed, the starter switches to delta for full torque.' };
  }
  if (s.includes('sem 1') || s.includes('simple') || s.includes('explain like')) {
    return { role: 'ai', text: 'Simple version: Star connection = gentle start (less current). Delta connection = full power for running. We start in star, then switch to delta — like starting a bike in first gear, then shifting up.' };
  }
  return { role: 'ai', text: 'Got it — I will pull the most relevant 3D lesson and notes for “' + (q || '').trim() + '”. Meanwhile, try one of the suggested prompts below to dig deeper.',
    followup: ['Give me a practical example', 'Explain like I\'m in Sem 1', 'Prepare me for viva'] };
}

function AITutor({ onNavigate }) {
  const [input, setInput] = React.useState('');
  const [messages, setMessages] = React.useState(AITUTOR_SEED);
  const scrollRef = React.useRef(null);

  React.useEffect(() => {
    const el = scrollRef.current;
    if (el) el.scrollTop = el.scrollHeight;
  }, [messages]);

  const send = (raw) => {
    const text = (raw != null ? raw : input).trim();
    if (!text) return;
    setInput('');
    setMessages(m => [...m, { role: 'user', text }]);
    // Simulate the tutor thinking, then answer.
    setTimeout(() => setMessages(m => [...m, aiReplyFor(text)]), 500);
  };

  const clearChat = () => { setMessages([]); window.toast('Chat cleared'); };

  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1fr 320px', height: 'calc(100vh - 60px)', overflow: 'hidden' }}>
      <div style={{ display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
        {/* Chat header */}
        <div style={{ padding: '18px 28px', borderBottom: '1px solid var(--ink-200)', background: 'white', display: 'flex', alignItems: 'center', gap: 14 }}>
          <div style={{ width: 44, height: 44, borderRadius: 12, background: 'linear-gradient(135deg, #0b2a5b, #e67514)', display: 'grid', placeItems: 'center', color: 'white' }}>
            <window.IconSparkle size={22}/>
          </div>
          <div>
            <div style={{ fontFamily: 'var(--font-serif)', fontSize: 18, fontWeight: 600, color: 'var(--ink-900)' }}>ShikshaTri AI Tutor</div>
            <div style={{ fontSize: 12, color: 'var(--ink-600)', display: 'flex', gap: 8, alignItems: 'center' }}>
              <span style={{ width: 6, height: 6, background: 'var(--green-600)', borderRadius: '50%' }}/>
              Online · Answering in English, हिंदी, தமிழ், తెలుగు
            </div>
          </div>
          <div style={{ marginLeft: 'auto', display: 'flex', gap: 8 }}>
            <button className="btn btn-ghost" onClick={() => window.toast('Voice mode is coming soon in this demo')}><window.IconMic size={13}/> Voice mode</button>
            <button className="btn btn-ghost" onClick={clearChat}>Clear chat</button>
          </div>
        </div>

        {/* Messages */}
        <div ref={scrollRef} style={{ flex: 1, overflow: 'auto', padding: '28px 28px 20px', display: 'flex', flexDirection: 'column', gap: 20 }}>
          {messages.length === 0 && (
            <div style={{ margin: 'auto', textAlign: 'center', color: 'var(--ink-500)', fontSize: 13 }}>
              Ask the AI Tutor anything about your trade to begin.
            </div>
          )}
          {messages.map((m, i) => (
            m.role === 'user' ? (
              <div key={i} style={{ display: 'flex', gap: 12, justifyContent: 'flex-end' }}>
                <div style={{ maxWidth: 540, background: 'var(--navy-800)', color: 'white', padding: '12px 16px', borderRadius: '14px 14px 4px 14px' }}>
                  <div style={{ fontSize: 14, lineHeight: 1.45 }}>{m.text}</div>
                  {m.hi && <div className="hi" style={{ fontSize: 13, marginTop: 4, color: 'rgba(255,255,255,0.75)' }}>{m.hi}</div>}
                </div>
                <div className="avatar" style={{ background: 'var(--navy-700)', flexShrink: 0 }}>RK</div>
              </div>
            ) : (
              <div key={i} style={{ display: 'flex', gap: 12 }}>
                <div style={{ width: 32, height: 32, borderRadius: 8, background: 'linear-gradient(135deg, #0b2a5b, #e67514)', color: 'white', display: 'grid', placeItems: 'center', flexShrink: 0 }}>
                  <window.IconSparkle size={16}/>
                </div>
                <div style={{ maxWidth: 640 }}>
                  <div style={{ background: 'white', border: '1px solid var(--ink-200)', padding: '14px 18px', borderRadius: '14px 14px 14px 4px' }}>
                    <div style={{ fontSize: 14, lineHeight: 1.55, color: 'var(--ink-900)' }}>{m.text}</div>
                    {m.cards && (
                      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginTop: 12 }}>
                        {m.cards.map(c => (
                          <div key={c.title} style={{ padding: 14, background: 'var(--navy-50)', border: '1px solid var(--navy-100)', borderRadius: 10 }}>
                            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
                              <window.IconCube size={16} style={{ color: 'var(--navy-700)' }}/>
                              <span style={{ fontSize: 13, fontWeight: 700, color: 'var(--navy-800)' }}>{c.title}</span>
                            </div>
                            <div style={{ fontSize: 12.5, color: 'var(--ink-700)', lineHeight: 1.5 }}>{c.body}</div>
                          </div>
                        ))}
                      </div>
                    )}
                    {m.lesson && (
                      <div style={{ marginTop: 12, display: 'flex', gap: 12, padding: 12, background: 'var(--ink-50)', borderRadius: 10, alignItems: 'center' }}>
                        <div style={{ width: 80, height: 60, background: '#0b2a5b', borderRadius: 6, position: 'relative', overflow: 'hidden' }}>
                          <img src="assets/hero-motor.jpg" style={{ width: '100%', height: '100%', objectFit: 'cover' }} alt=""/>
                          <div style={{ position: 'absolute', inset: 0, display: 'grid', placeItems: 'center' }}>
                            <window.IconPlay size={22} style={{ color: 'white' }}/>
                          </div>
                        </div>
                        <div style={{ flex: 1 }}>
                          <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--ink-900)' }}>{m.lesson.title}</div>
                          <div style={{ fontSize: 12, color: 'var(--ink-600)', marginTop: 2 }}>{m.lesson.trade} · {m.lesson.dur}</div>
                        </div>
                        <button className="btn btn-primary" onClick={() => onNavigate && onNavigate('lesson')}>Open lesson</button>
                      </div>
                    )}
                  </div>
                  {m.followup && (
                    <div style={{ display: 'flex', gap: 8, marginTop: 10, flexWrap: 'wrap' }}>
                      {m.followup.map(f => (
                        <button key={f} onClick={() => send(f)} style={{
                          padding: '7px 12px',
                          fontSize: 12,
                          background: 'white',
                          border: '1px solid var(--ink-200)',
                          borderRadius: 999,
                          color: 'var(--ink-800)',
                          fontWeight: 500,
                          cursor: 'pointer',
                        }}>{f}</button>
                      ))}
                    </div>
                  )}
                </div>
              </div>
            )
          ))}
        </div>

        {/* Input */}
        <div style={{ padding: 20, borderTop: '1px solid var(--ink-200)', background: 'white' }}>
          <div style={{ display: 'flex', gap: 10, alignItems: 'end', background: 'var(--ink-50)', border: '1px solid var(--ink-200)', borderRadius: 12, padding: 10 }}>
            <button className="icon-btn" style={{ width: 34, height: 34, background: 'transparent' }}><window.IconMic size={16}/></button>
            <textarea
              value={input}
              onChange={e => setInput(e.target.value)}
              onKeyDown={e => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send(); } }}
              placeholder="Ask about any machine, process, or concept — in English, हिंदी, தமிழ் or తెలుగు…"
              rows={1}
              style={{
                flex: 1, resize: 'none', border: 'none', outline: 'none',
                background: 'transparent', fontFamily: 'inherit', fontSize: 14,
                padding: '8px 4px', minHeight: 32, maxHeight: 120,
              }}
            />
            <button className="btn btn-primary" style={{ padding: '8px 14px' }} onClick={() => send()}>
              <window.IconSend size={13}/> Send
            </button>
          </div>
          <div style={{ display: 'flex', gap: 10, marginTop: 10, flexWrap: 'wrap' }}>
            {['Explain like I\'m in Sem 1', 'Give me a practical example', 'What did I get wrong yesterday?', 'Prepare me for viva'].map(s => (
              <button key={s} onClick={() => send(s)} style={{ padding: '6px 10px', fontSize: 11, background: 'white', border: '1px solid var(--ink-200)', borderRadius: 999, color: 'var(--ink-700)', cursor: 'pointer' }}>{s}</button>
            ))}
          </div>
        </div>
      </div>

      {/* Side panel */}
      <aside style={{ background: 'white', borderLeft: '1px solid var(--ink-200)', overflow: 'auto' }}>
        <div style={{ padding: 20 }}>
          <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--ink-600)', textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: 12 }}>
            Weak topics detected
          </div>
          {[
            { t: 'Star-Delta connection', v: 42 },
            { t: 'Squirrel cage rotor', v: 58 },
            { t: 'Torque-slip curve', v: 61 },
            { t: 'Motor starters', v: 74 },
          ].map(w => (
            <div key={w.t} style={{ padding: '10px 0', borderBottom: '1px dashed var(--ink-200)' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12.5, marginBottom: 4 }}>
                <span style={{ color: 'var(--ink-800)', fontWeight: 500 }}>{w.t}</span>
                <span style={{ fontFamily: 'var(--font-mono)', color: 'var(--ink-600)', fontSize: 11 }}>{w.v}%</span>
              </div>
              <div className="progress-track" style={{ height: 4 }}>
                <div className="progress-fill" style={{ width: `${w.v}%`, background: w.v < 60 ? 'var(--red-600)' : w.v < 75 ? 'var(--saffron-500)' : 'var(--green-600)' }}/>
              </div>
            </div>
          ))}
        </div>

        <div style={{ padding: 20, borderTop: '1px solid var(--ink-200)' }}>
          <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--ink-600)', textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: 12 }}>
            Suggested revision plan
          </div>
          <div style={{ padding: 14, background: 'var(--navy-50)', borderRadius: 10, border: '1px solid var(--navy-100)' }}>
            <div style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--navy-800)', marginBottom: 6 }}>Next 3 days · 45 min/day</div>
            {[
              { d: 'Today', t: 'Star-Delta 3D walkthrough' },
              { d: 'Tomorrow', t: 'Torque-slip practice quiz' },
              { d: 'Fri', t: 'Motor starters virtual lab' },
            ].map(x => (
              <div key={x.d} style={{ padding: '6px 0', display: 'flex', gap: 8, fontSize: 12, color: 'var(--ink-700)' }}>
                <span style={{ fontFamily: 'var(--font-mono)', color: 'var(--saffron-600)', fontWeight: 700, width: 60 }}>{x.d}</span>
                <span>{x.t}</span>
              </div>
            ))}
          </div>
          <button className="btn btn-primary" style={{ width: '100%', justifyContent: 'center', marginTop: 12 }} onClick={() => window.toast('Revision plan added to your schedule')}>Accept plan</button>
        </div>
      </aside>
    </div>
  );
}

window.AITutor = AITutor;
