/**
 * Notifications + Reminders Module
 * NotificationsBell: פעמון + badge + inbox panel
 * ReminderEngine: בדיקת תאריכי יעד + יצירת התראות
 * נשמר ב: cloudSave('notifications_store')
 */
(function () {

const { useState, useEffect, useRef } = React;

// ── Types ─────────────────────────────────────────────────────────────────────
const NOTIF_TYPES = {
  task_due:      { icon: '⏰', color: '#eab308', bg: '#fffbeb', label: 'תזכורת משימה' },
  task_done:     { icon: '✅', color: '#16a34a', bg: '#f0fdf4', label: 'משימה הושלמה' },
  reject_new:    { icon: '🚨', color: '#dc2626', bg: '#fef2f2', label: 'ריג׳קט חדש' },
  quote_pending: { icon: '📋', color: '#7c3aed', bg: '#f5f3ff', label: 'הצעה ממתינה' },
  payment_approved:{ icon: '💰', color: '#16a34a', bg: '#f0fdf4', label: 'תשלום אושר' },
  protocol_new:  { icon: '📝', color: '#2563eb', bg: '#eff6ff', label: 'פרוטוקול חדש' },
  tender_update: { icon: '📬', color: '#ea580c', bg: '#fff7ed', label: 'עדכון מכרז' },
  dist_overdue:  { icon: '📤', color: '#ea580c', bg: '#fff7ed', label: 'תוכניות לא הופצו' },
  general:       { icon: '🔔', color: '#6b7280', bg: '#f9fafb', label: 'כללי' },
};

// ── Storage ───────────────────────────────────────────────────────────────────
const NOTIF_KEY = 'notifications_store';

function loadNotifications() {
  return window.cloudLoadSync ? window.cloudLoadSync(NOTIF_KEY, []) : [];
}

function saveNotifications(list) {
  if (window.cloudSaveSync) window.cloudSaveSync(NOTIF_KEY, list);
}

function genNotifId() {
  return 'notif_' + Date.now().toString(36) + Math.random().toString(36).slice(2, 5);
}

// ── Public API: addNotification ───────────────────────────────────────────────
function addNotification({ type = 'general', title, body, screen, projectId, entityId }) {
  const notifs = loadNotifications();
  const newNotif = {
    id: genNotifId(),
    type, title, body, screen, projectId, entityId,
    createdAt: new Date().toISOString(),
    read: false,
  };
  const updated = [newNotif, ...notifs].slice(0, 100); // max 100
  saveNotifications(updated);
  // dispatch event לעדכון ה-bell
  window.dispatchEvent(new CustomEvent('ybp-notification-added', { detail: newNotif }));
  return newNotif.id;
}

// ── Reminder Engine ───────────────────────────────────────────────────────────
function runReminderEngine() {
  if (!window.SyncStore) return;
  const store = window.SyncStore.get();
  const tasks = (store.tasks || []).filter(t => t.status !== 'archived');
  const existingNotifs = loadNotifications();
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  const newNotifs = [];

  tasks.forEach(task => {
    if (task.status === 'done') return;
    if (!task.due) return;

    const due = new Date(task.due);
    due.setHours(0, 0, 0, 0);
    const daysLeft = Math.ceil((due - today) / 86400000);

    // בדוק אם כבר נשלחה תזכורת היום למשימה זו
    const alreadySent = existingNotifs.some(n =>
      n.entityId === task.id &&
      n.type === 'task_due' &&
      n.createdAt.slice(0, 10) === today.toISOString().slice(0, 10)
    );
    if (alreadySent) return;

    let shouldNotify = false;
    let urgency = '';

    if (daysLeft < 0) {
      shouldNotify = true;
      urgency = `איחור של ${Math.abs(daysLeft)} ימים`;
    } else if (daysLeft === 0) {
      shouldNotify = true;
      urgency = 'היום הוא המועד האחרון';
    } else if (daysLeft === 2) {
      shouldNotify = true;
      urgency = '2 ימים לתאריך היעד';
    } else if (daysLeft === 3) {
      shouldNotify = true;
      urgency = '3 ימים לתאריך היעד';
    } else if (daysLeft === 7) {
      shouldNotify = true;
      urgency = 'שבוע לתאריך היעד';
    }

    if (shouldNotify) {
      newNotifs.push({
        id: genNotifId(),
        type: 'task_due',
        title: task.title,
        body: urgency + (task.assignee ? ` · ${task.assignee}` : ''),
        screen: 'tasks',
        projectId: task.projectId ?? null,
        entityId: task.id,
        createdAt: new Date().toISOString(),
        read: false,
      });
    }
  });

  if (newNotifs.length > 0) {
    const updated = [...newNotifs, ...existingNotifs].slice(0, 100);
    saveNotifications(updated);
    newNotifs.forEach(n => {
      window.dispatchEvent(new CustomEvent('ybp-notification-added', { detail: n }));
    });
  }

  return newNotifs.length;
}

// ── NotificationItem ─────────────────────────────────────────────────────────
const NotificationItem = ({ notif, onRead, onNavigate }) => {
  const cfg = NOTIF_TYPES[notif.type] || NOTIF_TYPES.general;
  const timeAgo = (() => {
    const diff = Date.now() - new Date(notif.createdAt).getTime();
    const mins = Math.floor(diff / 60000);
    const hours = Math.floor(diff / 3600000);
    const days = Math.floor(diff / 86400000);
    if (mins < 1) return 'עכשיו';
    if (mins < 60) return `לפני ${mins} דק'`;
    if (hours < 24) return `לפני ${hours} שע'`;
    return `לפני ${days} ימים`;
  })();

  return (
    <div
      onClick={() => { onRead(notif.id); onNavigate(notif.screen, notif.projectId); }}
      style={{
        padding: '12px 16px',
        background: notif.read ? 'transparent' : cfg.bg,
        borderBottom: '1px solid var(--ybp-border,#e5e7eb)',
        cursor: 'pointer', display: 'flex', gap: 12, alignItems: 'flex-start',
        transition: 'background 0.15s',
      }}
      onMouseEnter={e => e.currentTarget.style.background = 'var(--ybp-row-hover,#f6f7f9)'}
      onMouseLeave={e => e.currentTarget.style.background = notif.read ? 'transparent' : cfg.bg}
    >
      {/* Icon */}
      <div style={{
        width: 36, height: 36, borderRadius: '50%',
        background: cfg.bg, border: `1.5px solid ${cfg.color}20`,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontSize: 16, flexShrink: 0,
      }}>{cfg.icon}</div>

      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 6 }}>
          <div style={{
            fontSize: 13, fontWeight: notif.read ? 500 : 700,
            color: 'var(--ybp-ink,#111827)',
            overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', flex: 1,
          }}>{notif.title}</div>
          <span style={{ fontSize: 10, color: 'var(--ybp-ink-faint,#9ca3af)', flexShrink: 0 }}>{timeAgo}</span>
        </div>
        {notif.body && (
          <div style={{ fontSize: 12, color: 'var(--ybp-ink-faint,#6b7280)', marginTop: 2, lineHeight: 1.4 }}>
            {notif.body}
          </div>
        )}
        <div style={{ fontSize: 10, color: cfg.color, fontWeight: 600, marginTop: 3 }}>
          {cfg.label}
        </div>
      </div>

      {/* Unread dot */}
      {!notif.read && (
        <div style={{
          width: 8, height: 8, borderRadius: '50%',
          background: cfg.color, flexShrink: 0, marginTop: 4,
        }} />
      )}
    </div>
  );
};

// ── NotificationsInbox ───────────────────────────────────────────────────────
const NotificationsInbox = ({ notifications, onClose, onNavigate, onMarkAllRead, onClearAll }) => {
  const [tab, setTab] = useState('new'); // new | read
  const [notifs, setNotifs] = useState(notifications);

  useEffect(() => { setNotifs(notifications); }, [notifications]);

  const handleRead = (id) => {
    const updated = notifs.map(n => n.id === id ? { ...n, read: true } : n);
    setNotifs(updated);
    saveNotifications(updated);
  };

  const unread = notifs.filter(n => !n.read);
  const read = notifs.filter(n => n.read);
  const display = tab === 'new' ? unread : read;

  return (
    <div style={{
      position: 'fixed',
      top: 44, left: 0,
      width: Math.min(380, window.innerWidth),
      maxHeight: 'calc(100vh - 44px)',
      background: 'var(--ybp-panel,#fff)',
      boxShadow: '0 8px 32px rgba(0,0,0,0.16)',
      borderRadius: '0 0 12px 0',
      zIndex: 9900,
      display: 'flex', flexDirection: 'column',
      fontFamily: 'Assistant, sans-serif', direction: 'rtl',
      border: '1px solid var(--ybp-border,#e5e7eb)',
    }}>
      {/* Header */}
      <div style={{
        padding: '14px 16px', borderBottom: '1px solid var(--ybp-border,#e5e7eb)',
        display: 'flex', justifyContent: 'space-between', alignItems: 'center',
      }}>
        <h3 style={{ margin: 0, fontSize: 16, fontWeight: 700, color: 'var(--ybp-ink,#111827)' }}>
          🔔 התראות
          {unread.length > 0 && (
            <span style={{
              marginRight: 6, padding: '1px 7px', borderRadius: 99,
              background: '#dc2626', color: '#fff', fontSize: 11, fontWeight: 700,
            }}>{unread.length}</span>
          )}
        </h3>
        <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
          {unread.length > 0 && (
            <button onClick={onMarkAllRead} style={{
              fontSize: 11, color: '#2563eb', background: 'none', border: 'none',
              cursor: 'pointer', fontFamily: 'Assistant, sans-serif',
            }}>סמן הכל כנקרא</button>
          )}
          <button onClick={onClose} style={{
            background: 'none', border: 'none', cursor: 'pointer',
            fontSize: 18, color: 'var(--ybp-ink-faint,#6b7280)', padding: 2,
          }}>✕</button>
        </div>
      </div>

      {/* Tabs */}
      <div style={{ display: 'flex', borderBottom: '1px solid var(--ybp-border,#e5e7eb)' }}>
        {[['new', `חדשות (${unread.length})`], ['read', `נקראו (${read.length})`]].map(([k, label]) => (
          <button key={k} onClick={() => setTab(k)} style={{
            flex: 1, padding: '9px', background: 'none', border: 'none',
            cursor: 'pointer', fontSize: 13,
            fontWeight: tab === k ? 700 : 500,
            color: tab === k ? '#1a2c4a' : 'var(--ybp-ink-faint,#6b7280)',
            borderBottom: tab === k ? '2px solid #1a2c4a' : '2px solid transparent',
            fontFamily: 'Assistant, sans-serif',
          }}>{label}</button>
        ))}
      </div>

      {/* List */}
      <div style={{ flex: 1, overflowY: 'auto' }}>
        {display.length === 0 ? (
          <div style={{ padding: '32px 16px', textAlign: 'center', color: 'var(--ybp-ink-faint,#6b7280)', fontSize: 13 }}>
            {tab === 'new' ? '✅ אין התראות חדשות' : 'אין התראות שנקראו'}
          </div>
        ) : (
          display.map(n => (
            <NotificationItem
              key={n.id} notif={n}
              onRead={handleRead}
              onNavigate={onNavigate}
            />
          ))
        )}
      </div>

      {/* Footer */}
      {notifs.length > 0 && (
        <div style={{
          padding: '10px 16px', borderTop: '1px solid var(--ybp-border,#e5e7eb)',
          display: 'flex', justifyContent: 'center',
        }}>
          <button onClick={onClearAll} style={{
            fontSize: 12, color: '#dc2626', background: 'none', border: 'none',
            cursor: 'pointer', fontFamily: 'Assistant, sans-serif',
          }}>נקה הכל</button>
        </div>
      )}
    </div>
  );
};

// ── Pending Rejects polling — DISABLED (Make webhook not configured yet) ────
async function checkPendingCount() {
  // TODO: Wire up real Make webhook URL in settings before enabling
  return 0;
}

// ── Check pending summaries count (Supabase direct) ─────────────────────────
async function checkPendingSummariesCount() {
  try {
    if (!window.YBP_SUPABASE) return 0;
    const sb = await window.YBP_SUPABASE.getClient();
    const { data: { session } } = await sb.auth.getSession();
    if (!session?.user?.id) return 0;
    const { count, error } = await sb
      .from('pending_summaries')
      .select('*', { count: 'exact', head: true })
      .eq('user_id', session.user.id);
    if (error) { console.warn('[pendingSummaries] count failed:', error.message); return 0; }
    return count || 0;
  } catch (e) {
    console.warn('[pendingSummaries] count error:', e.message);
    return 0;
  }
}

// ── NotificationsBell ────────────────────────────────────────────────────────
const NotificationsBell = ({ onNavigate }) => {
  const [notifs, setNotifs] = useState(loadNotifications);
  const [open, setOpen] = useState(false);
  const [animating, setAnimating] = useState(false);
  const [pendingCount, setPendingCount] = useState(0);
  const [pendingSummariesCount, setPendingSummariesCount] = useState(0);
  const bellRef = useRef(null);

  const unreadCount = notifs.filter(n => !n.read).length;

  // Poll for external pending rejects every 5 min when tab visible
  useEffect(() => {
    let cancelled = false;
    const poll = async () => {
      if (cancelled || document.visibilityState !== 'visible') return;
      const count = await checkPendingCount();
      if (!cancelled) setPendingCount(count);
    };
    const initTimer = setTimeout(poll, 1500);
    const interval = setInterval(poll, 5 * 60 * 1000);
    const onVisibility = () => { if (document.visibilityState === 'visible') poll(); };
    document.addEventListener('visibilitychange', onVisibility);
    return () => {
      cancelled = true;
      clearTimeout(initTimer);
      clearInterval(interval);
      document.removeEventListener('visibilitychange', onVisibility);
    };
  }, []);

  // Supabase Realtime — pending summaries count
  useEffect(() => {
    let channel = null;
    let cancelled = false;
    const init = async () => {
      const count = await checkPendingSummariesCount();
      if (!cancelled) setPendingSummariesCount(count);
      if (!window.YBP_SUPABASE) return;
      try {
        const sb = await window.YBP_SUPABASE.getClient();
        const { data: { session } } = await sb.auth.getSession();
        if (!session?.user?.id || cancelled) return;
        const userId = session.user.id;
        channel = sb
          .channel('bell-pending-summaries')
          .on('postgres_changes', {
            event: '*',
            schema: 'public',
            table: 'pending_summaries',
            filter: `user_id=eq.${userId}`,
          }, async () => {
            const c = await checkPendingSummariesCount();
            if (!cancelled) setPendingSummariesCount(c);
          })
          .subscribe();
      } catch (e) {
        console.warn('[bell] Realtime setup failed:', e.message);
      }
    };
    const initTimer = setTimeout(init, 2000);
    const onApproved = async () => {
      const c = await checkPendingSummariesCount();
      if (!cancelled) setPendingSummariesCount(c);
    };
    window.addEventListener('ybp-pending-summary-approved', onApproved);
    return () => {
      cancelled = true;
      clearTimeout(initTimer);
      window.removeEventListener('ybp-pending-summary-approved', onApproved);
      if (channel) { window.YBP_SUPABASE?.getClient?.().then?.(sb => sb.removeChannel(channel)).catch?.(() => {}); }
    };
  }, []);

  // Listen for new notifications
  useEffect(() => {
    const handler = () => {
      setNotifs(loadNotifications());
      // Bell animation
      setAnimating(true);
      setTimeout(() => setAnimating(false), 600);
    };
    window.addEventListener('ybp-notification-added', handler);
    window.addEventListener('ybp-cloud-change', handler);
    return () => {
      window.removeEventListener('ybp-notification-added', handler);
      window.removeEventListener('ybp-cloud-change', handler);
    };
  }, []);

  // Run reminder engine on mount
  useEffect(() => {
    const count = runReminderEngine();
    if (count > 0) setNotifs(loadNotifications());
    // Re-run every 5 minutes
    const interval = setInterval(() => {
      runReminderEngine();
      setNotifs(loadNotifications());
    }, 5 * 60 * 1000);
    return () => clearInterval(interval);
  }, []);

  const handleMarkAllRead = () => {
    const updated = notifs.map(n => ({ ...n, read: true }));
    setNotifs(updated);
    saveNotifications(updated);
  };

  const handleClearAll = () => {
    setNotifs([]);
    saveNotifications([]);
    setOpen(false);
    window.toastSuccess && window.toastSuccess('התראות נוקו');
  };

  const handleNavigate = (screen, projectId) => {
    setOpen(false);
    if (screen && onNavigate) onNavigate(screen, projectId);
  };

  // Close on outside click
  useEffect(() => {
    if (!open) return;
    const handler = (e) => {
      if (bellRef.current && !bellRef.current.contains(e.target)) {
        setOpen(false);
      }
    };
    document.addEventListener('mousedown', handler);
    return () => document.removeEventListener('mousedown', handler);
  }, [open]);

  return (
    <div ref={bellRef} style={{ position: 'relative', display: 'inline-flex', alignItems: 'center', gap: 2 }}>

      {/* Pending summaries button */}
      {pendingSummariesCount > 0 && (
        <button
          onClick={() => { setOpen(false); window.openPendingSummariesModal && window.openPendingSummariesModal(); }}
          title={`${pendingSummariesCount} סיכומים ממתינים מקלוד`}
          style={{
            position: 'relative', background: 'none', border: 'none',
            cursor: 'pointer', padding: '4px 5px',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}
          aria-label="סיכומים ממתינים"
        >
          <span style={{ fontSize: 18 }}>📋</span>
          <span style={{
            position: 'absolute', top: 0, left: 1,
            minWidth: 16, height: 16, borderRadius: 8,
            background: '#7c3aed', color: '#fff',
            fontSize: 10, fontWeight: 700,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            padding: '0 3px', lineHeight: 1,
            border: '1.5px solid var(--ybp-panel,#fff)',
          }}>
            {pendingSummariesCount > 9 ? '9+' : pendingSummariesCount}
          </span>
        </button>
      )}

      {/* Pending rejects tray button */}
      {pendingCount > 0 && (
        <button
          onClick={() => { setOpen(false); onNavigate && onNavigate('fieldCapture', null); }}
          title={`${pendingCount} ריג'קטים ממתינים לאישור`}
          style={{
            position: 'relative', background: 'none', border: 'none',
            cursor: 'pointer', padding: '4px 5px',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            animation: 'ybp-bell-shake 1s ease infinite',
          }}
          aria-label="ריג'קטים ממתינים"
        >
          <span style={{ fontSize: 18 }}>📥</span>
          <span style={{
            position: 'absolute', top: 0, left: 1,
            minWidth: 16, height: 16, borderRadius: 8,
            background: '#dc2626', color: '#fff',
            fontSize: 10, fontWeight: 700,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            padding: '0 3px', lineHeight: 1,
            border: '1.5px solid var(--ybp-panel,#fff)',
          }}>
            {pendingCount > 9 ? '9+' : pendingCount}
          </span>
        </button>
      )}

      {/* Bell button */}
      <button
        onClick={() => setOpen(o => !o)}
        style={{
          position: 'relative', background: 'none', border: 'none',
          cursor: 'pointer', padding: '4px 6px', display: 'flex',
          alignItems: 'center', justifyContent: 'center',
          animation: animating ? 'ybp-bell-shake 0.5s ease' : 'none',
        }}
        aria-label="התראות"
      >
        <Icon name="bell" size={20} color="var(--ybp-ink-soft,#374151)" />
        {unreadCount > 0 && (
          <span style={{
            position: 'absolute', top: 0, left: 2,
            minWidth: 16, height: 16, borderRadius: 8,
            background: '#dc2626', color: '#fff',
            fontSize: 10, fontWeight: 700,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            padding: '0 3px', lineHeight: 1,
            border: '1.5px solid var(--ybp-panel,#fff)',
          }}>
            {unreadCount > 9 ? '9+' : unreadCount}
          </span>
        )}
      </button>

      {/* Inbox panel */}
      {open && (
        <NotificationsInbox
          notifications={notifs}
          onClose={() => setOpen(false)}
          onNavigate={handleNavigate}
          onMarkAllRead={handleMarkAllRead}
          onClearAll={handleClearAll}
        />
      )}
    </div>
  );
};

// ── CSS animations ────────────────────────────────────────────────────────────
(function injectCSS() {
  if (document.getElementById('ybp-bell-css')) return;
  const st = document.createElement('style');
  st.id = 'ybp-bell-css';
  st.textContent = `
    @keyframes ybp-bell-shake {
      0%,100% { transform: rotate(0); }
      20%      { transform: rotate(-15deg); }
      40%      { transform: rotate(12deg); }
      60%      { transform: rotate(-8deg); }
      80%      { transform: rotate(5deg); }
    }
  `;
  document.head.appendChild(st);
})();

// ── Export ────────────────────────────────────────────────────────────────────
Object.assign(window, {
  NotificationsBell,
  NotificationsInbox,
  addNotification,
  runReminderEngine,
  loadNotifications,
});
})();
