// Pending Summaries Modal — מודל סיכומים ממתינים מקלוד צ'ט
(function () {
const { useState, useEffect } = React;

// Spinner keyframe (injected once)
if (!document.getElementById('ybp-spin-style')) {
  const s = document.createElement('style');
  s.id = 'ybp-spin-style';
  s.textContent = '@keyframes spin { to { transform: rotate(360deg); } }';
  document.head.appendChild(s);
}

// ── Webhook Defaults ──────────────────────────────────────────────────────────
const WEBHOOK_DEFAULTS = {
  PLACEHOLDER_SUMMARIES_LIST:    'https://hook.eu2.make.com/f7q1rar5ttdcgjrc7d4l5r723h69anx5',
  PLACEHOLDER_SUMMARIES_APPROVE: 'https://hook.eu2.make.com/ufypg398p6d6rr8ffb4g673dzzgcls87',
  PLACEHOLDER_PROCESS_FORM_VOICE:'https://hook.eu2.make.com/4epcge33jekixuz8eod2vgt4lcdd4rhj',
};

// ── AI Structure Prompts ──────────────────────────────────────────────────────
const STRUCTURE_PROMPTS = {
  daily: `מהטקסט שלהלן, חלץ JSON תקני בלבד (ללא הסברים, ללא markdown, ללא \`\`\`):
{
  "notes": "סיכום עבודות שבוצעו היום ב-2-4 משפטים. אל תכלול בתוכו ליקויים/ריג'קטים — אלה ירדו ל-rejects.",
  "weather": "מזג אוויר אם הוזכר, אחרת ריק",
  "siteVisitors": "רשימת אנשים שנכחו באתר מופרדת בפסיקים, אחרת ריק",
  "issues": "בעיות תפעוליות באתר (עיכובים, חוסרים, החלטות פתוחות). ריק אם אין.",
  "rejects": [
    {"title": "כותרת קצרה (5-8 מילים)", "description": "פירוט הליקוי", "severity": "low|medium|high|critical", "assignee": "אחראי אם הוזכר"}
  ]
}
חוקים חובה:
1. כל פריט שמוזכר כליקוי / ריג'קט / "צריך לתקן" / "לא בסדר" / "להשלים" / סעיף ברשימה (מקף, כוכבית, מספר) — חייב להיכנס למערך rejects כפריט נפרד.
2. אם הטקסט כולו רשימת ליקויים, החזר rejects מלא ו-notes ריק.
3. אסור לדחוס ריג'קטים לתוך notes או issues.
4. אם אין ריג'קטים אמיתיים, החזר "rejects": [].`,
  weekly: `מהטקסט שלהלן, חלץ JSON תקני בלבד (ללא הסברים, ללא markdown):
{
  "summary": "סיכום השבוע ב-5-8 משפטים",
  "keyPoints": ["נקודה 1", "נקודה 2"],
  "nextWeekFocus": "תוכניות לשבוע הבא ב-2-3 משפטים"
}`,
  rejects: `מהטקסט שלהלן, חלץ רשימת ריג'קטים (ליקויים שצריך לתקן). החזר JSON תקני בלבד (ללא הסברים, ללא markdown, ללא \`\`\`):
{
  "rejects": [
    {"title": "כותרת קצרה (5-8 מילים)", "description": "פירוט הליקוי", "severity": "low|medium|high|critical", "assignee": "אחראי אם הוזכר"}
  ],
  "notes": "הערות כלליות שאינן ליקויים. ריק אם אין."
}
חוקים חובה:
1. כל סעיף ברשימה (מקף "-", כוכבית "*", "•", מספר "1.", או שורה נפרדת שמתארת ליקוי) — חייב להיות ריג'קט נפרד.
2. אסור לדחוס ליקויים לתוך notes. אם זו רשימת ליקויים — חלץ כל אחד בנפרד.
3. severity ברירת מחדל: "medium". "קריטי"/"דחוף" → "critical"; "חשוב"/"גבוה" → "high"; "שולי"/"קוסמטי" → "low".
4. החזר תמיד מערך rejects עם לפחות פריט אחד אם הטקסט מתאר ליקוי כלשהו.`,
  infra: `מהטקסט שלהלן, חלץ JSON תקני בלבד (ללא הסברים, ללא markdown):
{
  "notes": "תיאור התשתית והעבודה ב-3-5 משפטים",
  "items": [
    {"system": "חשמל|מים|כיבוי אש|מיזוג|תקשורת|אחר", "status": "תיאור מצב", "issues": "ליקויים אם יש"}
  ]
}`
};

// ── Fallback bullet parser (when AI fails to extract rejects) ─────────────────
function parseBulletPoints(text) {
  if (!text || typeof text !== 'string') return [];
  const lines = text.split(/\r?\n/);
  const items = [];
  for (let raw of lines) {
    const line = raw.trim();
    if (!line) continue;
    // Match: "- text", "* text", "• text", "● text", "▪ text", "1. text", "1) text"
    const m = line.match(/^[-*•●▪◦‣⁃]\s+(.+)$/) || line.match(/^\d+[.)]\s+(.+)$/);
    if (m && m[1].length >= 3) {
      const txt = m[1].trim();
      items.push({
        title: txt.length > 60 ? txt.slice(0, 60).trim() + '…' : txt,
        description: txt.length > 60 ? txt : '',
        severity: 'medium',
        assignee: '',
      });
    }
  }
  return items;
}

// ── Helpers ───────────────────────────────────────────────────────────────────
function getWebhookUrl(key) {
  try {
    const s = JSON.parse(localStorage.getItem('ybp_settings') || '{}');
    return (s.webhooks || {})[key] || WEBHOOK_DEFAULTS[key] || '';
  } catch { return WEBHOOK_DEFAULTS[key] || ''; }
}

function getSecurityKey() {
  try {
    const s = JSON.parse(localStorage.getItem('ybp_settings') || '{}');
    return (s.webhooks || {})._securityKey || '1h4M4SEXbhoYF1YVW1mS6YJZs84yxSVHaBjPDDxMpbak';
  } catch { return '1h4M4SEXbhoYF1YVW1mS6YJZs84yxSVHaBjPDDxMpbak'; }
}

function safeJSONParse(str, fallback) {
  try { return JSON.parse(str); } catch { return fallback; }
}

const fmtDateHe = (iso) => {
  if (!iso) return '';
  const [y, m, d] = (iso || '').slice(0, 10).split('-');
  return `${d || ''}/${m || ''}/${y || ''}`;
};

const TYPE_LABELS = {
  daily:   'דוח יומי',
  weekly:  'דוח שבועי',
  rejects: "דוח ריג'קטים",
  infra:   'תיעוד תשתיות',
};

// ── Data Layer (Supabase direct) ──────────────────────────────────────────────
async function fetchPendingSummaries() {
  if (!window.YBP_SUPABASE) return [];
  try {
    const sb = await window.YBP_SUPABASE.getClient();
    const { data: { session } } = await sb.auth.getSession();
    if (!session?.user?.id) return [];
    const { data, error } = await sb
      .from('pending_summaries')
      .select('*')
      .eq('user_id', session.user.id)
      .order('created_at', { ascending: false });
    if (error) { console.error('[PendingSummaries] LIST failed:', error.message); return []; }

    const safeJSON = (val, fallback) => {
      if (!val) return fallback;
      if (typeof val === 'object') return val;
      try { return JSON.parse(val); } catch { return fallback; }
    };

    return (data || []).map(r => ({
      id:            r.id,
      summary:       r.summary       || '',
      suggestedType: r.suggested_type || r.suggestedType || '',
      projectId:     r.project_id    || r.projectId     || '',
      rejects:       safeJSON(r.rejects_json || r.rejectsJson, []),
      meta:          safeJSON(r.meta_json    || r.metaJson,    {}),
      createdAt:     r.created_at    || r.createdAt     || '',
    }));
  } catch (e) {
    console.error('[PendingSummaries] LIST failed:', e);
    return [];
  }
}

async function structureSummary(summaryText, type) {
  const url = getWebhookUrl('PLACEHOLDER_PROCESS_FORM_VOICE');
  if (!url || !STRUCTURE_PROMPTS[type]) return null;
  try {
    const timeout = new Promise((_, rej) => setTimeout(() => rej(new Error('timeout')), 15000));
    const req = fetch(url, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ prompt: STRUCTURE_PROMPTS[type], text: summaryText, _sk: getSecurityKey() }),
    }).then(r => r.ok ? r.text() : Promise.reject(new Error(`HTTP ${r.status}`)));
    const txt = await Promise.race([req, timeout]);
    const cleaned = txt.replace(/```json\n?|```\n?/g, '').trim();
    const parsed = safeJSONParse(cleaned, null);

    // Fallback: AI didn't extract rejects but text has bullet points → parse client-side
    if (parsed && (type === 'daily' || type === 'rejects')) {
      const aiRejects = Array.isArray(parsed.rejects) ? parsed.rejects : [];
      if (aiRejects.length === 0) {
        const fallback = parseBulletPoints(summaryText);
        if (fallback.length > 0) {
          parsed.rejects = fallback;
          console.warn('[PendingSummaries] AI returned 0 rejects — used bullet fallback (' + fallback.length + ' items)');
        }
      }
    }
    return parsed;
  } catch (e) {
    console.error('[PendingSummaries] structureSummary failed:', e);
    return null;
  }
}

async function submitApprove(id, action) {
  if (!window.YBP_SUPABASE) return;
  try {
    const sb = await window.YBP_SUPABASE.getClient();
    const { data: { session } } = await sb.auth.getSession();
    if (!session?.user?.id) return;
    await sb
      .from('pending_summaries')
      .delete()
      .eq('id', id)
      .eq('user_id', session.user.id);
    // notify bell + banner to refresh count (Realtime will also fire)
    window.dispatchEvent(new CustomEvent('ybp-pending-summary-approved', { detail: { id, action } }));
  } catch (e) {
    console.warn('[PendingSummaries] approve failed:', e.message);
  }
}

// ── Global API (called by form components after submit) ───────────────────────
window.PendingSummariesAPI = {
  approveUsed:     (id) => submitApprove(id, 'used'),
  approveRejected: (id) => submitApprove(id, 'rejected'),
  fetchPending:    ()   => fetchPendingSummaries(),
};

// ── Summary Card (list view) ──────────────────────────────────────────────────
const SummaryCard = ({ item, onClick, onDismiss }) => {
  const [expanded, setExpanded] = useState(false);
  const projects = window.YBP_DATA?.projects || [];
  const projName = item.projectId
    ? (projects.find(p => p.id === item.projectId)?.name || item.projectId)
    : null;
  const lines = (item.summary || '').split('\n');
  const preview = lines.slice(0, 4).join('\n');
  const hasMore = lines.length > 4;

  return (
    <div
      onClick={onClick}
      style={{
        background: '#fff', borderRadius: 12, border: '1px solid #e5e7eb',
        boxShadow: '0 2px 8px rgba(0,0,0,0.06)', padding: '14px 16px',
        cursor: 'pointer', direction: 'rtl',
      }}
    >
      {/* Tags row + dismiss button */}
      <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 8, marginBottom: 8 }}>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, flex: 1 }}>
          {item.createdAt && (
            <span style={{ fontSize: 12, background: '#f3f4f6', color: '#6b7280', borderRadius: 6, padding: '2px 8px' }}>
              {fmtDateHe(item.createdAt)}
            </span>
          )}
          {item.suggestedType && TYPE_LABELS[item.suggestedType] && (
            <span style={{ fontSize: 12, background: '#eff6ff', color: '#1d4ed8', borderRadius: 6, padding: '2px 8px', fontWeight: 600 }}>
              {TYPE_LABELS[item.suggestedType]}
            </span>
          )}
          {projName && (
            <span style={{ fontSize: 12, background: '#f0fdf4', color: '#16a34a', borderRadius: 6, padding: '2px 8px' }}>
              {projName}
            </span>
          )}
          {item.rejects.length > 0 && (
            <span style={{ fontSize: 12, background: '#fef3c7', color: '#b45309', borderRadius: 6, padding: '2px 8px' }}>
              {`+${item.rejects.length} ריג'קטים זוהו`}
            </span>
          )}
        </div>
        <button
          onClick={e => {
            e.stopPropagation();
            if (!window.confirm('למחוק את הסיכום מהרשימה? לא ניתן לשחזר.')) return;
            onDismiss && onDismiss(item.id);
          }}
          title="מחק סיכום"
          style={{
            background: 'transparent', border: 'none', cursor: 'pointer',
            color: '#9ca3af', fontSize: 16, padding: '2px 6px', borderRadius: 6,
            lineHeight: 1, flexShrink: 0, fontFamily: 'inherit',
          }}
          onMouseEnter={e => { e.currentTarget.style.color = '#dc2626'; e.currentTarget.style.background = '#fef2f2'; }}
          onMouseLeave={e => { e.currentTarget.style.color = '#9ca3af'; e.currentTarget.style.background = 'transparent'; }}
        >
          🗑
        </button>
      </div>

      {/* Summary preview */}
      <div style={{ fontSize: 13.5, color: '#374151', lineHeight: 1.6, whiteSpace: 'pre-wrap', wordBreak: 'break-word' }}>
        {expanded ? item.summary : preview}
      </div>
      {hasMore && (
        <button
          onClick={e => { e.stopPropagation(); setExpanded(x => !x); }}
          style={{ background: 'none', border: 'none', color: '#1d4ed8', fontSize: 12, cursor: 'pointer', padding: '4px 0', fontFamily: 'inherit' }}
        >
          {expanded ? 'פחות ▲' : 'קרא עוד ▼'}
        </button>
      )}

      {/* CTA arrow */}
      <div style={{ display: 'flex', justifyContent: 'flex-start', marginTop: 10 }}>
        <span style={{ fontSize: 12, color: '#1d4ed8', fontWeight: 700 }}>לחץ למילוי דוח ←</span>
      </div>
    </div>
  );
};

// ── Main Component ────────────────────────────────────────────────────────────
const PendingSummariesModal = ({ onClose, onOpenForm }) => {
  const [summaries, setSummaries] = useState([]);
  const [loading, setLoading]     = useState(true);
  const [error, setError]         = useState(null);
  const [selected, setSelected]   = useState(null);
  const [chosenType, setChosenType]           = useState('');
  const [chosenProjectId, setChosenProjectId] = useState('');
  const [aiLoading, setAiLoading] = useState(false);
  const [aiToast, setAiToast]     = useState('');

  const projects = window.YBP_DATA?.projects || [];

  // Fetch on mount
  useEffect(() => {
    let cancelled = false;
    fetchPendingSummaries().then(list => {
      if (cancelled) return;
      setLoading(false);
      if (list.length === 0) {
        onClose(); // nothing to show — close silently
        return;
      }
      setSummaries(list);
    }).catch(() => {
      if (!cancelled) { setLoading(false); setError('שגיאה בטעינת הסיכומים'); }
    });
    return () => { cancelled = true; };
  }, []);

  // When a summary is selected, pre-populate type + project
  const handleSelectSummary = (item) => {
    setSelected(item);
    setChosenType(item.suggestedType && TYPE_LABELS[item.suggestedType] ? item.suggestedType : '');
    setChosenProjectId(item.projectId || (projects.length === 1 ? projects[0].id : ''));
  };

  const handleDismiss = async (id) => {
    setSummaries(prev => {
      const next = prev.filter(x => x.id !== id);
      if (next.length === 0) {
        setTimeout(() => onClose && onClose(), 100);
      }
      return next;
    });
    try {
      if (window.PendingSummariesAPI) {
        await window.PendingSummariesAPI.approveRejected(id);
      }
    } catch (e) {
      console.warn('[PendingSummaries] dismiss failed:', e.message);
    }
  };

  const handleOpenForm = async () => {
    if (!chosenType || !chosenProjectId) return;
    setAiLoading(true);
    setAiToast('');
    let structured = await structureSummary(selected.summary, chosenType);
    setAiLoading(false);
    if (!structured) setAiToast('AI לא זמין — ממולא טקסט גולמי');

    // Final fallback: גם אם AI נפל לגמרי, ננסה לפרסר bullets ולחלץ ריג'קטים
    let bulletRejects = [];
    if (chosenType === 'daily' || chosenType === 'rejects') {
      const aiRejects = Array.isArray(structured?.rejects) ? structured.rejects : [];
      if (aiRejects.length === 0) {
        bulletRejects = parseBulletPoints(selected.summary);
        if (bulletRejects.length > 0) {
          structured = structured || {};
          structured.rejects = bulletRejects;
          console.warn('[PendingSummaries] Final bullet fallback yielded ' + bulletRejects.length + ' rejects');
        }
      }
    }

    // suggestedRejects (מה-DataStore) משולב עם bulletRejects (אם AI נפל)
    const mergedSuggested = (selected.rejects && selected.rejects.length)
      ? selected.rejects
      : (bulletRejects.length ? bulletRejects : []);

    const prefillData = {
      summaryId:        selected.id,
      summaryText:      selected.summary,
      suggestedRejects: mergedSuggested,
      meta:             selected.meta,
      structured:       structured || null,
    };
    onOpenForm(chosenType, chosenProjectId, prefillData);
  };

  // ── Loading ───────────────────────────────────────────────────────────────
  if (loading) {
    return (
      <div style={overlayStyle}>
        <div style={modalCardStyle}>
          <div style={{ padding: '40px 20px', textAlign: 'center', color: '#6b7280', fontSize: 15 }}>
            <div style={{ fontSize: 28, marginBottom: 12 }}>⏳</div>
            בודק סיכומים ממתינים...
          </div>
        </div>
      </div>
    );
  }

  // ── Error ─────────────────────────────────────────────────────────────────
  if (error) {
    return (
      <div style={overlayStyle}>
        <div style={modalCardStyle}>
          <div style={{ padding: '32px 20px', textAlign: 'center' }}>
            <div style={{ fontSize: 24, marginBottom: 8 }}>⚠️</div>
            <div style={{ fontSize: 14, color: '#dc2626', marginBottom: 20 }}>{error}</div>
            <button onClick={onClose} style={btnSecondaryStyle}>סגור</button>
          </div>
        </div>
      </div>
    );
  }

  // ── Detail View (selected summary) ───────────────────────────────────────
  if (selected) {
    const projName = chosenProjectId
      ? (projects.find(p => p.id === chosenProjectId)?.name || chosenProjectId)
      : null;
    const canSubmit = !!chosenType && !!chosenProjectId;

    return (
      <div style={overlayStyle}>
        <div style={modalCardStyle}>
          {/* Header */}
          <div style={headerStyle}>
            <button onClick={() => setSelected(null)} style={backBtnStyle}>
              ← חזרה
            </button>
            <span style={{ fontSize: 16, fontWeight: 700, color: '#1f2937' }}>איזה דוח למלא?</span>
            <button onClick={onClose} style={closeBtnStyle}>✕</button>
          </div>

          <div style={{ padding: '16px', overflowY: 'auto', flex: 1, direction: 'rtl' }}>
            {/* Summary text */}
            <div style={{
              background: '#f8fafc', borderRadius: 10, border: '1px solid #e5e7eb',
              padding: '12px 14px', marginBottom: 18, maxHeight: 200, overflowY: 'auto',
            }}>
              <div style={{ fontSize: 11, fontWeight: 700, color: '#9ca3af', marginBottom: 6, textTransform: 'uppercase', letterSpacing: 0.5 }}>
                סיכום מקלוד צ'ט
              </div>
              <div style={{ fontSize: 13.5, color: '#374151', lineHeight: 1.6, whiteSpace: 'pre-wrap', wordBreak: 'break-word' }}>
                {selected.summary}
              </div>
            </div>

            {/* Rejects notice */}
            {selected.rejects.length > 0 && (
              <div style={{
                background: '#fef3c7', borderRadius: 8, border: '1px solid #fcd34d',
                padding: '10px 12px', marginBottom: 16, fontSize: 13, color: '#92400e',
              }}>
                {`ℹ️ זוהו ${selected.rejects.length} ריג'קטים בסיכום. אם תבחר "דוח יומי" הם יתווספו אוטומטית לסעיף הריג'קטים בדוח.`}
              </div>
            )}

            {/* Report type selection */}
            <div style={{ marginBottom: 18 }}>
              <div style={{ fontSize: 13, fontWeight: 700, color: '#374151', marginBottom: 10 }}>סוג דוח</div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                {Object.entries(TYPE_LABELS).map(([k, label]) => (
                  <label key={k} style={{
                    display: 'flex', alignItems: 'center', gap: 12,
                    padding: '12px 14px', borderRadius: 9, cursor: 'pointer',
                    border: `1.5px solid ${chosenType === k ? '#1d4ed8' : '#e5e7eb'}`,
                    background: chosenType === k ? '#eff6ff' : '#fff',
                    minHeight: 48,
                  }}>
                    <input
                      type="radio"
                      name="reportType"
                      value={k}
                      checked={chosenType === k}
                      onChange={() => setChosenType(k)}
                      style={{ width: 18, height: 18, cursor: 'pointer', accentColor: '#1d4ed8', flexShrink: 0 }}
                    />
                    <span style={{ fontSize: 15, fontWeight: chosenType === k ? 700 : 400, color: '#1f2937' }}>
                      {label}
                    </span>
                  </label>
                ))}
              </div>
            </div>

            {/* Project selection (only if not pre-filled or ambiguous) */}
            {(!selected.projectId || projects.length > 1) && (
              <div style={{ marginBottom: 18 }}>
                <div style={{ fontSize: 13, fontWeight: 700, color: '#374151', marginBottom: 8 }}>
                  פרויקט {!selected.projectId && <span style={{ color: '#dc2626' }}>*</span>}
                </div>
                <select
                  value={chosenProjectId}
                  onChange={e => setChosenProjectId(e.target.value)}
                  style={{
                    width: '100%', padding: '12px', borderRadius: 8,
                    border: `1.5px solid ${!chosenProjectId ? '#dc2626' : '#e5e7eb'}`,
                    fontSize: 15, fontFamily: 'inherit', background: '#fff',
                    color: '#1f2937', boxSizing: 'border-box',
                  }}
                >
                  <option value="">— בחר פרויקט —</option>
                  {projects.map(p => (
                    <option key={p.id} value={p.id}>{p.name}</option>
                  ))}
                </select>
              </div>
            )}
          </div>

          {/* AI Toast */}
          {aiToast && (
            <div style={{ margin: '0 16px 8px', padding: '8px 12px', background: '#fef3c7', borderRadius: 8, fontSize: 13, color: '#92400e', direction: 'rtl' }}>
              ⚠️ {aiToast}
            </div>
          )}

          {/* Footer buttons */}
          <div style={{ padding: '12px 16px', borderTop: '1px solid #e5e7eb', display: 'flex', gap: 10, direction: 'rtl' }}>
            <button
              onClick={handleOpenForm}
              disabled={!canSubmit || aiLoading}
              style={{
                ...btnPrimaryStyle,
                flex: 1,
                opacity: (canSubmit && !aiLoading) ? 1 : 0.6,
                cursor: (canSubmit && !aiLoading) ? 'pointer' : 'not-allowed',
                display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
              }}
            >
              {aiLoading ? (
                <>
                  <span style={{ display: 'inline-block', width: 16, height: 16, border: '2px solid rgba(255,255,255,0.4)', borderTopColor: '#fff', borderRadius: '50%', animation: 'spin 0.7s linear infinite' }}/>
                  🧠 מבנה את הסיכום...
                </>
              ) : 'המשך לטופס ←'}
            </button>
            <button
              onClick={async () => {
                if (!window.confirm('למחוק את הסיכום מהרשימה? לא ניתן לשחזר.')) return;
                const id = selected.id;
                setSummaries(prev => {
                  const next = prev.filter(x => x.id !== id);
                  if (next.length === 0) {
                    setTimeout(() => onClose && onClose(), 100);
                  }
                  return next;
                });
                setSelected(null);
                try {
                  if (window.PendingSummariesAPI) {
                    await window.PendingSummariesAPI.approveRejected(id);
                  }
                } catch (e) {
                  console.warn('[PendingSummaries] detail dismiss failed:', e.message);
                }
              }}
              disabled={aiLoading}
              style={{
                background: 'var(--ybp-panel,#fff)',
                color: 'var(--ybp-danger,#dc2626)',
                border: '1px solid var(--ybp-danger-bg,#fecaca)',
                padding: '10px 16px', borderRadius: 8, fontSize: 13, fontWeight: 600,
                cursor: aiLoading ? 'not-allowed' : 'pointer',
                fontFamily: 'inherit', opacity: aiLoading ? 0.5 : 1,
                display: 'flex', alignItems: 'center', gap: 6,
              }}
            >
              🗑 מחק סיכום
            </button>
            <button onClick={() => setSelected(null)} disabled={aiLoading} style={{ ...btnSecondaryStyle, minWidth: 80, opacity: aiLoading ? 0.5 : 1 }}>
              ביטול
            </button>
          </div>
        </div>
      </div>
    );
  }

  // ── List View ─────────────────────────────────────────────────────────────
  return (
    <div style={overlayStyle}>
      <div style={modalCardStyle}>
        {/* Header */}
        <div style={headerStyle}>
          <span style={{ fontSize: 16, fontWeight: 700, color: '#1f2937' }}>
            {`📥 סיכומים ממתינים מקלוד צ'ט (${summaries.length})`}
          </span>
          <button onClick={onClose} style={closeBtnStyle}>✕</button>
        </div>

        {/* List */}
        <div style={{ padding: '12px 16px', overflowY: 'auto', flex: 1, display: 'flex', flexDirection: 'column', gap: 10 }}>
          {summaries.map(item => (
            <SummaryCard
              key={item.id}
              item={item}
              onClick={() => handleSelectSummary(item)}
              onDismiss={handleDismiss}
            />
          ))}
        </div>

        {/* Footer */}
        <div style={{ padding: '12px 16px', borderTop: '1px solid #e5e7eb' }}>
          <button onClick={onClose} style={{ ...btnSecondaryStyle, width: '100%' }}>
            מאוחר יותר
          </button>
        </div>
      </div>
    </div>
  );
};

// ── Style constants ───────────────────────────────────────────────────────────
const overlayStyle = {
  position: 'fixed', inset: 0, zIndex: 10000,
  background: 'rgba(0,0,0,0.5)',
  display: 'flex', alignItems: 'flex-end', justifyContent: 'center',
  fontFamily: 'Assistant, sans-serif',
};

const modalCardStyle = {
  background: '#fff', borderRadius: '16px 16px 0 0',
  width: '100%', maxWidth: 520,
  maxHeight: '90vh', display: 'flex', flexDirection: 'column',
  boxShadow: '0 -8px 40px rgba(0,0,0,0.15)',
};

const headerStyle = {
  display: 'flex', alignItems: 'center', justifyContent: 'space-between',
  padding: '16px 16px 12px', borderBottom: '1px solid #e5e7eb',
  direction: 'rtl', flexShrink: 0,
};

const backBtnStyle = {
  background: 'none', border: 'none', color: '#1d4ed8',
  fontSize: 14, fontWeight: 700, cursor: 'pointer',
  padding: '8px 4px', fontFamily: 'inherit', minHeight: 44,
};

const closeBtnStyle = {
  background: '#f3f4f6', border: 'none', borderRadius: 8,
  width: 36, height: 36, cursor: 'pointer', fontSize: 15,
  display: 'flex', alignItems: 'center', justifyContent: 'center',
  flexShrink: 0,
};

const btnPrimaryStyle = {
  padding: '14px 20px', borderRadius: 9, border: 'none',
  background: '#1a2c4a', color: '#fff',
  fontSize: 15, fontWeight: 700, fontFamily: 'inherit',
  minHeight: 50,
};

const btnSecondaryStyle = {
  padding: '12px 16px', borderRadius: 9,
  border: '1.5px solid #e5e7eb', background: '#fff',
  color: '#374151', fontSize: 14, fontWeight: 600,
  fontFamily: 'inherit', cursor: 'pointer', minHeight: 48,
};

window.PendingSummariesModal = PendingSummariesModal;
})();
