// AI Agent — floating button + chat drawer with smart suggestions
(function(){
const AI_CHAT_FN = 'https://ifppalksavexjrjsngeh.supabase.co/functions/v1/ai-chat';
const { useState, useEffect, useRef } = React;

const STARTER_SUGGESTIONS = [
  { icon: '📋', text: 'סכם לי את המשימות הפתוחות השבוע' },
  { icon: '⚠️', text: 'אילו משימות בסיכון איחור?' },
  { icon: '📅', text: 'מה יש לי מחר?' },
  { icon: '✍️', text: 'נסח מייל תזכורת לקבלן' },
  { icon: '📊', text: 'תן לי דוח סטטוס כללי על הפרויקטים' },
];

const AiAgent = () => {
  const [open, setOpen] = useState(false);

  // קבל שם ראשון מהמשתמש המחובר
  const _rawName = window.YBP_AUTH?.getCurrentUser?.()?.name || '';
  const firstName = _rawName.split(' ')[0] || 'שלום';

  const [messages, setMessages] = useState([
    { role: 'agent', text: `שלום ${firstName} 👋 אני העוזר האישי שלך. אני יכול לעזור עם משימות, תזכורות, ניסוח מיילים, וסיכומים. נסה אחד מהקיצורים למטה או כתוב מה שצריך.` },
  ]);
  const [input, setInput] = useState('');
  const [loading, setLoading] = useState(false);
  const [unread, setUnread] = useState(1);
  const endRef = useRef(null);

  useEffect(() => {
    if (open) setUnread(0);
  }, [open]);

  useEffect(() => {
    endRef.current?.scrollTo({ top: 9999, behavior: 'smooth' });
  }, [messages]);

  const send = async (text) => {
    const t = (text || input).trim();
    if (!t || loading) return;
    setMessages(m => [...m, { role: 'user', text: t }]);
    setInput('');
    setLoading(true);
    try {
      const store = SyncStore.get();
      const openTasks = (store.tasks || []).filter(x => x.status !== 'done' && x.status !== 'archived').slice(0, 15);
      const recentReports = (store.reports || []).slice(-5);
      const openRejects = (store.directRejects || []).concat(
        (store.reports || []).flatMap(r => r.rejects || [])
      ).filter(r => !r.resolved).slice(0, 10);
      const projects = YBP_DATA?.projects || [];

      const ctx = [
        'אתה עוזר אישי למנהל פרויקטים בבנייה — YBP Projects.',
        'ענה תמיד בעברית. תשובות קצרות, מעשיות, ממוקדות.',
        `פרויקטים פעילים: ${projects.map(p => p.name).join(', ')}.`,
        `משימות פתוחות (${openTasks.length}): ${openTasks.slice(0,5).map(t => `${t.title} (אחראי: ${t.assignee||'—'}, יעד: ${t.due||'—'})`).join(' | ')}.`,
        openRejects.length ? `ריג'קטים פתוחים (${openRejects.length}): ${openRejects.slice(0,4).map(r => r.title).join(', ')}.` : '',
        recentReports.length ? `דוחות אחרונים: ${recentReports.map(r => r.title).join(', ')}.` : '',
      ].filter(Boolean).join(' ');

      // קבל session token לאימות
      let authToken = '';
      try {
        if (window.YBP_SUPABASE) {
          const sb = await window.YBP_SUPABASE.getClient();
          const { data: { session } } = await sb.auth.getSession();
          if (session?.access_token) authToken = session.access_token;
        }
      } catch {}

      const res = await fetch(AI_CHAT_FN, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          ...(authToken ? { 'Authorization': `Bearer ${authToken}` } : {}),
        },
        body: JSON.stringify({
          messages: [{ role: 'user', content: `${ctx}\n\nשאלה: ${t}` }],
        }),
      });
      const data = await res.json();
      const reply = data.reply || 'לא קיבלתי תשובה. נסה שוב.';
      setMessages(m => [...m, { role: 'agent', text: reply }]);
    } catch (e) {
      setMessages(m => [...m, { role: 'agent', text: 'סליחה, לא הצלחתי להשיב כרגע. נסה שוב.' }]);
    }
    setLoading(false);
  };

  // חשוף פונקציה גלובלית לפתיחה מה-SessionBar
  React.useEffect(() => {
    window.openAiAgent = () => setOpen(true);
    window.closeAiAgent = () => setOpen(false);
    return () => { delete window.openAiAgent; delete window.closeAiAgent; };
  }, []);

  return (
    <>
      {/* Drawer */}
      {open && (
        <div style={{
          position: 'fixed', bottom: 60, left: 24, zIndex: 1399,
          width: 'min(380px, 92vw)', height: 'min(560px, 70vh)',
          background: '#fff', borderRadius: 14, boxShadow: '0 20px 60px rgba(0,0,0,0.25)',
          display: 'flex', flexDirection: 'column', fontFamily: 'Heebo, Assistant, sans-serif',
          direction: 'rtl', border: '1px solid #E2E7EF', overflow: 'hidden',
          animation: 'aiSlide .2s ease',
        }}>
          {/* Header */}
          <div style={{ padding: '14px 16px', background: 'linear-gradient(135deg, #1B2B4B, #2E4270)', color: '#fff', display: 'flex', alignItems: 'center', gap: 10 }}>
            <div style={{ width: 32, height: 32, borderRadius: 16, background: 'rgba(255,255,255,0.15)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 16 }}>🤖</div>
            <div>
              <div style={{ fontSize: 14, fontWeight: 700 }}>YBP Assistant</div>
              <div style={{ fontSize: 10.5, opacity: 0.75 }}>מופעל Claude · מחובר לפרויקטים שלך</div>
            </div>
            <button onClick={() => setOpen(false)} style={{ marginRight: 'auto', background: 'transparent', border: 'none', color: '#fff', cursor: 'pointer', padding: 4, fontSize: 18 }}>×</button>
          </div>

          {/* Messages */}
          <div ref={endRef} style={{ flex: 1, overflowY: 'auto', padding: '16px', background: '#FAFBFC' }}>
            {messages.map((m, i) => (
              <div key={i} style={{
                marginBottom: 10, display: 'flex',
                justifyContent: m.role === 'user' ? 'flex-start' : 'flex-end',
              }}>
                <div style={{
                  maxWidth: '85%', padding: '9px 13px', borderRadius: 12,
                  background: m.role === 'user' ? '#1B2B4B' : '#fff',
                  color: m.role === 'user' ? '#fff' : '#1E293B',
                  fontSize: 13, lineHeight: 1.5,
                  border: m.role === 'agent' ? '1px solid #E2E7EF' : 'none',
                  whiteSpace: 'pre-wrap',
                }}>{m.text}</div>
              </div>
            ))}
            {loading && (
              <div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: 10 }}>
                <div style={{ padding: '9px 13px', borderRadius: 12, background: '#fff', border: '1px solid #E2E7EF', fontSize: 13, color: '#64748B' }}>
                  חושב<span className="aiDots">...</span>
                </div>
              </div>
            )}
            {messages.length === 1 && (
              <div style={{ marginTop: 14 }}>
                <div style={{ fontSize: 11, color: '#64748B', marginBottom: 6, fontWeight: 600 }}>הצעות:</div>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                  {STARTER_SUGGESTIONS.map((s, i) => (
                    <button key={i} onClick={() => send(s.text)} style={{
                      background: '#fff', border: '1px solid #E2E7EF', padding: '8px 12px', borderRadius: 8,
                      fontSize: 12.5, textAlign: 'right', cursor: 'pointer', fontFamily: 'inherit',
                      display: 'flex', alignItems: 'center', gap: 8, color: '#1E293B',
                    }} onMouseEnter={e => e.currentTarget.style.borderColor = '#3B6FD4'} onMouseLeave={e => e.currentTarget.style.borderColor = '#E2E7EF'}>
                      <span>{s.icon}</span>
                      <span style={{ flex: 1 }}>{s.text}</span>
                    </button>
                  ))}
                </div>
              </div>
            )}
          </div>

          {/* Input */}
          <div style={{ padding: 10, borderTop: '1px solid #E2E7EF', background: '#fff', display: 'flex', gap: 6 }}>
            <input value={input} onChange={e => setInput(e.target.value)}
              onKeyDown={e => e.key === 'Enter' && send()}
              placeholder="כתוב הודעה..."
              style={{ flex: 1, padding: '9px 12px', border: '1px solid #E2E7EF', borderRadius: 8, fontSize: 13, fontFamily: 'inherit', direction: 'rtl' }}/>
            <button onClick={() => send()} disabled={!input.trim() || loading} style={{
              background: '#1B2B4B', color: '#fff', border: 'none', borderRadius: 8, padding: '0 14px',
              fontSize: 16, cursor: input.trim() && !loading ? 'pointer' : 'not-allowed',
              opacity: input.trim() && !loading ? 1 : 0.4, fontFamily: 'inherit',
            }}>↑</button>
          </div>
        </div>
      )}
      <style>{`
        @keyframes aiSlide { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }
        .aiDots::after { content: ''; animation: aiDots 1.4s infinite; }
        @keyframes aiDots { 0%,20% { content: '.'; } 40% { content: '..'; } 60%,100% { content: '...'; } }
      `}</style>
    </>
  );
};

window.AiAgent = AiAgent;
})();
