
const { useState, useRef, useEffect, useCallback } = React;

const QUICK_PROMPTS = [
  'What should I take next semester?',
  'Can I finish in 2 years?',
  'Is my schedule too heavy?',
  'Which Cal-GETC areas am I missing?',
];

function MarkdownText({ text }) {
  const parts = text.split(/(\*\*[^*]+\*\*|`[^`]+`|\n)/g);
  return (
    <span>
      {parts.map((p, i) => {
        if (p === '\n') return <br key={i} />;
        if (p.startsWith('**') && p.endsWith('**')) return <strong key={i}>{p.slice(2, -2)}</strong>;
        if (p.startsWith('`') && p.endsWith('`')) return <code key={i} className="chat-code">{p.slice(1, -1)}</code>;
        return <span key={i}>{p}</span>;
      })}
    </span>
  );
}

function ChatPanel({ open, onClose, profile }) {
  const [messages, setMessages] = useState(() => {
    try { return JSON.parse(localStorage.getItem('tl_chat') || '[]'); } catch { return []; }
  });
  const [input, setInput] = useState('');
  const [loading, setLoading] = useState(false);
  const [sending, setSending] = useState(false);
  const bottomRef = useRef(null);
  const inputRef = useRef(null);
  const sendBtnRef = useRef(null);

  useEffect(() => {
    if (open) setTimeout(() => inputRef.current?.focus(), 100);
  }, [open]);

  useEffect(() => {
    if (bottomRef.current) {
      bottomRef.current.parentElement.scrollTop = bottomRef.current.offsetTop;
    }
  }, [messages, loading]);

  useEffect(() => {
    localStorage.setItem('tl_chat', JSON.stringify(messages.slice(-40)));
  }, [messages]);

  const buildContext = () => {
    const sels = (profile.selections || []).map(s => `${s.school?.abbr || s.school?.name} - ${s.major}`).join(', ');
    const coursesPlaced = Object.values(profile.semesters || {}).flat().length;
    const calgetcDone = Object.keys(profile.calgetcSelections || {}).filter(k => (profile.calgetcSelections[k] || []).length > 0).length;
    const completed = Object.entries(profile.courseStatuses || {}).filter(([, s]) => s === 'completed').map(([k]) => k);
    return `Student context:
- Community college: ${profile.cc?.name || 'Irvine Valley College'}
- Target schools/majors: ${sels || 'None set yet'}
- Transfer term: ${profile.transferTerm || 'Fall 2027'}
- Courses placed in plan: ${coursesPlaced}
- Courses completed: ${completed.join(', ') || 'None yet'}
- Cal-GETC areas filled: ${calgetcDone}/11
- Summers included: ${profile.useSummer ? 'Yes' : 'No'}`;
  };

  const send = useCallback(async (text) => {
    const trimmed = text.trim();
    if (!trimmed || loading) return;
    setSending(true);
    setTimeout(() => setSending(false), 400);
    const userMsg = { role: 'user', content: trimmed };
    const updated = [...messages, userMsg];
    setMessages(updated);
    setInput('');
    setLoading(true);

    try {
      const ctx = buildContext();
      const reply = await window.claude.complete({
        messages: [
          {
            role: 'user',
            content: `You are a warm, knowledgeable California community college transfer advisor inside an app called TransferLens. You help students understand their transfer pathway clearly and calmly. Keep answers concise (2-4 sentences max unless asked for detail), encouraging, and specific to the student's situation. Avoid jargon when possible. Here is the student's current context:\n\n${ctx}\n\nStudent question: ${trimmed}`
          }
        ]
      });
      setMessages(prev => [...prev, { role: 'assistant', content: reply }]);
    } catch (e) {
      setMessages(prev => [...prev, { role: 'assistant', content: "I'm having trouble connecting right now. Please try again in a moment." }]);
    } finally {
      setLoading(false);
    }
  }, [messages, loading, profile]);

  const handleKey = (e) => {
    if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send(input); }
  };

  return (
    <div className={`chat-panel ${open ? 'chat-open' : ''}`}>
      <div className="chat-header">
        <div className="chat-header-left">
          <div className="chat-avatar-sm">
            <svg width="16" height="16" viewBox="0 0 16 16" fill="none"><circle cx="8" cy="6" r="3" stroke="currentColor" strokeWidth="1.5"/><path d="M2 14c0-3.3 2.7-4 6-4s6 .7 6 4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/></svg>
          </div>
          <div>
            <div className="chat-header-title">Transfer Advisor</div>
            <div className="chat-header-sub">AI-powered · answers based on your plan</div>
          </div>
        </div>
        <div className="chat-header-actions">
          {messages.length > 0 && (
            <button className="chat-clear" onClick={() => { setMessages([]); localStorage.removeItem('tl_chat'); }}>Clear</button>
          )}
          <button className="chat-close" onClick={onClose}>
            <svg width="16" height="16" viewBox="0 0 16 16" fill="none"><path d="M4 4l8 8M12 4l-8 8" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/></svg>
          </button>
        </div>
      </div>

      <div className="chat-messages">
        {messages.length === 0 && (
          <div className="chat-welcome">
            <div className="chat-welcome-icon">
              <svg width="32" height="32" viewBox="0 0 32 32" fill="none"><circle cx="16" cy="13" r="6" stroke="var(--accent)" strokeWidth="2"/><path d="M4 30c0-6.6 5.4-8 12-8s12 1.4 12 8" stroke="var(--accent)" strokeWidth="2" strokeLinecap="round"/></svg>
            </div>
            <div className="chat-welcome-title">Hi! I'm your transfer advisor.</div>
            <div className="chat-welcome-sub">Ask me anything about your plan, courses, deadlines, or what to take next.</div>
            <div className="chat-quick-prompts">
              {QUICK_PROMPTS.map(q => (
                <button key={q} className="chat-quick-btn" onClick={() => send(q)}>{q}</button>
              ))}
            </div>
          </div>
        )}

        {messages.map((m, i) => (
          <div key={i} className={`chat-msg ${m.role === 'user' ? 'chat-msg-user' : 'chat-msg-ai'}`}>
            {m.role === 'assistant' && (
              <div className="chat-msg-avatar">
                <svg width="14" height="14" viewBox="0 0 14 14" fill="none"><circle cx="7" cy="5.5" r="2.5" stroke="currentColor" strokeWidth="1.4"/><path d="M1.5 13c0-2.9 2.4-3.5 5.5-3.5s5.5.6 5.5 3.5" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round"/></svg>
              </div>
            )}
            <div className="chat-msg-bubble">
              <MarkdownText text={m.content} />
            </div>
          </div>
        ))}

        {loading && (
          <div className="chat-msg chat-msg-ai">
            <div className="chat-msg-avatar">
              <svg width="14" height="14" viewBox="0 0 14 14" fill="none"><circle cx="7" cy="5.5" r="2.5" stroke="currentColor" strokeWidth="1.4"/><path d="M1.5 13c0-2.9 2.4-3.5 5.5-3.5s5.5.6 5.5 3.5" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round"/></svg>
            </div>
            <div className="chat-msg-bubble chat-typing">
              <span></span><span></span><span></span>
            </div>
          </div>
        )}

        <div ref={bottomRef}></div>
      </div>

      <div className="chat-input-row">
        <textarea
          ref={inputRef}
          className="chat-input"
          placeholder="Ask about your transfer plan…"
          value={input}
          onChange={e => setInput(e.target.value)}
          onKeyDown={handleKey}
          rows={1}
        />
        <button ref={sendBtnRef} className={`chat-send ${sending ? 'sending' : ''}`} disabled={!input.trim() || loading} onClick={() => send(input)}>
          <svg width="16" height="16" viewBox="0 0 16 16" fill="none"><path d="M13 3L3 8l4 2 2 4 4-11z" stroke="currentColor" strokeWidth="1.5" strokeLinejoin="round"/></svg>
        </button>
      </div>
    </div>
  );
}

Object.assign(window, { ChatPanel });
