// פיצ'ר 3 — פופאפ תמונות אחרי שמירת דוח + שליחה ל-Make Drive
// offline queue + דחיסה + שמירה מקומית עד חזרת חיבור
(function(){
const { useState, useRef, useEffect, useCallback } = React;

// ── Make webhook ─────────────────────────────────────────────────────────────
const PHOTO_WEBHOOK_KEY = 'PLACEHOLDER_UPLOAD_PHOTO';
const PHOTO_WEBHOOK_FALLBACK = 'https://hook.eu2.make.com/od77j53zjvkzdc5rsyfpjfpg6rjuz4e4';

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

;(function seedPhotoWebhook() {
  try {
    const s = JSON.parse(localStorage.getItem('ybp_settings') || '{}');
    if (!(s.webhooks || {})[PHOTO_WEBHOOK_KEY]) {
      s.webhooks = { ...(s.webhooks || {}), [PHOTO_WEBHOOK_KEY]: PHOTO_WEBHOOK_FALLBACK };
      localStorage.setItem('ybp_settings', JSON.stringify(s));
    }
  } catch {}
})();

// ── offline queue ─────────────────────────────────────────────────────────────
const QUEUE_KEY = 'ybp_photo_upload_queue';

const getQueue = () => {
  try { return JSON.parse(localStorage.getItem(QUEUE_KEY) || '[]'); } catch { return []; }
};
const saveQueue = (q) => localStorage.setItem(QUEUE_KEY, JSON.stringify(q));

const addToQueue = (item) => {
  const q = getQueue();
  q.push({ ...item, queuedAt: Date.now() });
  saveQueue(q);
};

const removeFromQueue = (id) => {
  const q = getQueue().filter(i => i.id !== id);
  saveQueue(q);
};

// ── דחיסת תמונה ─────────────────────────────────────────────────────────────
const compressImage = (file, maxW = 1600, quality = 0.82) =>
  new Promise((resolve) => {
    const img = new Image();
    const url = URL.createObjectURL(file);
    img.onload = () => {
      URL.revokeObjectURL(url);
      const scale = Math.min(1, maxW / img.width, maxW / img.height);
      const w = Math.round(img.width * scale);
      const h = Math.round(img.height * scale);
      const canvas = document.createElement('canvas');
      canvas.width = w; canvas.height = h;
      canvas.getContext('2d').drawImage(img, 0, 0, w, h);
      canvas.toBlob(resolve, 'image/jpeg', quality);
    };
    img.src = url;
  });

// ── שליחה ל-Make ─────────────────────────────────────────────────────────────
const blobToBase64 = (blob) => new Promise((resolve, reject) => {
  const reader = new FileReader();
  reader.onload = () => resolve(reader.result.split(',')[1]);
  reader.onerror = reject;
  reader.readAsDataURL(blob);
});

const uploadPhoto = async ({ id, photoBlob, projectId, pmName, reportType, reportTopic, reportDate, photoIndex }) => {
  const url = getWebhookUrl(PHOTO_WEBHOOK_KEY);
  if (!url) throw new Error('no-webhook');
  const projectData = YBP_DATA.projects.find(p => p.id === projectId) || {};
  const fallback = (window.YBP_AUTH && window.YBP_AUTH.getCurrentUser) ? window.YBP_AUTH.getCurrentUser().name : '';
  const managerName = (pmName || fallback || '').trim();
  const projName = (projectData.name || projectId || '').trim();
  if (!managerName || managerName === 'מנהל' || managerName === 'מנהל פרויקט') {
    if (window.toastError) window.toastError('הגדר שם מנהל בפרופיל לפני העלאת תמונות');
    throw new Error('invalid-manager');
  }
  if (!projName) {
    if (window.toastError) window.toastError('שם הפרויקט חסר');
    throw new Error('invalid-project');
  }
  const image_base64 = await blobToBase64(photoBlob);

  const resp = await fetch(url, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      manager: managerName,
      project: projName,
      rejection_name: reportTopic || reportType || 'תמונה',
      date: reportDate,
      image_base64,
      photo_index: photoIndex || Date.now(),
    }),
  });
  if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
  return await resp.json();
};

// ── background sync loop ──────────────────────────────────────────────────────
const startSyncLoop = () => {
  const tryFlush = async () => {
    if (!navigator.onLine) return;
    const q = getQueue();
    if (!q.length) return;

    for (const item of q) {
      try {
        // blob שוחזר מ-base64
        const resp = await fetch(item.photoDataUrl);
        const blob = await resp.blob();
        await uploadPhoto({ ...item, photoBlob: blob });
        removeFromQueue(item.id);
        console.log('[PhotoQueue] העלאה הצליחה:', item.id);
        // dispatch event כדי לעדכן UI
        window.dispatchEvent(new CustomEvent('ybp-photo-uploaded', { detail: { id: item.id } }));
      } catch (err) {
        console.warn('[PhotoQueue] נכשל — ינסה שוב:', item.id, err);
      }
    }
  };

  window.addEventListener('online', tryFlush);
  setInterval(tryFlush, 30000); // ניסיון כל 30 שניות
  tryFlush(); // ניסיון מיידי
};

// הפעל loop
if (typeof window !== 'undefined' && !window.__ybpPhotoSyncStarted) {
  window.__ybpPhotoSyncStarted = true;
  startSyncLoop();
}

// ── קומפוננט פופאפ ───────────────────────────────────────────────────────────
const PhotoUploadPopup = ({
  projectId,
  reportType,    // 'דוח שדה' | 'ריג\'קט' | 'סקר תשתיות' | 'סיכום דיון' | ...
  reportTopic,   // שם/נושא הדוח
  reportDate,    // YYYY-MM-DD
  onClose,
}) => {
  const [photos, setPhotos] = useState([]);       // { id, file, blob, preview, status }
  const [uploading, setUploading] = useState(false);
  const [allDone, setAllDone] = useState(false);
  const [queuedCount, setQueuedCount] = useState(0);
  const fileRef = useRef(null);
  const cameraRef = useRef(null);

  const pmName = ((window.YBP_AUTH && window.YBP_AUTH.getCurrentUser) ? window.YBP_AUTH.getCurrentUser().name : '') || 'מנהל';
  const fmtDate = (iso) => iso.split('-').reverse().join('.');

  // ── הוספת תמונה ───────────────────────────────────────────────────
  const addPhoto = useCallback(async (file) => {
    if (!file || !file.type.startsWith('image/')) return;
    const id = `ph-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;
    const preview = URL.createObjectURL(file);
    const compressed = await compressImage(file);
    setPhotos(prev => [...prev, { id, file, blob: compressed, preview, status: 'ready' }]);
  }, []);

  const handleFileInput = async (e) => {
    const files = Array.from(e.target.files || []);
    for (const f of files) await addPhoto(f);
    e.target.value = '';
  };

  const removePhoto = (id) => {
    setPhotos(prev => {
      const ph = prev.find(p => p.id === id);
      if (ph) URL.revokeObjectURL(ph.preview);
      return prev.filter(p => p.id !== id);
    });
  };

  // ── שלח תמונות ────────────────────────────────────────────────────
  const uploadAll = async () => {
    if (!photos.length) { onClose(); return; }
    setUploading(true);
    let queued = 0;

    for (const ph of photos) {
      setPhotos(prev => prev.map(p => p.id === ph.id ? { ...p, status: 'uploading' } : p));
      try {
        if (navigator.onLine) {
          await uploadPhoto({
            id: ph.id,
            photoBlob: ph.blob,
            projectId, pmName, reportType, reportTopic, reportDate,
          });
          setPhotos(prev => prev.map(p => p.id === ph.id ? { ...p, status: 'done' } : p));
        } else {
          throw new Error('offline');
        }
      } catch (err) {
        // offline — queue
        const reader = new FileReader();
        await new Promise(resolve => {
          reader.onload = e => {
            addToQueue({ id: ph.id, photoDataUrl: e.target.result, projectId, pmName, reportType, reportTopic, reportDate });
            resolve();
          };
          reader.readAsDataURL(ph.blob);
        });
        setPhotos(prev => prev.map(p => p.id === ph.id ? { ...p, status: 'queued' } : p));
        queued++;
      }
    }

    setQueuedCount(queued);
    setUploading(false);
    setAllDone(true);
  };

  // סגנונות
  const overlay = {
    position: 'fixed', inset: 0, zIndex: 9500,
    background: 'rgba(0,0,0,0.55)',
    display: 'flex', alignItems: 'flex-end', justifyContent: 'center',
  };
  const sheet = {
    background: '#fff', borderRadius: '16px 16px 0 0',
    width: '100%', maxWidth: 480,
    boxShadow: '0 -8px 40px rgba(0,0,0,0.2)',
    fontFamily: 'Assistant, sans-serif', direction: 'rtl',
    overflow: 'hidden',
    animation: 'ybp-slide-up 0.25s ease-out',
  };

  // inject animation
  useEffect(() => {
    if (!document.getElementById('ybp-photo-anim')) {
      const s = document.createElement('style');
      s.id = 'ybp-photo-anim';
      s.textContent = `@keyframes ybp-slide-up { from { transform: translateY(100%); opacity: 0; } to { transform: translateY(0); opacity: 1; } }`;
      document.head.appendChild(s);
    }
  }, []);

  const statusIcon = (status) => {
    if (status === 'done') return <span style={{ color: '#059669', fontSize: 16 }}>✅</span>;
    if (status === 'queued') return <span style={{ color: '#f59e0b', fontSize: 16 }}>📶</span>;
    if (status === 'uploading') return <div style={{ width: 16, height: 16, border: '2px solid #e5e7eb', borderTopColor: '#1a2c4a', borderRadius: 8, animation: 'ybp-spin 0.7s linear infinite' }}/>;
    return null;
  };

  return (
    <div style={overlay} onClick={e => e.target === e.currentTarget && !uploading && onClose()}>
      <div style={sheet}>
        {/* Handle */}
        <div style={{ padding: '10px 0 0', display: 'flex', justifyContent: 'center' }}>
          <div style={{ width: 36, height: 4, background: '#e5e7eb', borderRadius: 2 }}/>
        </div>

        {/* Header */}
        <div style={{ padding: '12px 20px 10px', borderBottom: '1px solid #f3f4f6' }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <div style={{ fontSize: 15, fontWeight: 700, color: '#1f2937' }}>
              📷 הוספת תמונות לדוח
            </div>
            {!uploading && !allDone && (
              <button onClick={onClose} style={{ background: 'none', border: 'none', color: '#9ca3af', fontSize: 20, cursor: 'pointer', lineHeight: 1 }}>✕</button>
            )}
          </div>
          <div style={{ fontSize: 12, color: '#6b7280', marginTop: 4 }}>
            {reportType} — {reportTopic} — {fmtDate(reportDate)}
          </div>
        </div>

        {/* Content */}
        <div style={{ padding: '16px 20px' }}>
          {!allDone ? (
            <>
              {/* כפתורי הוספה */}
              <div style={{ display: 'flex', gap: 10, marginBottom: 16 }}>
                {/* גלריה */}
                <input ref={fileRef} type="file" accept="image/*" multiple onChange={handleFileInput} style={{ display: 'none' }}/>
                <button
                  onClick={() => fileRef.current?.click()}
                  style={{ flex: 1, padding: '14px 10px', background: '#f9fafb', border: '1.5px dashed #d1d5db', borderRadius: 10, cursor: 'pointer', fontFamily: 'inherit', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6, color: '#374151' }}
                >
                  <span style={{ fontSize: 26 }}>🖼️</span>
                  <span style={{ fontSize: 13, fontWeight: 600 }}>גלריה</span>
                </button>

                {/* מצלמה */}
                <input ref={cameraRef} type="file" accept="image/*" capture="environment" onChange={handleFileInput} style={{ display: 'none' }}/>
                <button
                  onClick={() => cameraRef.current?.click()}
                  style={{ flex: 1, padding: '14px 10px', background: '#1a2c4a', border: 'none', borderRadius: 10, cursor: 'pointer', fontFamily: 'inherit', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6, color: '#fff' }}
                >
                  <span style={{ fontSize: 26 }}>📷</span>
                  <span style={{ fontSize: 13, fontWeight: 700 }}>צלם</span>
                </button>

                {/* ללא */}
                <button
                  onClick={onClose}
                  style={{ flex: 0.7, padding: '14px 8px', background: '#fff', border: '1.5px solid #e5e7eb', borderRadius: 10, cursor: 'pointer', fontFamily: 'inherit', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6, color: '#6b7280' }}
                >
                  <span style={{ fontSize: 26 }}>✕</span>
                  <span style={{ fontSize: 12, fontWeight: 600 }}>ללא</span>
                </button>
              </div>

              {/* תצוגה מקדימה של תמונות */}
              {photos.length > 0 && (
                <div style={{ marginBottom: 16 }}>
                  <div style={{ fontSize: 12, fontWeight: 700, color: '#374151', marginBottom: 8 }}>
                    {photos.length} תמונ{photos.length === 1 ? 'ה' : 'ות'} נבחרו:
                  </div>
                  <div style={{ display: 'flex', gap: 8, overflowX: 'auto', paddingBottom: 4 }}>
                    {photos.map(ph => (
                      <div key={ph.id} style={{ position: 'relative', flexShrink: 0 }}>
                        <img
                          src={ph.preview}
                          alt=""
                          style={{ width: 72, height: 72, objectFit: 'cover', borderRadius: 8, border: '2px solid #e5e7eb', display: 'block' }}
                        />
                        <button
                          onClick={() => removePhoto(ph.id)}
                          style={{ position: 'absolute', top: -6, left: -6, width: 20, height: 20, background: '#dc2626', color: '#fff', border: 'none', borderRadius: 10, fontSize: 11, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 700 }}
                        >✕</button>
                        {/* מידע גודל */}
                        <div style={{ fontSize: 9, color: '#6b7280', textAlign: 'center', marginTop: 2 }}>
                          {ph.blob ? (ph.blob.size / 1024).toFixed(0) + 'KB' : ''}
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {/* offline warning */}
              {!navigator.onLine && (
                <div style={{ background: '#fffbeb', border: '1px solid #fde68a', borderRadius: 8, padding: '8px 12px', marginBottom: 12, fontSize: 12, color: '#92400e', display: 'flex', gap: 8 }}>
                  <span>📶</span>
                  <span>אין חיבור לאינטרנט — התמונות ישמרו מקומית וישלחו אוטומטית כשהחיבור יחזור.</span>
                </div>
              )}

              {/* כפתורי פעולה */}
              <div style={{ display: 'flex', gap: 10 }}>
                {photos.length > 0 && (
                  <button
                    onClick={uploadAll}
                    disabled={uploading}
                    style={{
                      flex: 1, padding: '12px', background: uploading ? '#9ca3af' : '#1a2c4a',
                      color: '#fff', border: 'none', borderRadius: 8, fontSize: 14, fontWeight: 700,
                      cursor: uploading ? 'not-allowed' : 'pointer', fontFamily: 'inherit',
                      display: 'flex', alignItems: 'center', gap: 8, justifyContent: 'center',
                    }}
                  >
                    {uploading ? (
                      <>
                        <div style={{ width: 16, height: 16, border: '2px solid rgba(255,255,255,0.3)', borderTopColor: '#fff', borderRadius: 8, animation: 'ybp-spin 0.7s linear infinite' }}/>
                        שולח...
                      </>
                    ) : (
                      <>💾 שמור {photos.length > 0 ? `${photos.length} תמונ${photos.length === 1 ? 'ה' : 'ות'}` : ''} ב-Drive</>
                    )}
                  </button>
                )}
              </div>
            </>
          ) : (
            /* סיום */
            <div style={{ textAlign: 'center', padding: '8px 0 8px' }}>
              <div style={{ fontSize: 44, marginBottom: 8 }}>
                {queuedCount === photos.length ? '📶' : '✅'}
              </div>
              <div style={{ fontSize: 15, fontWeight: 700, color: '#1f2937', marginBottom: 6 }}>
                {queuedCount > 0
                  ? `${photos.length - queuedCount} תמונות נשלחו, ${queuedCount} בתור`
                  : `${photos.length} תמונות נשמרו ב-Drive`}
              </div>

              {/* סטטוס כל תמונה */}
              <div style={{ display: 'flex', gap: 8, justifyContent: 'center', marginBottom: 12 }}>
                {photos.map(ph => (
                  <div key={ph.id} style={{ position: 'relative' }}>
                    <img src={ph.preview} alt="" style={{ width: 48, height: 48, objectFit: 'cover', borderRadius: 6, border: `2px solid ${ph.status === 'done' ? '#86efac' : ph.status === 'queued' ? '#fde68a' : '#e5e7eb'}` }}/>
                    <div style={{ position: 'absolute', bottom: -4, left: '50%', transform: 'translateX(-50%)' }}>
                      {statusIcon(ph.status)}
                    </div>
                  </div>
                ))}
              </div>

              {queuedCount > 0 && (
                <div style={{ background: '#fffbeb', border: '1px solid #fde68a', borderRadius: 8, padding: '8px 12px', marginBottom: 12, fontSize: 12, color: '#92400e' }}>
                  📶 {queuedCount} תמונות בתור — ישלחו אוטומטית כשיהיה חיבור
                </div>
              )}

              <div style={{ fontSize: 12, color: '#6b7280', marginBottom: 14 }}>
                📁 Drive: תיעוד צילומים / {reportType}_{reportTopic}_{fmtDate(reportDate)}
              </div>

              <button onClick={onClose} style={{ padding: '10px 28px', background: '#1a2c4a', color: '#fff', border: 'none', borderRadius: 8, fontSize: 14, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit' }}>
                סגור
              </button>
            </div>
          )}
        </div>

        {/* queue badge */}
        {getQueue().length > 0 && !allDone && (
          <div style={{ padding: '0 20px 14px', fontSize: 11, color: '#f59e0b', textAlign: 'center' }}>
            📶 {getQueue().length} תמונות בתור לשליחה (offline)
          </div>
        )}
      </div>
    </div>
  );
};

// ── hook: usePhotoUpload ──────────────────────────────────────────────────────
// שימוש בטפסים: const { triggerPhotoUpload, PhotoPopup } = usePhotoUpload({ projectId, reportType, reportTopic, reportDate });
// אחרי submit: triggerPhotoUpload();
// ב-JSX: <PhotoPopup/>
const usePhotoUpload = ({ projectId, reportType, reportTopic, reportDate }) => {
  const [showPopup, setShowPopup] = useState(false);

  const triggerPhotoUpload = useCallback(() => {
    setShowPopup(true);
  }, []);

  const PhotoPopup = useCallback(() =>
    showPopup ? React.createElement(PhotoUploadPopup, {
      projectId,
      reportType,
      reportTopic,
      reportDate: reportDate || new Date().toISOString().slice(0,10),
      onClose: () => setShowPopup(false),
    }) : null
  , [showPopup, projectId, reportType, reportTopic, reportDate]);

  return { triggerPhotoUpload, PhotoPopup };
};

// ── queue status badge (גלובלי) ───────────────────────────────────────────────
const PhotoQueueBadge = () => {
  const [count, setCount] = useState(getQueue().length);

  useEffect(() => {
    const update = () => setCount(getQueue().length);
    window.addEventListener('ybp-photo-uploaded', update);
    window.addEventListener('online', update);
    const interval = setInterval(update, 5000);
    return () => {
      window.removeEventListener('ybp-photo-uploaded', update);
      window.removeEventListener('online', update);
      clearInterval(interval);
    };
  }, []);

  if (!count) return null;

  return (
    <div style={{
      position: 'fixed', top: 52, left: 12, zIndex: 7999,
      background: '#f59e0b', color: '#fff',
      padding: '4px 10px', borderRadius: 12,
      fontSize: 11, fontWeight: 700, fontFamily: 'Assistant, sans-serif',
      boxShadow: '0 2px 8px rgba(0,0,0,0.15)',
      display: 'flex', alignItems: 'center', gap: 5,
    }}>
      📶 {count} תמונות ממתינות לשליחה
    </div>
  );
};

Object.assign(window, { PhotoUploadPopup, usePhotoUpload, PhotoQueueBadge });
})();
