// פיצ'ר 2 — הקלטת פגישה פיזית, תמלול וסיכום אוטומטי
// MediaRecorder → Make webhook → Whisper → Claude Sonnet → Drive + App
(function(){
const { useState, useRef, useEffect, useCallback } = React;

// ── Make webhooks ────────────────────────────────────────────────────────────
const MAKE_MEETING_WEBHOOK  = 'https://hook.eu2.make.com/PLACEHOLDER_MEETING_RECORDING_EU2'; // תרחיש: process-meeting-recording — צריך יצירה ב-Make eu2
const MAKE_PROJECTS_WEBHOOK = 'https://hook.eu2.make.com/1geqn8hdj9bhqnwwgwn2pydsjw967fhh'; // YBP - קבלת פרויקטים v2
const MAKE_SK = '1h4M4SEXbhoYF1YVW1mS6YJZs84yxSVHaBjPDDxMpbak';

// ── עזרים ───────────────────────────────────────────────────────────────────
const fmtDuration = (sec) => {
  const h = Math.floor(sec / 3600);
  const m = Math.floor((sec % 3600) / 60);
  const s = sec % 60;
  if (h > 0) return `${h}:${String(m).padStart(2,'0')}:${String(s).padStart(2,'0')}`;
  return `${String(m).padStart(2,'0')}:${String(s).padStart(2,'0')}`;
};

const fmtFileSizeMB = (bytes) => (bytes / (1024 * 1024)).toFixed(1) + ' MB';

const todayISO = () => new Date().toISOString().slice(0,10);

// ── מסך הקלטת פגישה ─────────────────────────────────────────────────────────
const MeetingRecorderScreen = ({ projectId: initProjectId, onBack, onOpenProtocol }) => {
  const { isMobile } = useViewport();
  // ── state ─────────────────────────────────────────────────────────────
  const [phase, setPhase] = useState('setup');
  // phases: setup | recording | processing | result | viewTranscript | error

  const [projects, setProjects] = useState([]);
  const [selectedProjectId, setSelectedProjectId] = useState(initProjectId || '');
  const [topic, setTopic] = useState('');
  const [meetingDate, setMeetingDate] = useState(todayISO());
  const [elapsedSec, setElapsedSec] = useState(0);
  const [audioSize, setAudioSize] = useState(0);
  const [result, setResult] = useState(null); // { summary, tasks, transcriptId, driveUrls }
  const [activeTab, setActiveTab] = useState('summary'); // summary | tasks | transcript
  const [error, setError] = useState('');

  // ── refs ──────────────────────────────────────────────────────────────
  const mediaRecorderRef = useRef(null);
  const audioChunksRef = useRef([]);
  const timerRef = useRef(null);
  const streamRef = useRef(null);

  // ── טען פרויקטים ─────────────────────────────────────────────────────
  useEffect(() => {
    const loadProjects = async () => {
      try {
        const resp = await fetch(MAKE_PROJECTS_WEBHOOK, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ _sk: MAKE_SK, userId: ((window.YBP_AUTH && window.YBP_AUTH.getCurrentUser) ? window.YBP_AUTH.getCurrentUser().email : YBP_DATA.user?.id) || 'u1' }) });
        if (resp.ok) {
          const data = await resp.json();
          setProjects(data.projects || []);
        } else throw new Error();
      } catch {
        // fallback: data.js
        setProjects(YBP_DATA.projects.map(p => ({ id: p.id, name: p.name, pm: p.pm })));
      }
    };
    loadProjects();
  }, []);

  // ── timer ────────────────────────────────────────────────────────────
  useEffect(() => {
    if (phase === 'recording') {
      timerRef.current = setInterval(() => setElapsedSec(s => s + 1), 1000);
    } else {
      clearInterval(timerRef.current);
    }
    return () => clearInterval(timerRef.current);
  }, [phase]);

  // ── התחל הקלטה ────────────────────────────────────────────────────────
  const startRecording = useCallback(async () => {
    if (!topic.trim()) { setError('נא להזין נושא פגישה'); return; }
    setError('');

    try {
      const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
      streamRef.current = stream;
      audioChunksRef.current = [];

      const mimeType = MediaRecorder.isTypeSupported('audio/webm;codecs=opus')
        ? 'audio/webm;codecs=opus'
        : MediaRecorder.isTypeSupported('audio/webm') ? 'audio/webm' : 'audio/ogg';

      const recorder = new MediaRecorder(stream, { mimeType });
      mediaRecorderRef.current = recorder;

      recorder.ondataavailable = (e) => {
        if (e.data.size > 0) {
          audioChunksRef.current.push(e.data);
          setAudioSize(prev => prev + e.data.size);
        }
      };

      recorder.start(10000); // chunk כל 10 שניות
      setElapsedSec(0);
      setAudioSize(0);
      setPhase('recording');
    } catch (err) {
      setError('לא ניתן לגשת למיקרופון: ' + err.message);
    }
  }, [topic]);

  // ── עצור הקלטה ────────────────────────────────────────────────────────
  const stopRecording = useCallback(() => {
    if (mediaRecorderRef.current?.state === 'recording') {
      mediaRecorderRef.current.stop();
    }
    streamRef.current?.getTracks().forEach(t => t.stop());
    setPhase('processing');
    setTimeout(processAudio, 500); // תן לRecorder לסיים
  }, []);

  // ── עיבוד ושליחה ל-Make ───────────────────────────────────────────────
  const processAudio = useCallback(async () => {
    const chunks = audioChunksRef.current;
    if (!chunks.length) { setError('לא הוקלט אודיו'); setPhase('error'); return; }

    const mimeType = chunks[0].type || 'audio/webm';
    const audioBlob = new Blob(chunks, { type: mimeType });

    const project = (projects.length ? projects : YBP_DATA.projects).find(p => p.id === selectedProjectId);
    const projectName = project?.name || selectedProjectId;
    const pmName = ((window.YBP_AUTH && window.YBP_AUTH.getCurrentUser) ? window.YBP_AUTH.getCurrentUser().name : '') || 'מנהל';

    try {
      const formData = new FormData();
      formData.append('audio', audioBlob, `meeting_${Date.now()}.webm`);
      formData.append('projectId', selectedProjectId);
      formData.append('topic', topic);
      formData.append('date', meetingDate);
      formData.append('pmName', pmName);
      // שם הפרויקט — רק לקביעת תיקייה ב-Drive, לא ל-Whisper/Claude
      formData.append('drivePath', `2026 / ${pmName} / ${projectName} / מסמכים / סיכומי פגישות`);
      formData.append('transcriptModel', 'whisper-1');
      formData.append('summaryModel', 'claude-sonnet-4-20250514');

      const resp = await fetch(MAKE_MEETING_WEBHOOK, { method: 'POST', body: formData });

      if (resp.ok) {
        const data = await resp.json();
        audioChunksRef.current = [];
        const newProtocol = {
          id: 'prot_' + Date.now().toString(36),
          projectId: selectedProjectId,
          title: topic,
          type: 'site',
          meetingDate: meetingDate,
          participants: [],
          agenda: '',
          summary: Array.isArray(data.summary)
            ? '• ' + data.summary.join('\n• ')
            : (data.summary || ''),
          decisions: '',
          nextSteps: data.tasks?.map(t => `• ${t.title} — ${t.assignee} עד ${t.due}`).join('\n') || '',
          extractedTasks: data.tasks || [],
          transcript: data.transcript || '',
          transcriptId: data.transcriptId || '',
          audioDuration: elapsedSec,
          driveUrls: data.driveUrls || {},
          documents: [],
          status: 'draft',
          source: 'recording',
          createdAt: new Date().toISOString(),
          author: pmName,
        };
        if (window.SyncStore?.addProtocol) window.SyncStore.addProtocol(newProtocol);
        if (onOpenProtocol) { onOpenProtocol(newProtocol.id); return; }
        setResult(data);
        setPhase('result');
      } else throw new Error(`HTTP ${resp.status}`);
    } catch (err) {
      // Mock result לפרוטוטייפ
      console.warn('[MeetingRecorder] Make לא זמין — mock', err);
      audioChunksRef.current = [];
      const mockResult = generateMockResult(topic, projectName, elapsedSec);
      const mockProtocol = {
        id: 'prot_' + Date.now().toString(36),
        projectId: selectedProjectId,
        title: topic,
        type: 'site',
        meetingDate: meetingDate,
        participants: [],
        agenda: '',
        summary: Array.isArray(mockResult.summary)
          ? '• ' + mockResult.summary.join('\n• ')
          : (mockResult.summary || ''),
        decisions: '',
        nextSteps: mockResult.tasks?.map(t => `• ${t.title} — ${t.assignee} עד ${t.due}`).join('\n') || '',
        extractedTasks: mockResult.tasks || [],
        transcript: mockResult.transcript || '',
        transcriptId: '',
        audioDuration: elapsedSec,
        driveUrls: mockResult.driveUrls || {},
        documents: [],
        status: 'draft',
        source: 'recording',
        createdAt: new Date().toISOString(),
        author: pmName,
      };
      if (window.SyncStore?.addProtocol) window.SyncStore.addProtocol(mockProtocol);
      if (onOpenProtocol) { onOpenProtocol(mockProtocol.id); return; }
      setResult(mockResult);
      setPhase('result');
    }
  }, [selectedProjectId, topic, meetingDate, projects, elapsedSec]);

  // ── Mock result ───────────────────────────────────────────────────────
  const generateMockResult = (topic, projectName, duration) => ({
    summary: [
      `נדון נושא: ${topic}`,
      'הוחלט לתאם בדיקת חשמל לפני סיום שלב א׳',
      'הקבלן יגיש לוח זמנים מעודכן עד סוף השבוע',
      'נקבע סיור לקוח לתאריך 02.05.2026',
    ],
    tasks: [
      { title: 'הגשת לוח זמנים מעודכן', assignee: 'אבי כהן', due: '2026-05-08', status: 'open' },
      { title: 'תיאום בדיקת חשמל', assignee: 'רונית לוי', due: '2026-05-05', status: 'open' },
      { title: 'הכנת נושאים לסיור לקוח', assignee: ((window.YBP_AUTH && window.YBP_AUTH.getCurrentUser) ? window.YBP_AUTH.getCurrentUser().name : '') || 'מנהל', due: '2026-05-01', status: 'open' },
    ],
    transcript: `[פגישה: ${topic}]\n[פרויקט: [מוסתר מ-Whisper]]\n\nמנהל: בוקר טוב לכולם. נתחיל בסקירת הסטטוס...\nקבלן: ביצענו השבוע את עבודות הגבס בקומה ב׳...\nמנהל: מצוין. מה הסטטוס עם לוח החשמל?\nקבלן: ממתינים לחומר מהספק, צפי הגעה ב-5 למאי...\n[תמלול מלא — ${Math.round(duration/60)} דקות]`,
    driveUrls: {
      summary: `https://drive.google.com/file/d/MOCK_SUMMARY_${Date.now()}`,
      transcript: `https://drive.google.com/file/d/MOCK_TRANSCRIPT_${Date.now()}`,
      folder: `https://drive.google.com/drive/folders/MOCK_FOLDER`,
    },
    savedToDrive: true,
    drivePath: `2026 / ${((window.YBP_AUTH && window.YBP_AUTH.getCurrentUser) ? window.YBP_AUTH.getCurrentUser().name : '') || 'מנהל'} / ${projectName} / מסמכים / סיכומי פגישות`,
  });

  // ── PDF export ────────────────────────────────────────────────────────
  const exportPDF = (type) => {
    if (!window.YBPPdf) { alert('pdf-base.js לא נטען'); return; }
    const project = (projects.length ? projects : YBP_DATA.projects).find(p => p.id === selectedProjectId);
    const pmName  = YBP_DATA.user?.name || 'מנהל';
    const fmtDate = (iso) => iso.split('-').reverse().join('.');
    const logoSrc = 'assets/ybp-logo-new.png';

    // ── מטא-בר תחת הלוגו ────────────────────────────────────────────
    const headerMetaHtml = `
      <div class="mb">
        <div>
          <div style="font-size:18px;font-weight:800;color:#1a2c4a;margin-bottom:4px">
            ${type === 'summary' ? 'סיכום פגישה' : 'תמלול פגישה'} — ${topic}
          </div>
          <div style="font-size:12px;color:#6b7280">
            ${project?.name || ''} &nbsp;·&nbsp; ${fmtDate(meetingDate)} &nbsp;·&nbsp; ${pmName}
          </div>
        </div>
        <div style="text-align:left">
          <span class="badge">${type === 'summary' ? 'סיכום' : 'תמלול'}</span>
        </div>
      </div>`;

    // ── תוכן לפי סוג ────────────────────────────────────────────────
    let bodyHtml = '';

    if (type === 'summary') {
      // נקודות עיקריות
      bodyHtml += `
        <div class="sec">
          <div class="sec-lbl">נקודות עיקריות</div>
          <table class="d">
            <thead><tr>
              <th style="width:40px">#</th>
              <th>נושא</th>
            </tr></thead>
            <tbody>
              ${result.summary.map((s, i) => `
                <tr><td style="text-align:center;font-weight:700">${i+1}</td><td>${s}</td></tr>
              `).join('')}
            </tbody>
          </table>
        </div>`;

      // משימות שחולצו
      if (result.tasks?.length) {
        bodyHtml += `
          <div class="sec" style="margin-top:20px">
            <div class="sec-lbl">משימות שחולצו (${result.tasks.length})</div>
            <table class="d">
              <thead><tr>
                <th>משימה</th>
                <th style="width:130px">אחראי</th>
                <th style="width:100px">תאריך יעד</th>
                <th style="width:80px">סטטוס</th>
              </tr></thead>
              <tbody>
                ${result.tasks.map(t => `
                  <tr>
                    <td style="font-weight:600">${t.title}</td>
                    <td>${t.assignee || '—'}</td>
                    <td style="direction:ltr;text-align:right">${t.due || '—'}</td>
                    <td><span style="background:#dbeafe;color:#1e40af;padding:2px 8px;border-radius:3px;font-size:10px;font-weight:700">פתוח</span></td>
                  </tr>
                `).join('')}
              </tbody>
            </table>
          </div>`;
      }

      // Drive path
      if (result.drivePath) {
        bodyHtml += `
          <div class="sec" style="margin-top:20px;background:#f8f9fa;border:1px solid #e5e7eb;border-radius:6px;padding:12px 16px">
            <div class="sec-lbl">נשמר ב-Google Drive</div>
            <div style="font-size:11px;color:#374151;direction:ltr;text-align:right">📁 ${result.drivePath}</div>
          </div>`;
      }

    } else {
      // תמלול מלא
      bodyHtml += `
        <div class="sec">
          <div class="sec-lbl">תמלול מלא</div>
          <div style="background:#f8f9fa;border:1px solid #e5e7eb;border-radius:6px;padding:16px 20px">
            <pre style="white-space:pre-wrap;font-family:Assistant,Arial,sans-serif;font-size:12px;line-height:1.8;color:#1f2937;margin:0;direction:rtl">${result.transcript || ''}</pre>
          </div>
        </div>`;
    }

    // ── חתימה ───────────────────────────────────────────────────────
    const sigHtml = `
      <div class="sig">
        <div>
          <div style="font-size:10px;color:#6b7280;margin-bottom:4px">הופק על ידי</div>
          <div style="font-size:13px;font-weight:700;color:#1a2c4a">${pmName}</div>
          <div style="font-size:11px;color:#6b7280">${fmtDate(meetingDate)}</div>
        </div>
        <div style="text-align:left">
          <div style="font-size:10px;color:#6b7280;margin-bottom:4px">פרויקט</div>
          <div style="font-size:13px;font-weight:700;color:#1a2c4a">${project?.name || ''}</div>
          <div style="font-size:11px;color:#6b7280">${project?.address || ''}</div>
        </div>
      </div>`;

    window.YBPPdf.openPrintWindow({
      orientation: 'portrait',
      logoSrc,
      fileName: `${type === 'summary' ? 'סיכום' : 'תמלול'} פגישה — ${topic} — ${fmtDate(meetingDate)}`,
      headerMetaHtml,
      bodyHtml,
      sigHtml,
    });
  };

  const selectedProject = (projects.length ? projects : YBP_DATA.projects).find(p => p.id === selectedProjectId) || {};

  // ── סגנונות ──────────────────────────────────────────────────────────
  const s = {
    page: { minHeight: '100%', background: '#f6f7f9', fontFamily: 'Assistant,sans-serif', direction: 'rtl', paddingBottom: 40 },
    header: { background: '#1a2c4a', color: '#fff', padding: '14px 20px', display: 'flex', alignItems: 'center', gap: 12 },
    backBtn: { background: 'none', border: 'none', color: '#fff', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 4, fontSize: 14, fontFamily: 'inherit', opacity: 0.8 },
    card: { background: '#fff', borderRadius: 12, border: '1px solid #e5e7eb', padding: 20, margin: '16px', marginTop: 0 },
    inp: { width: '100%', padding: '10px 12px', border: '1px solid #e5e7eb', borderRadius: 8, fontSize: 14, fontFamily: 'inherit', direction: 'rtl', boxSizing: 'border-box', outline: 'none' },
    label: { fontSize: 12, fontWeight: 700, color: '#374151', display: 'block', marginBottom: 6, letterSpacing: 0.3 },
    btn: (color, bg) => ({ padding: '11px 20px', background: bg, color, border: 'none', borderRadius: 8, fontSize: 14, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit', display: 'flex', alignItems: 'center', gap: 8 }),
    tab: (active) => ({ padding: '8px 16px', border: 'none', borderRadius: 6, fontSize: 13, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit', background: active ? '#1a2c4a' : '#f3f4f6', color: active ? '#fff' : '#374151' }),
  };

  return (
    <div style={s.page}>
      {/* Header */}
      <div style={s.header}>
        <button style={s.backBtn} onClick={onBack}>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="15 18 9 12 15 6"/></svg>
          חזרה
        </button>
        <div style={{ width: 1, height: 20, background: 'rgba(255,255,255,0.3)' }}/>
        <div>
          <div style={{ fontSize: 16, fontWeight: 700 }}>🎙️ הקלטת פגישה</div>
          {phase === 'recording' && <div style={{ fontSize: 11, opacity: 0.7, marginTop: 2 }}>מקליט — {fmtDuration(elapsedSec)}</div>}
        </div>
      </div>

      {/* ── SETUP ───────────────────────────────────────────────────── */}
      {phase === 'setup' && (
        <div style={{ padding: '16px 16px 0' }}>
          <div style={s.card}>
            <div style={{ fontSize: 15, fontWeight: 700, color: '#1a2c4a', marginBottom: 16, display: 'flex', alignItems: 'center', gap: 8 }}>
              <span style={{ background: '#1a2c4a', color: '#fff', width: 26, height: 26, borderRadius: 5, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 13, fontWeight: 800 }}>1</span>
              הגדרת הפגישה
            </div>

            <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
              <div>
                <label style={s.label}>פרויקט</label>
                <select value={selectedProjectId} onChange={e => setSelectedProjectId(e.target.value)} style={s.inp}>
                  {(projects.length ? projects : YBP_DATA.projects).map(p => (
                    <option key={p.id} value={p.id}>{p.name}</option>
                  ))}
                </select>
              </div>
              <div>
                <label style={s.label}>נושא הפגישה *</label>
                <input
                  value={topic}
                  onChange={e => setTopic(e.target.value)}
                  placeholder="למשל: תיאום שבועי, סיור לקוח, פגישת קבלן..."
                  style={s.inp}
                />
              </div>
              <div>
                <label style={s.label}>תאריך</label>
                <input type="date" value={meetingDate} onChange={e => setMeetingDate(e.target.value)} style={s.inp}/>
              </div>
            </div>

            {error && <div style={{ marginTop: 12, color: '#dc2626', fontSize: 13 }}>⚠️ {error}</div>}
          </div>

          {/* בנר הסבר */}
          <div style={{ ...s.card, background: 'linear-gradient(135deg, #eff6ff, #f8fafc)', border: '1px solid #bfdbfe', marginTop: 0 }}>
            <div style={{ fontSize: 13, fontWeight: 700, color: '#1e40af', marginBottom: 8 }}>איך זה עובד?</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {[
                ['🎙️', 'מקליט קובץ אודיו מלא של הפגישה (ללא תמלול חי)'],
                ['📤', 'שולח ל-Make → Whisper (תמלול מלא ומדויק)'],
                ['🤖', 'Claude Sonnet מסכם נקודות + משימות'],
                ['💾', 'שומר PDF + DOCX ב-Drive תחת סיכומי פגישות'],
                ['🗑️', 'קובץ האודיו נמחק מיד אחרי תמלול'],
              ].map(([icon, text], i) => (
                <div key={i} style={{ display: 'flex', gap: 10, alignItems: 'flex-start', fontSize: 12.5, color: '#374151' }}>
                  <span style={{ fontSize: 16, flexShrink: 0 }}>{icon}</span>
                  <span style={{ lineHeight: 1.5 }}>{text}</span>
                </div>
              ))}
            </div>
          </div>

          <div style={{ padding: '0 0 16px' }}>
            <button onClick={startRecording} disabled={!topic.trim()} style={{
              ...s.btn('#fff', topic.trim() ? '#dc2626' : '#9ca3af'),
              width: '100%', justifyContent: 'center', padding: '15px', fontSize: 16,
              borderRadius: 12, cursor: topic.trim() ? 'pointer' : 'not-allowed',
            }}>
              <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" 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"/></svg>
              התחל הקלטה
            </button>
          </div>
        </div>
      )}

      {/* ── RECORDING ───────────────────────────────────────────────── */}
      {phase === 'recording' && (
        <div style={{ padding: '16px 16px 0' }}>
          <div style={{ ...s.card, border: '2px solid #fecaca', background: 'linear-gradient(135deg, #fff5f5, #fff)', textAlign: 'center' }}>
            {/* אנימציית גלים */}
            <div style={{ display: 'flex', gap: 4, justifyContent: 'center', alignItems: 'flex-end', height: 56, marginBottom: 16 }}>
              {Array.from({length: 18}).map((_, i) => (
                <div key={i} style={{
                  width: 4, background: '#dc2626', borderRadius: 2,
                  height: 8 + Math.sin(i * 0.7) * 22,
                  animation: `ybp-wave ${0.5 + (i % 4) * 0.1}s ease-in-out ${i * 0.06}s infinite`,
                  opacity: 0.6 + (i % 3) * 0.15,
                }}/>
              ))}
            </div>

            <div style={{ fontSize: 36, fontWeight: 800, color: '#dc2626', fontVariantNumeric: 'tabular-nums', letterSpacing: 1, marginBottom: 6 }}>
              {fmtDuration(elapsedSec)}
            </div>
            <div style={{ fontSize: 13, color: '#6b7280', marginBottom: 4 }}>
              {selectedProject.name} — {topic}
            </div>
            <div style={{ fontSize: 11.5, color: '#9ca3af', marginBottom: 20 }}>
              גודל אודיו: {fmtFileSizeMB(audioSize)}
            </div>

            {/* דוט אדום מהבהב */}
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, justifyContent: 'center', marginBottom: 20 }}>
              <div style={{ width: 10, height: 10, background: '#dc2626', borderRadius: 5, animation: 'ybp-pulse 1s ease-in-out infinite' }}/>
              <span style={{ fontSize: 13, fontWeight: 700, color: '#dc2626' }}>מקליט...</span>
            </div>

            <button onClick={stopRecording} style={{ ...s.btn('#fff', '#1a2c4a'), width: '100%', justifyContent: 'center', padding: 14, borderRadius: 10, fontSize: 15 }}>
              <svg width="20" height="20" viewBox="0 0 24 24" fill="#fff" stroke="none"><rect x="4" y="4" width="16" height="16" rx="2"/></svg>
              סיים הקלטה
            </button>
          </div>

          <div style={{ ...s.card, marginTop: 0, background: '#fffbeb', border: '1px solid #fde68a' }}>
            <div style={{ fontSize: 12, color: '#92400e', lineHeight: 1.6 }}>
              💡 <strong>הפגישה מוקלטת.</strong> ניתן להשתמש בטלפון בזמן ההקלטה. האפליקציה תמשיך לרקום גם אם המסך כבה.
            </div>
          </div>
        </div>
      )}

      {/* ── PROCESSING ──────────────────────────────────────────────── */}
      {phase === 'processing' && (
        <div style={{ padding: '60px 16px', textAlign: 'center' }}>
          <div style={{ width: 64, height: 64, border: '5px solid #e5e7eb', borderTopColor: '#1a2c4a', borderRadius: 32, animation: 'ybp-spin 0.8s linear infinite', margin: '0 auto 24px' }}/>
          <div style={{ fontSize: 18, fontWeight: 700, color: '#1a2c4a', marginBottom: 8 }}>מעבד את ההקלטה...</div>
          <div style={{ fontSize: 13, color: '#6b7280', lineHeight: 1.7 }}>
            שולח ל-Make → Whisper מתמלל → Claude מסכם<br/>
            <span style={{ fontSize: 11 }}>עשוי לקחת 1-3 דקות לפגישה ארוכה</span>
          </div>
          <div style={{ marginTop: 24, display: 'flex', flexDirection: 'column', gap: 10, maxWidth: 280, margin: '24px auto 0' }}>
            {[
              ['📤', 'שולח קובץ אודיו ל-Make...'],
              ['🎙️', 'Whisper מתמלל בעברית...'],
              ['🤖', 'Claude מסכם ומחלץ משימות...'],
              ['💾', 'שומר ל-Drive...'],
            ].map(([icon, text], i) => (
              <div key={i} style={{ display: 'flex', gap: 10, alignItems: 'center', fontSize: 13, color: '#374151', background: '#f9fafb', padding: '8px 14px', borderRadius: 8 }}>
                <span>{icon}</span><span>{text}</span>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* ── RESULT ──────────────────────────────────────────────────── */}
      {phase === 'result' && result && (
        <div style={{ padding: '16px 16px 0' }}>
          {/* כרטיס הצלחה */}
          <div style={{ ...s.card, background: 'linear-gradient(135deg, #f0fdf4, #fff)', border: '1px solid #86efac' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 12 }}>
              <div style={{ width: 44, height: 44, background: '#d1fae5', borderRadius: 22, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 22 }}>✅</div>
              <div>
                <div style={{ fontSize: 15, fontWeight: 700, color: '#065f46' }}>הפגישה עובדה בהצלחה</div>
                <div style={{ fontSize: 12, color: '#059669', marginTop: 2 }}>נשמר ב-Drive + האפליקציה</div>
              </div>
            </div>

            {/* Drive links */}
            {result.driveUrls && (
              <div style={{ background: '#fff', border: '1px solid #d1fae5', borderRadius: 8, padding: '10px 14px', display: 'flex', flexDirection: 'column', gap: 8 }}>
                <div style={{ fontSize: 11, fontWeight: 700, color: '#6b7280', textTransform: 'uppercase', letterSpacing: 0.4 }}>נשמר ב-Drive:</div>
                <div style={{ fontSize: 11.5, color: '#374151', direction: 'ltr', textAlign: 'right' }}>
                  📁 {result.drivePath}
                </div>
                <div style={{ display: 'flex', gap: 8 }}>
                  {result.driveUrls.summary && (
                    <a href={result.driveUrls.summary} target="_blank" rel="noreferrer" style={{ fontSize: 12, color: '#1a2c4a', background: '#eff6ff', padding: '5px 10px', borderRadius: 5, textDecoration: 'none', fontWeight: 600 }}>
                      📄 סיכום.pdf
                    </a>
                  )}
                  {result.driveUrls.transcript && (
                    <a href={result.driveUrls.transcript} target="_blank" rel="noreferrer" style={{ fontSize: 12, color: '#1a2c4a', background: '#f3f4f6', padding: '5px 10px', borderRadius: 5, textDecoration: 'none', fontWeight: 600 }}>
                      📝 תמלול.docx
                    </a>
                  )}
                </div>
              </div>
            )}
          </div>

          {/* Tabs */}
          <div style={{ display: 'flex', gap: 8, padding: '0 16px', marginBottom: 12 }}>
            {[['summary','סיכום'],['tasks','משימות'],['transcript','תמלול']].map(([k,label]) => (
              <button key={k} onClick={() => setActiveTab(k)} style={s.tab(activeTab === k)}>{label}</button>
            ))}
          </div>

          {/* Summary tab */}
          {activeTab === 'summary' && (
            <div style={s.card}>
              <div style={{ fontSize: 14, fontWeight: 700, color: '#1a2c4a', marginBottom: 12 }}>נקודות עיקריות</div>
              {result.summary.map((point, i) => (
                <div key={i} style={{ display: 'flex', gap: 10, alignItems: 'flex-start', padding: '8px 0', borderTop: i > 0 ? '1px solid #f3f4f6' : 'none' }}>
                  <span style={{ width: 22, height: 22, background: '#1a2c4a', color: '#fff', borderRadius: 11, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 11, fontWeight: 700, flexShrink: 0 }}>{i+1}</span>
                  <span style={{ fontSize: 13.5, lineHeight: 1.6, color: '#1f2937' }}>{point}</span>
                </div>
              ))}
            </div>
          )}

          {/* Tasks tab */}
          {activeTab === 'tasks' && (
            <div style={s.card}>
              <div style={{ fontSize: 14, fontWeight: 700, color: '#1a2c4a', marginBottom: 12 }}>
                {result.tasks.length} משימות שחולצו
              </div>
              {result.tasks.map((task, i) => (
                <div key={i} style={{ background: '#f9fafb', borderRadius: 8, padding: '12px 14px', marginBottom: 8, border: '1px solid #e5e7eb' }}>
                  <div style={{ fontSize: 13.5, fontWeight: 600, color: '#1f2937', marginBottom: 6 }}>{task.title}</div>
                  <div style={{ display: 'flex', gap: 10, fontSize: 12, color: '#6b7280' }}>
                    <span>👤 {task.assignee}</span>
                    <span>📅 עד {task.due}</span>
                  </div>
                </div>
              ))}
              <button
                onClick={() => {
                  result.tasks.forEach(t => SyncStore.addTask({
                    projectId: selectedProjectId,
                    title: t.title, assignee: t.assignee, due: t.due,
                    source: 'meeting_recording', severity: 'medium',
                  }));
                  alert('✅ ' + result.tasks.length + ' משימות נוספו לרשימת המשימות של הפרויקט');
                }}
                style={{ ...s.btn('#fff', '#1a2c4a'), width: '100%', justifyContent: 'center', marginTop: 4 }}
              >
                ➕ הוסף כל המשימות לפרויקט
              </button>
            </div>
          )}

          {/* Transcript tab */}
          {activeTab === 'transcript' && (
            <div style={s.card}>
              <div style={{ fontSize: 14, fontWeight: 700, color: '#1a2c4a', marginBottom: 12 }}>תמלול מלא</div>
              <pre style={{
                whiteSpace: 'pre-wrap', fontFamily: 'Assistant, sans-serif', fontSize: 12.5,
                lineHeight: 1.7, color: '#374151', background: '#f9fafb', padding: 14,
                borderRadius: 8, border: '1px solid #e5e7eb', maxHeight: 320, overflowY: 'auto',
                direction: 'rtl',
              }}>{result.transcript}</pre>
            </div>
          )}

          {/* Export buttons */}
          <div style={{ ...s.card, marginTop: 0 }}>
            <div style={{ fontSize: 13, fontWeight: 700, color: '#374151', marginBottom: 10 }}>ייצוא PDF</div>
            <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
              <button onClick={() => exportPDF('summary')} style={{ ...s.btn('#1a2c4a', '#f3f4f6'), fontSize: 12, padding: '8px 14px' }}>📄 סיכום</button>
              <button onClick={() => exportPDF('transcript')} style={{ ...s.btn('#1a2c4a', '#f3f4f6'), fontSize: 12, padding: '8px 14px' }}>📝 תמלול</button>
              <button onClick={() => { exportPDF('summary'); setTimeout(() => exportPDF('transcript'), 800); }} style={{ ...s.btn('#fff', '#1a2c4a'), fontSize: 12, padding: '8px 14px' }}>📑 שניהם</button>
            </div>
          </div>

          {/* הקלטה חדשה */}
          <div style={{ padding: '0 0 16px' }}>
            <button onClick={() => { setPhase('setup'); setResult(null); setTopic(''); setElapsedSec(0); setAudioSize(0); }} style={{ ...s.btn('#6b7280', '#fff'), border: '1px solid #e5e7eb', width: '100%', justifyContent: 'center' }}>
              🔄 הקלטה חדשה
            </button>
          </div>
        </div>
      )}

      {/* ── ERROR ───────────────────────────────────────────────────── */}
      {phase === 'error' && (
        <div style={{ padding: '60px 16px', textAlign: 'center' }}>
          <div style={{ fontSize: 48, marginBottom: 16 }}>⚠️</div>
          <div style={{ fontSize: 16, fontWeight: 700, color: '#dc2626', marginBottom: 8 }}>שגיאה בעיבוד</div>
          <div style={{ fontSize: 13, color: '#6b7280', marginBottom: 24 }}>{error}</div>
          <button onClick={() => setPhase('setup')} style={{ ...s.btn('#fff', '#1a2c4a'), margin: '0 auto' }}>נסה שוב</button>
        </div>
      )}
    </div>
  );
};

Object.assign(window, { MeetingRecorderScreen });
})();
