// ============================================================
// Saraya Events — Customer Notifications Page
//
// Full-page view of a signed-in customer's notifications
// (order status changes, RFQ offers, complaint updates).
// Reads from the shared `notifications` table via
// window.SarayaService.notifications (see db-service.js).
// ============================================================

function NotificationsPage() {
  const auth = window.useAuth ? window.useAuth() : {};
  const user = auth.user;
  let lang = 'en';
  try { lang = (React.useContext(window.LangContext) || {}).lang || localStorage.getItem('saraya_lang') || 'en'; } catch (e) {}
  const ar = lang === 'ar';

  const [items, setItems] = React.useState([]);
  const [loading, setLoading] = React.useState(true);

  const load = React.useCallback(async () => {
    if (!user || !window.SarayaService) { setLoading(false); return; }
    setLoading(true);
    const rows = await window.SarayaService.notifications.list(user.id, { limit: 100 });
    setItems(rows || []);
    setLoading(false);
  }, [user]);

  React.useEffect(() => { load(); }, [load]);

  const markRead = async (id) => {
    if (!window.SarayaService) return;
    await window.SarayaService.notifications.markRead(id);
    setItems((prev) => prev.map((n) => (n.id === id ? { ...n, is_read: true } : n)));
  };

  const markAll = async () => {
    if (!user || !window.SarayaService) return;
    await window.SarayaService.notifications.markAllRead(user.id);
    setItems((prev) => prev.map((n) => ({ ...n, is_read: true })));
  };

  return (
    <main style={{ maxWidth: 720, margin: '0 auto', padding: '40px 20px 80px' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 }}>
        <h1 style={{ fontSize: 24, margin: 0 }}>{ar ? 'الإشعارات' : 'Notifications'}</h1>
        {items.length > 0 && (
          <button onClick={markAll} style={{ background: 'none', border: '1px solid #cbd5e1', borderRadius: 8, padding: '8px 14px', cursor: 'pointer', fontSize: 13 }}>
            {ar ? 'وضع علامة مقروء على الكل' : 'Mark all read'}
          </button>
        )}
      </div>
      {loading && (
        <div style={{ color: '#94a3b8', fontSize: 14 }}>{ar ? 'جارٍ التحميل...' : 'Loading...'}</div>
      )}
      {!loading && !items.length && (
        <div style={{ padding: '60px 20px', textAlign: 'center', color: '#94a3b8' }}>
          <p style={{ fontSize: 15 }}>{ar ? 'لا توجد إشعارات حتى الآن.' : 'No notifications yet.'}</p>
          <p style={{ fontSize: 13 }}>{ar ? 'ستظهر هنا تحديثات الطلبات والعروض وحالة الحساب.' : 'Updates on orders, offers, and your account will appear here.'}</p>
        </div>
      )}
      {!loading && !!items.length && (
        <div style={{ display: 'grid', gap: 10 }}>
          {items.map((n) => (
            <div key={n.id} onClick={() => !n.is_read && markRead(n.id)}
              style={{ padding: '16px 18px', borderRadius: 12, border: '1px solid ' + (n.is_read ? '#e2e8f0' : '#93c5fd'), background: n.is_read ? '#fff' : '#eff6ff', cursor: n.is_read ? 'default' : 'pointer' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', gap: 10 }}>
                <strong style={{ fontSize: 15 }}>{n.title || n.type}</strong>
                {!n.is_read && <span style={{ width: 8, height: 8, borderRadius: '50%', background: '#3b82f6', flexShrink: 0, marginTop: 5 }} />}
              </div>
              <div style={{ fontSize: 14, color: '#475569', marginTop: 6 }}>{n.body}</div>
              <div style={{ fontSize: 12, color: '#94a3b8', marginTop: 8 }}>{new Date(n.created_at).toLocaleString()}</div>
            </div>
          ))}
        </div>
      )}
    </main>
  );
}
window.NotificationsPage = NotificationsPage;
