// פיצ'ר 1 — קלט קולי חכם לטפסים
// Web Speech API → Make webhook → Claude Haiku → מילוי שדות
(function(){
const { useState, useRef, useEffect, useCallback } = React;

// ── Make webhook — תרחיש: process-form-voice — צריך יצירה ב-Make eu2 ────────
const MAKE_VOICE_WEBHOOK = 'https://hook.eu2.make.com/PLACEHOLDER_VOICE_FORM_EU2';
const MAKE_SK = '1h4M4SEXbhoYF1YVW1mS6YJZs84yxSVHaBjPDDxMpbak';

// ── סכמות שדות לפי סוג טופס ────────────────────────────────────────────────
const FORM_SCHEMAS = {
  daily: {
    name: 'דוח יומי',
    fields: ['issues', 'notes', 'statusReason', 'contractors', 'rejects'],
    prompt: `אתה עוזר לניהול אתר בנייה. המשתמש מדבר בחופשיות בעברית ומתאר דוח יומי.
חלץ מהטקסט את השדות הבאים ותחזיר JSON בדיוק:
{
  "issues": "בעיות שהוזכרו",
  "notes": "הערות כלליות",
  "statusReason": "סיבה לסטטוס יום מיוחד אם הוזכרה",
  "contractors": ["מקצוע1", "מקצוע2"],
  "rejectTitle": "כותרת ריג'קט אם הוזכר",
  "rejectDescription": "תיאור ריג'קט",
  "rejectAssignee": "שם האחראי לתיקון",
  "rejectDue": "תאריך יעד YYYY-MM-DD"
}
אם שדה לא הוזכר — השאר ריק "". תאריכים — המר לפורמט YYYY-MM-DD (היום: ${new Date().toISOString().slice(0,10)}).`
  },
  meeting: {
    name: 'סיכום פגישה',
    fields: ['title', 'location', 'decision', 'findingTitle', 'findingDescription', 'findingAssignee'],
    prompt: `אתה עוזר לניהול אתר בנייה. המשתמש מדבר בחופשיות בעברית ומתאר פגישה.
חלץ מהטקסט את השדות הבאים ותחזיר JSON בדיוק:
{
  "title": "כותרת הפגישה",
  "location": "מיקום הפגישה",
  "decision": "החלטה שהתקבלה",
  "findingTitle": "כותרת ממצא/ריג'קט אם הוזכר",
  "findingDescription": "תיאור הממצא",
  "findingAssignee": "אחראי לטיפול",
  "findingDue": "תאריך יעד YYYY-MM-DD",
  "nextMeetingDate": "תאריך פגישה הבאה YYYY-MM-DD"
}
אם שדה לא הוזכר — השאר ריק "". היום: ${new Date().toISOString().slice(0,10)}.`
  },
  rejects: {
    name: 'דוח ריג\'קטים',
    fields: ['title', 'description', 'location', 'assignee', 'due'],
    prompt: `אתה עוזר לניהול אתר בנייה. המשתמש מדבר בחופשיות בעברית ומתאר ריג'קט/ממצא.
חלץ מהטקסט את השדות הבאים ותחזיר JSON בדיוק:
{
  "title": "כותרת הריג'קט",
  "description": "תיאור מפורט",
  "location": "מיקום בשטח",
  "assignee": "שם האחראי לתיקון",
  "due": "תאריך יעד YYYY-MM-DD",
  "severity": "high/medium/low"
}
אם שדה לא הוזכר — השאר ריק "". היום: ${new Date().toISOString().slice(0,10)}.`
  },
  infra: {
    name: 'תיעוד תשתיות',
    fields: ['notes', 'issues', 'location'],
    prompt: `אתה עוזר לניהול אתר בנייה. המשתמש מדבר בחופשיות בעברית ומתאר תשתיות.
חלץ מהטקסט את השדות הבאים ותחזיר JSON בדיוק:
{
  "notes": "הערות כלליות על התשתיות",
  "issues": "בעיות שזוהו",
  "location": "מיקום בשטח",
  "systemType": "סוג מערכת (חשמל/אינסטלציה/מיזוג/כיבוי)"
}
אם שדה לא הוזכר — השאר ריק "". היום: ${new Date().toISOString().slice(0,10)}.`
  },
  site: {
    name: 'תיעוד אתר',
    fields: ['notes', 'issues'],
    prompt: `אתה עוזר לניהול אתר בנייה. המשתמש מדבר בעברית ומתאר מצב האתר.
חלץ מהטקסט את השדות הבאים ותחזיר JSON בדיוק:
{
  "notes": "הערות כלליות",
  "issues": "בעיות שזוהו",
  "location": "מיקום ספציפי",
  "actionRequired": "פעולה נדרשת"
}
אם שדה לא הוזכר — השאר ריק "". היום: ${new Date().toISOString().slice(0,10)}.`
  },
};

// ── קומפוננט כפתור מיקרופון ─────────────────────────────────────────────────
const VoiceInputButton = ({ formType = 'daily', onFill, position = 'fab' }) => {
  const { isMobile } = useViewport();
  const [phase, setPhase] = useState('idle'); // idle | listening | processing | done | error
  const [transcript, setTranscript] = useState('');
  const [error, setError] = useState('');
  const [result, setResult] = useState(null);
  const [showPanel, setShowPanel] = useState(false);
  const recognitionRef = useRef(null);
  const schema = FORM_SCHEMAS[formType] || FORM_SCHEMAS.daily;

  // ── בדיקת תמיכה ────────────────────────────────────────────────────────
  const isSupported = typeof window !== 'undefined' &&
    ('SpeechRecognition' in window || 'webkitSpeechRecognition' in window);

  // ── Web Speech API ──────────────────────────────────────────────────────
  const startListening = useCallback(() => {
    if (!isSupported) { setError('הדפדפן לא תומך בקלט קולי. נסה Chrome.'); return; }
    const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
    const rec = new SpeechRecognition();
    rec.lang = 'he-IL';
    rec.continuous = false;
    rec.interimResults = true;
    rec.maxAlternatives = 1;

    recognitionRef.current = rec;
    setTranscript('');
    setError('');
    setResult(null);
    setPhase('listening');
    setShowPanel(true);

    rec.onresult = (e) => {
      const interim = Array.from(e.results).map(r => r[0].transcript).join('');
      setTranscript(interim);
    };

    rec.onerror = (e) => {
      setError('שגיאה בהקלטה: ' + (e.error === 'no-speech' ? 'לא זוהתה דיבור' : e.error));
      setPhase('error');
    };

    rec.onend = () => {
      if (phase !== 'processing') processTranscript();
    };

    rec.start();
  }, [isSupported, phase]);

  const stopListening = useCallback(() => {
    recognitionRef.current?.stop();
    setPhase('processing');
  }, []);

  // ── שליחה ל-Make webhook ────────────────────────────────────────────────
  const processTranscript = useCallback(async () => {
    const text = transcript;
    if (!text.trim()) { setPhase('idle'); setShowPanel(false); return; }
    setPhase('processing');

    try {
      const resp = await fetch(MAKE_VOICE_WEBHOOK, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          text,
          formType,
          prompt: schema.prompt,
          model: 'claude-haiku-4-5-20251001',
        }),
      });

      if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
      const data = await resp.json();

      // נקה טקסט גולמי מיד
      setTranscript('');

      setResult(data);
      setPhase('done');
    } catch (err) {
      // Fallback: Mock בפרוטוטייפ — מדמה תשובה מ-Make
      console.warn('[VoiceInput] Make webhook לא זמין — משתמש ב-mock', err);
      const mockResult = generateMockResult(text, formType);
      setTranscript('');
      setResult(mockResult);
      setPhase('done');
    }
  }, [transcript, formType, schema.prompt]);

  // ── Mock result לפרוטוטייפ ─────────────────────────────────────────────
  const generateMockResult = (text, type) => {
    const lower = text.toLowerCase();
    const today = new Date();
    const nextWeek = new Date(today); nextWeek.setDate(nextWeek.getDate() + 7);
    const fmtDate = d => d.toISOString().slice(0,10);

    if (type === 'daily') return {
      issues: lower.includes('ריצוף') ? 'איחור בעבודות הריצוף עקב חומר שלא הגיע' : text.slice(0, 80),
      notes: 'עודכן דרך קלט קולי',
      rejectTitle: lower.includes('ריג') || lower.includes('reject') ? text.slice(0, 40) : '',
      rejectAssignee: lower.match(/[אבגדהוזחטיכלמנסעפצקרשת][א-ת]+ [א-ת]+/)?.[0] || '',
      rejectDue: lower.includes('מאי') ? fmtDate(nextWeek) : '',
    };
    if (type === 'meeting') return {
      title: text.slice(0, 50),
      decision: text.slice(0, 80),
      findingTitle: lower.includes('ריג') ? text.slice(0, 40) : '',
    };
    if (type === 'rejects') return {
      title: text.slice(0, 50),
      description: text,
      location: lower.match(/[במטב][א-ת ]+/)?.[0]?.slice(0, 20) || '',
      severity: lower.includes('דחוף') || lower.includes('סכנה') ? 'high' : 'medium',
      due: fmtDate(nextWeek),
    };
    return { notes: text };
  };

  // ── החלת תוצאה על הטופס ────────────────────────────────────────────────
  const applyResult = () => {
    if (onFill && result) onFill(result);
    setShowPanel(false);
    setPhase('idle');
    setResult(null);
  };

  const dismiss = () => {
    recognitionRef.current?.stop();
    setShowPanel(false);
    setPhase('idle');
    setTranscript('');
    setResult(null);
  };

  // ── pulse animation ─────────────────────────────────────────────────────
  useEffect(() => {
    const style = document.getElementById('voice-pulse-style');
    if (!style) {
      const s = document.createElement('style');
      s.id = 'voice-pulse-style';
      s.textContent = `
        @keyframes ybp-pulse { 0%,100%{transform:scale(1);opacity:1} 50%{transform:scale(1.15);opacity:0.85} }
        @keyframes ybp-wave { 0%{transform:scaleY(0.3)} 50%{transform:scaleY(1)} 100%{transform:scaleY(0.3)} }
        @keyframes ybp-spin { to{transform:rotate(360deg)} }
        .ybp-voice-fab { transition: box-shadow 0.2s, transform 0.15s; }
        .ybp-voice-fab:hover { transform: scale(1.08) !important; box-shadow: 0 6px 20px rgba(220,38,38,0.4) !important; }
      `;
      document.head.appendChild(s);
    }
  }, []);

  const isListening = phase === 'listening';
  const isProcessing = phase === 'processing';
  const isDone = phase === 'done';

  // ── FAB כפתור ──────────────────────────────────────────────────────────
  const fabStyle = {
    position: 'fixed',
    bottom: 88,
    left: 20,
    width: 52,
    height: 52,
    borderRadius: 26,
    border: 'none',
    background: isListening ? '#dc2626' : isDone ? '#059669' : isProcessing ? '#f59e0b' : '#1a2c4a',
    color: '#fff',
    cursor: 'pointer',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    zIndex: 8000,
    boxShadow: isListening
      ? '0 0 0 8px rgba(220,38,38,0.2), 0 4px 14px rgba(220,38,38,0.5)'
      : '0 4px 14px rgba(26,44,74,0.35)',
    animation: isListening ? 'ybp-pulse 1.2s ease-in-out infinite' : 'none',
  };

  // ── פאנל ───────────────────────────────────────────────────────────────
  const panelStyle = {
    position: 'fixed',
    bottom: 150,
    left: 16,
    width: 300,
    background: '#fff',
    borderRadius: 14,
    boxShadow: '0 10px 40px rgba(0,0,0,0.18)',
    border: '1px solid #e5e7eb',
    fontFamily: 'Assistant, sans-serif',
    direction: 'rtl',
    zIndex: 8001,
    overflow: 'hidden',
  };

  return (
    <>
      {/* FAB כפתור מיקרופון */}
      <button
        className="ybp-voice-fab"
        onClick={() => {
          if (isListening) stopListening();
          else if (isDone) applyResult();
          else if (phase === 'idle') startListening();
        }}
        style={fabStyle}
        title={isListening ? 'עצור הקלטה' : isDone ? 'החל שדות' : 'קלט קולי'}
      >
        {isListening ? (
          /* גלים בזמן הקלטה */
          <div style={{ display: 'flex', gap: 2, alignItems: 'center', height: 22 }}>
            {[0,1,2,3,4].map(i => (
              <div key={i} style={{
                width: 3, background: '#fff', borderRadius: 2,
                height: 8 + (i % 3) * 8,
                animation: `ybp-wave 0.8s ease-in-out ${i * 0.12}s infinite`,
              }}/>
            ))}
          </div>
        ) : isProcessing ? (
          <div style={{ width: 22, height: 22, border: '2.5px solid rgba(255,255,255,0.3)', borderTopColor: '#fff', borderRadius: 11, animation: 'ybp-spin 0.7s linear infinite' }}/>
        ) : isDone ? (
          <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12"/></svg>
        ) : (
          <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <path d="M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"/>
            <path d="M19 10v2a7 7 0 0 1-14 0v-2"/>
            <line x1="12" y1="19" x2="12" y2="23"/>
            <line x1="8" y1="23" x2="16" y2="23"/>
          </svg>
        )}
      </button>

      {/* label קטן מתחת */}
      <div style={{
        position: 'fixed', bottom: 73, left: 8, width: 68,
        textAlign: 'center', fontSize: 10, color: '#6b7280', fontFamily: 'Assistant, sans-serif',
        zIndex: 8000, pointerEvents: 'none',
      }}>
        {isListening ? 'מקליט...' : isDone ? 'להחיל ✓' : isProcessing ? 'מנתח...' : 'קלט קולי'}
      </div>

      {/* פאנל מצב */}
      {showPanel && (
        <div style={panelStyle}>
          {/* Header */}
          <div style={{ background: isListening ? '#dc2626' : isDone ? '#059669' : '#1a2c4a', padding: '12px 16px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <div style={{ color: '#fff' }}>
              <div style={{ fontSize: 13, fontWeight: 700 }}>
                {isListening ? '🎙️ מקליט...' : isProcessing ? '⚙️ מנתח טקסט...' : isDone ? '✅ זוהו שדות' : schema.name}
              </div>
              <div style={{ fontSize: 11, opacity: 0.8, marginTop: 2 }}>
                {isListening ? 'דבר בחופשיות בעברית' : isProcessing ? 'Claude Haiku מנתח את הטקסט' : isDone ? 'לחץ להחיל על הטופס' : ''}
              </div>
            </div>
            <button onClick={dismiss} style={{ background: 'rgba(255,255,255,0.2)', border: 'none', color: '#fff', width: 26, height: 26, borderRadius: 13, cursor: 'pointer', fontSize: 14, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>✕</button>
          </div>

          {/* תוכן */}
          <div style={{ padding: 14 }}>
            {/* Listening — גלים + transcript חי */}
            {isListening && (
              <>
                <div style={{ display: 'flex', gap: 3, justifyContent: 'center', marginBottom: 12, height: 32, alignItems: 'center' }}>
                  {Array.from({length: 12}).map((_, i) => (
                    <div key={i} style={{
                      width: 3, background: '#dc2626', borderRadius: 2,
                      height: 6 + Math.sin(i * 0.5) * 18,
                      animation: `ybp-wave ${0.6 + i * 0.05}s ease-in-out ${i * 0.07}s infinite`,
                      opacity: 0.7 + (i % 3) * 0.1,
                    }}/>
                  ))}
                </div>
                {transcript && (
                  <div style={{ background: '#fef2f2', border: '1px solid #fecaca', borderRadius: 8, padding: '10px 12px', fontSize: 12.5, color: '#991b1b', lineHeight: 1.5, minHeight: 40, maxHeight: 80, overflow: 'hidden' }}>
                    {transcript}
                  </div>
                )}
                <button onClick={stopListening} style={{ width: '100%', marginTop: 12, padding: '10px', background: '#dc2626', color: '#fff', border: 'none', borderRadius: 8, fontSize: 13, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit' }}>
                  ⏹ עצור הקלטה
                </button>
              </>
            )}

            {/* Processing */}
            {isProcessing && (
              <div style={{ textAlign: 'center', padding: '16px 0' }}>
                <div style={{ width: 32, height: 32, border: '3px solid #e5e7eb', borderTopColor: '#1a2c4a', borderRadius: 16, animation: 'ybp-spin 0.7s linear infinite', margin: '0 auto 10px' }}/>
                <div style={{ fontSize: 12, color: '#6b7280' }}>שולח ל-Make → Claude מנתח...</div>
              </div>
            )}

            {/* Done — מציג שדות שזוהו */}
            {isDone && result && (
              <>
                <div style={{ fontSize: 11, fontWeight: 700, color: '#059669', marginBottom: 8, display: 'flex', alignItems: 'center', gap: 4 }}>
                  ✅ שדות שזוהו אוטומטית:
                </div>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 6, maxHeight: 160, overflowY: 'auto' }}>
                  {Object.entries(result).filter(([,v]) => v && v !== '').map(([key, val]) => (
                    <div key={key} style={{ background: '#f0fdf4', border: '1px solid #bbf7d0', borderRadius: 6, padding: '6px 10px' }}>
                      <div style={{ fontSize: 10, fontWeight: 700, color: '#059669', textTransform: 'uppercase', letterSpacing: 0.3 }}>{key}</div>
                      <div style={{ fontSize: 12.5, color: '#166534', marginTop: 2, lineHeight: 1.4 }}>{Array.isArray(val) ? val.join(', ') : String(val).slice(0, 80)}</div>
                    </div>
                  ))}
                </div>
                <div style={{ display: 'flex', gap: 8, marginTop: 12 }}>
                  <button onClick={applyResult} style={{ flex: 1, padding: '9px', background: '#059669', color: '#fff', border: 'none', borderRadius: 7, fontSize: 13, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit' }}>
                    החל על הטופס ✓
                  </button>
                  <button onClick={() => { setPhase('idle'); startListening(); }} style={{ padding: '9px 12px', background: '#fff', color: '#374151', border: '1px solid #e5e7eb', borderRadius: 7, fontSize: 12, cursor: 'pointer', fontFamily: 'inherit' }}>
                    נסה שוב
                  </button>
                </div>
              </>
            )}

            {/* Error */}
            {phase === 'error' && (
              <div style={{ textAlign: 'center', padding: '12px 0' }}>
                <div style={{ fontSize: 12, color: '#dc2626', marginBottom: 10 }}>⚠️ {error || 'שגיאה בעיבוד'}</div>
                <button onClick={startListening} style={{ padding: '8px 16px', background: '#fff', border: '1px solid #e5e7eb', borderRadius: 6, fontSize: 12, cursor: 'pointer', fontFamily: 'inherit' }}>נסה שוב</button>
              </div>
            )}
          </div>
        </div>
      )}
    </>
  );
};

// ── hook נוח לשימוש בטפסים ─────────────────────────────────────────────────
const useVoiceInput = (formType) => {
  const [voiceData, setVoiceData] = useState(null);

  const handleFill = useCallback((data) => {
    setVoiceData(data);
  }, []);

  return {
    voiceData,
    clearVoiceData: () => setVoiceData(null),
    VoiceButton: () => React.createElement(VoiceInputButton, { formType, onFill: handleFill }),
  };
};

Object.assign(window, { VoiceInputButton, useVoiceInput, FORM_SCHEMAS });
})();
