// PLANERAssistant.jsx
const { useState, useRef, useEffect } = React;

function PlanerAssistant({ entries, lang, onAddEntry }) {
  const [isListening, setIsListening] = useState(false);
  const [transcript, setTranscript] = useState('');
  const [response, setResponse] = useState('');
  const [isProcessing, setIsProcessing] = useState(false);
  const recognitionRef = useRef(null);
  const synthRef = useRef(window.speechSynthesis);

  // تهيئة التعرف على الصوت
  useEffect(() => {
    if (!('webkitSpeechRecognition' in window) && !('SpeechRecognition' in window)) {
      return;
    }
    const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
    const recognition = new SpeechRecognition();
    recognition.lang = lang === 'ar' ? 'ar-EG' : 'en-US';
    recognition.continuous = false;
    recognition.interimResults = false;

    recognition.onresult = (event) => {
      const text = event.results[0][0].transcript;
      setTranscript(text);
      handleSendToAI(text);
    };

    recognition.onerror = (event) => {
      console.error('خطأ في التعرف على الصوت:', event.error);
      setIsListening(false);
      if (event.error === 'not-allowed') {
        setResponse('الرجاء السماح للتطبيق باستخدام الميكروفون.');
      }
    };

    recognition.onend = () => {
      setIsListening(false);
    };

    recognitionRef.current = recognition;
  }, [lang]);

  // إرسال النص إلى Puter AI
  async function handleSendToAI(text) {
    if (!text.trim()) return;
    setIsProcessing(true);
    setResponse('...');
    try {
      const context = buildContext(entries, lang);
      const prompt = `
        أنت مساعد مالي ذكي لتطبيق PARAPLANER.
        إليك بيانات المستخدم الحالية:
        ${context}

        المستخدم يسأل: "${text}"
        قدم إجابة مفيدة ودقيقة باللغة المناسبة.
        إذا طلب المستخدم إضافة مصروف، استخرج المبلغ وقل "تم إضافة مصروف بقيمة X يورو" مع ذكر المبلغ.
      `;

      const result = await puter.ai.chat(prompt);
      const answer = result.message || result || 'لم أستطع فهم السؤال، حاول مرة أخرى.';
      setResponse(answer);
      speakText(answer);

      // معالجة الأوامر البسيطة (إضافة مصروف)
      if (answer.includes('إضافة مصروف') || answer.includes('أضف مصروف')) {
        const match = answer.match(/(\d+\.?\d*)/);
        if (match) {
          const amount = parseFloat(match[1]);
          if (!isNaN(amount) && amount > 0) {
            onAddEntry({
              id: makeId(),
              kind: 'expense',
              date: todayISO(),
              category: 'other',
              term: 'day',
              label: 'مصروف من المساعد الصوتي',
              amount: amount,
              recurring: false,
              expiresAt: null,
              exceptions: {},
            });
            setResponse(prev => prev + ' (تمت الإضافة بنجاح)');
          }
        }
      }
    } catch (error) {
      console.error('خطأ في الاتصال بـ Puter AI:', error);
      setResponse('حدث خطأ في الاتصال بالمساعد، تأكد من اتصال الإنترنت.');
    } finally {
      setIsProcessing(false);
    }
  }

  // بناء سياق البيانات المالية
  function buildContext(entries, lang) {
    const totalIncome = entries.filter(e => e.kind === 'income').reduce((s, e) => s + e.amount, 0);
    const totalExpenses = entries.filter(e => e.kind === 'expense').reduce((s, e) => s + e.amount, 0);
    const balance = totalIncome - totalExpenses;
    const recurring = entries.filter(e => e.recurring && e.kind === 'expense').length;
    const count = entries.length;
    return `
      - إجمالي الدخل: ${totalIncome} €
      - إجمالي المصاريف: ${totalExpenses} €
      - الرصيد: ${balance} €
      - عدد المصاريف المتكررة: ${recurring}
      - عدد العمليات الكلي: ${count}
    `;
  }

  // النطق بالرد
  function speakText(text) {
    if (!synthRef.current) return;
    synthRef.current.cancel();
    const utterance = new SpeechSynthesisUtterance(text);
    utterance.lang = lang === 'ar' ? 'ar-EG' : 'en-US';
    utterance.rate = 1;
    utterance.pitch = 1;
    synthRef.current.speak(utterance);
  }

  // بدء/إيقاف التسجيل
  function toggleListening() {
    if (isListening) {
      recognitionRef.current?.stop();
      setIsListening(false);
    } else {
      if (!recognitionRef.current) {
        setResponse('المتصفح لا يدعم التعرف على الصوت.');
        return;
      }
      setTranscript('');
      setResponse('');
      try {
        recognitionRef.current.start();
        setIsListening(true);
      } catch (e) {
        console.warn(e);
        setResponse('حدث خطأ في بدء التسجيل، حاول مرة أخرى.');
      }
    }
  }

  // دوال مساعدة
  function makeId() {
    return Math.random().toString(36).slice(2, 10) + Date.now().toString(36);
  }
  function todayISO() {
    return new Date().toISOString().slice(0, 10);
  }

  // عرض واجهة المساعد
  return (
    <div className="panel" style={{ background: 'rgba(212,175,55,0.05)', borderColor: 'var(--gold-dim)' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, flexWrap: 'wrap' }}>
        <button
          onClick={toggleListening}
          className={`quick-fab ${isListening ? 'quick-fab--active' : ''}`}
          style={{
            background: isListening ? 'rgba(224,100,90,0.2)' : 'rgba(212,175,55,0.12)',
            borderColor: isListening ? 'var(--red)' : 'var(--gold-dim)',
            color: isListening ? 'var(--red)' : 'var(--gold)',
            padding: '8px 16px',
            width: 'auto',
            gap: 8,
          }}
        >
          <Icon name={isListening ? 'mic-off' : 'mic'} size={18} />
          <span>{isListening ? 'أوقف التسجيل' : 'تحدث إلى المساعد'}</span>
        </button>
        {isProcessing && <span style={{ color: 'var(--gold)', fontSize: 13 }}>جاري التفكير...</span>}
      </div>

      {transcript && (
        <div style={{ marginTop: 12, fontSize: 13, color: 'var(--muted)' }}>
          <strong>أنت:</strong> {transcript}
        </div>
      )}

      {response && (
        <div style={{ marginTop: 12, padding: 12, background: 'var(--surface-2)', borderRadius: 10 }}>
          <strong style={{ color: 'var(--gold)' }}>المساعد:</strong>
          <p style={{ margin: '6px 0 0', whiteSpace: 'pre-wrap', lineHeight: 1.6 }}>{response}</p>
        </div>
      )}

      <p style={{ fontSize: 11, color: 'var(--muted)', marginTop: 12 }}>
        💡 اضغط على الزر وتحدث بسؤالك المالي، وسيجيبك المساعد الذكي.
        {lang === 'ar' ? ' يمكنك أيضاً أن تطلب إضافة مصروف (مثلاً: "أضف مصروف 20 يورو").' : ''}
      </p>
    </div>
  );
}