// Notifications — Sayfa 6
// Dropdown panel (header bell tıklayınca) + Tüm bildirimler sayfası

// ─────────── Data ───────────
// Bildirim tipleri:
//   approved  — yöneticim onayladı
//   rejected  — talep reddedildi
//   moved     — bir sonraki aşamaya iletildi
//   completed — satınalma tamamlandı / teslim alındı
//   removed   — bir ürün talepten çıkarıldı
//   draft-reminder — taslak hatırlatması

const NOTIFICATIONS = [
  {
    id: 'n01', time: '2 saat önce', timeFull: '21 May 2026, 10:14',
    kind: 'approved', read: false,
    title: 'Talebiniz #IT-2026-00123 yöneticiniz tarafından onaylandı',
    body: 'Mehmet Demir tarafından onaylandı. Üst Yönetim onayı bekleniyor.',
    refId: '#IT-2026-00123',
  },
  {
    id: 'n02', time: '5 saat önce', timeFull: '21 May 2026, 07:42',
    kind: 'removed', read: false,
    title: 'Talebinizden 1 ürün çıkarıldı: Microsoft 365 Business Standard',
    body: 'Yöneticiniz, talep #IT-2026-00123 içindeki bu kalemi Q3 satınalmaya taşıdı.',
    refId: '#IT-2026-00123',
  },
  {
    id: 'n03', time: 'Dün', timeFull: '20 May 2026, 16:08',
    kind: 'moved', read: false,
    title: 'Talebiniz #IT-2026-00099 Satınalma aşamasına iletildi',
    body: 'IT teknik onayı tamamlandı. Tedarik süreci başladı, tahmini teslim 5-7 iş günü.',
    refId: '#IT-2026-00099',
  },
  {
    id: 'n04', time: '3 gün önce', timeFull: '18 May 2026, 11:30',
    kind: 'rejected', read: true,
    title: 'Talebiniz #IT-2026-00115 reddedildi',
    body: 'Üst Yönetim tarafından reddedildi. Gerekçe: Q1\'de aynı danışmanlık için bütçe ayrıldı.',
    refId: '#IT-2026-00115',
  },
  {
    id: 'n05', time: '5 gün önce', timeFull: '16 May 2026, 09:00',
    kind: 'completed', read: true,
    title: 'Talebiniz #IT-2026-00118 teslim edildi',
    body: 'Dell OptiPlex 7020 Micro siparişi tamamlandı. Cihazınızı IT ofisinden teslim alabilirsiniz.',
    refId: '#IT-2026-00118',
  },
  {
    id: 'n06', time: '1 hafta önce', timeFull: '14 May 2026, 14:55',
    kind: 'draft-reminder', read: true,
    title: '#IT-2026-00135 taslağı 7 gündür bekliyor',
    body: 'Sepetinizde bekleyen bir taslak var. Tamamlamak için Taleplerime gidin.',
    refId: '#IT-2026-00135',
  },
  {
    id: 'n07', time: '1 hafta önce', timeFull: '14 May 2026, 10:20',
    kind: 'moved', read: true,
    title: 'Talebiniz #IT-2026-00099 IT teknik onayına iletildi',
    body: 'Üst Yönetim onayı tamamlandı. IT ekibi teknik uygunluk kontrolü yapacak.',
    refId: '#IT-2026-00099',
  },
  {
    id: 'n08', time: '2 hafta önce', timeFull: '07 May 2026, 09:12',
    kind: 'approved', read: true,
    title: 'Talebiniz #IT-2026-00087 onay sürecini tamamladı',
    body: 'Tüm onaylar alındı, Satınalma siparişi oluşturdu.',
    refId: '#IT-2026-00087',
  },
];

function unreadCount() {
  return NOTIFICATIONS.filter((n) => !n.read).length;
}

// ─────────── Per-kind visual ───────────
const NOTIF_KINDS = {
  approved:        { bg: 'rgba(16,185,129,0.14)', color: '#047857', icon: 'check' },
  rejected:        { bg: 'rgba(239,68,68,0.14)',  color: '#B91C1C', icon: 'x' },
  moved:           { bg: 'rgba(37,99,235,0.14)',  color: '#1D4ED8', icon: 'arrow' },
  completed:       { bg: 'rgba(37,99,235,0.14)',  color: '#1D4ED8', icon: 'box' },
  removed:         { bg: 'rgba(245,158,11,0.14)', color: '#B45309', icon: 'minus' },
  'draft-reminder':{ bg: 'rgba(100,116,139,0.14)', color: '#475569', icon: 'edit' },
};

function NotifIcon({ name }) {
  const p = { width: 14, height: 14, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', strokeWidth: 2.4, strokeLinecap: 'round', strokeLinejoin: 'round' };
  if (name === 'check') return <svg {...p}><path d="M20 6L9 17l-5-5" /></svg>;
  if (name === 'x')     return <svg {...p}><path d="M18 6L6 18M6 6l12 12" /></svg>;
  if (name === 'arrow') return <svg {...p}><path d="M5 12h14M13 5l7 7-7 7" /></svg>;
  if (name === 'box')   return <svg {...p}><path d="M3 7l9-4 9 4M3 7v10l9 4 9-4V7M3 7l9 4 9-4M12 11v10" /></svg>;
  if (name === 'minus') return <svg {...p}><path d="M5 12h14" /></svg>;
  if (name === 'edit')  return <svg {...p}><path d="M12 20h9M16.5 3.5a2.12 2.12 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z" /></svg>;
  return <svg {...p}><circle cx="12" cy="12" r="4" /></svg>;
}

// ─────────── Dropdown panel ───────────
function NotifDropdown({ c, items, onClose, onSeeAll, onMarkAllRead }) {
  return (
    <div style={{
      position: 'absolute', top: 'calc(100% + 8px)', right: 0, zIndex: 31,
      width: 380,
      background: c.surface,
      border: `1px solid ${c.border}`,
      borderRadius: 14,
      boxShadow: '0 14px 40px -10px rgba(15,23,42,0.22)',
      overflow: 'hidden',
      animation: 'popDown 160ms cubic-bezier(.2,.9,.3,1.2)',
    }}>
      {/* Header */}
      <div style={{
        padding: '14px 16px 12px',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        borderBottom: `1px solid ${c.borderSoft}`,
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <div style={{ fontSize: 14, fontWeight: 600, color: c.text }}>Bildirimler</div>
          <div style={{
            padding: '2px 7px', borderRadius: 999,
            background: c.selectedBg, color: c.selectedText,
            fontSize: 10.5, fontWeight: 700,
          }}>{unreadCount()} yeni</div>
        </div>
        <button onClick={onMarkAllRead} style={{
          appearance: 'none', background: 'transparent', border: 'none',
          cursor: 'pointer', color: c.primary,
          fontSize: 11.5, fontWeight: 600, fontFamily: 'inherit',
          padding: 0,
        }}>Tümünü okundu işaretle</button>
      </div>

      {/* Items */}
      <div>
        {items.slice(0, 5).map((n) => (
          <NotifRow key={n.id} n={n} c={c} compact />
        ))}
      </div>

      {/* Footer */}
      <button onClick={onSeeAll} style={{
        display: 'block', width: '100%',
        appearance: 'none', cursor: 'pointer',
        background: c.borderSoft, color: c.primary,
        border: 'none', borderTop: `1px solid ${c.borderSoft}`,
        padding: '12px 16px',
        fontSize: 13, fontWeight: 600, fontFamily: 'inherit',
        textAlign: 'center',
      }}>
        Tüm bildirimleri gör →
      </button>
    </div>
  );
}

// ─────────── Single notification row (used by dropdown + page) ───────────
function NotifRow({ n, c, compact, onClick }) {
  const v = NOTIF_KINDS[n.kind] || NOTIF_KINDS.moved;
  const [hover, setHover] = React.useState(false);
  return (
    <div
      onClick={onClick}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{
        display: 'grid', gridTemplateColumns: '36px 1fr auto', gap: 12,
        padding: compact ? '12px 16px' : '16px 20px',
        background: hover ? c.borderSoft : (n.read ? 'transparent' : (compact ? c.selectedBg : c.selectedBg)),
        borderBottom: `1px solid ${c.borderSoft}`,
        cursor: onClick ? 'pointer' : 'default',
        position: 'relative',
        transition: 'background 120ms',
      }}>
      {/* Unread dot indicator at left edge */}
      {!n.read && (
        <span style={{
          position: 'absolute', left: 6, top: '50%', transform: 'translateY(-50%)',
          width: 6, height: 6, borderRadius: 999,
          background: c.primary,
        }} />
      )}

      {/* Icon */}
      <div style={{
        width: 36, height: 36, borderRadius: 10,
        background: v.bg, color: v.color,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        flexShrink: 0,
      }}>
        <NotifIcon name={v.icon} />
      </div>

      {/* Body */}
      <div style={{ minWidth: 0 }}>
        <div style={{
          fontSize: compact ? 12.5 : 13.5,
          fontWeight: n.read ? 500 : 600,
          color: c.text, lineHeight: 1.4,
        }}>{n.title}</div>
        <div style={{
          fontSize: compact ? 11.5 : 12.5,
          color: c.muted, marginTop: 4, lineHeight: 1.5,
          display: '-webkit-box', WebkitLineClamp: compact ? 1 : 2, WebkitBoxOrient: 'vertical', overflow: 'hidden',
        }}>{n.body}</div>
      </div>

      {/* Time */}
      <div style={{
        fontSize: 11, color: c.subtle, textAlign: 'right',
        whiteSpace: 'nowrap', alignSelf: 'flex-start',
        paddingTop: 2,
      }}>{compact ? n.time : n.timeFull}</div>
    </div>
  );
}

// ─────────── FULL NOTIFICATIONS PAGE ───────────
function NotificationsPage({ initialDark = false }) {
  const [dark, setDark] = React.useState(initialDark);
  React.useEffect(() => { setDark(initialDark); }, [initialDark]);

  const [filter, setFilter] = React.useState('all');
  // Paylaşılan bildirim state'inden oku — sayfa kapatılıp açılınca okundu işaretleri korunsun
  const items = useNotifSnapshot();
  const [headerSearch, setHeaderSearch] = React.useState('');
  const [bellOpen, setBellOpen] = React.useState(false);

  const c = catalogTheme(dark);

  const filtered = items.filter((n) => {
    if (filter === 'all') return true;
    if (filter === 'unread') return !n.read;
    if (filter === 'approved') return n.kind === 'approved' || n.kind === 'moved' || n.kind === 'completed';
    if (filter === 'rejected') return n.kind === 'rejected';
    return true;
  });

  const tabs = [
    { v: 'all',      label: 'Tümü',       count: items.length },
    { v: 'unread',   label: 'Okunmamış',  count: items.filter((x) => !x.read).length },
    { v: 'approved', label: 'Onay',       count: items.filter((x) => ['approved','moved','completed'].includes(x.kind)).length },
    { v: 'rejected', label: 'Red',        count: items.filter((x) => x.kind === 'rejected').length },
  ];

  function markAllRead() {
    if (window.__notif && typeof window.__notif.markAll === 'function') window.__notif.markAll();
  }

  function markOneRead(id) {
    if (window.__notif && typeof window.__notif.markOne === 'function') window.__notif.markOne(id);
  }

  const unread = items.filter((x) => !x.read).length;

  return (
    <div style={{
      width: '100%', height: '100%',
      background: c.bg, color: c.text,
      fontFamily: 'Inter, system-ui, sans-serif',
      display: 'flex', flexDirection: 'column',
    }}>
      <CatalogHeader
        c={c} dark={dark}
        onToggleDark={() => setDark((x) => !x)}
        search={headerSearch} setSearch={setHeaderSearch}
        cartCount={0}
        notifCount={unread}
      />

      <div style={{ padding: '28px 32px 40px', maxWidth: 920, margin: '0 auto', width: '100%', boxSizing: 'border-box' }}>
        <div style={{
          display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16, flexWrap: 'wrap',
        }}>
          <div>
            <h1 style={{ margin: 0, fontSize: 26, fontWeight: 600, letterSpacing: '-0.015em', color: c.text }}>
              Bildirimler
            </h1>
            <p style={{ margin: '6px 0 0', fontSize: 13, color: c.muted }}>
              {unread > 0
                ? <span><strong style={{ color: c.text, fontWeight: 600 }}>{unread} okunmamış</strong> bildirim var.</span>
                : 'Tüm bildirimler okundu.'}
            </p>
          </div>

          <button onClick={markAllRead} disabled={unread === 0} style={{
            appearance: 'none',
            cursor: unread === 0 ? 'not-allowed' : 'pointer',
            opacity: unread === 0 ? 0.5 : 1,
            padding: '10px 16px', borderRadius: 10,
            background: 'transparent', color: c.primary,
            border: `1px solid ${c.primary}66`,
            fontSize: 13, fontWeight: 600, fontFamily: 'inherit',
            display: 'inline-flex', alignItems: 'center', gap: 8,
          }}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
              <path d="M20 6L9 17l-5-5" />
            </svg>
            Tümünü okundu olarak işaretle
          </button>
        </div>

        {/* Filter chips */}
        <div style={{ marginTop: 20, display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
          {tabs.map((t) => {
            const active = filter === t.v;
            return (
              <button key={t.v} onClick={() => setFilter(t.v)} style={{
                appearance: 'none', cursor: 'pointer',
                padding: '8px 14px', borderRadius: 999,
                background: active ? c.primary : c.surface,
                color: active ? '#fff' : c.text,
                border: `1px solid ${active ? c.primary : c.border}`,
                fontSize: 12.5, fontWeight: 500, fontFamily: 'inherit',
                display: 'inline-flex', alignItems: 'center', gap: 7,
                transition: 'all 120ms',
              }}>
                {t.label}
                {t.count > 0 && (
                  <span style={{
                    fontSize: 10.5, fontWeight: 600,
                    padding: '1px 6px', borderRadius: 999,
                    background: active ? 'rgba(255,255,255,0.22)' : c.chipBg,
                    color: active ? '#fff' : c.muted,
                    minWidth: 18, textAlign: 'center',
                  }}>{t.count}</span>
                )}
              </button>
            );
          })}
        </div>

        {/* List */}
        <div style={{
          marginTop: 18,
          background: c.surface,
          border: `1px solid ${c.border}`,
          borderRadius: 14,
          overflow: 'hidden',
        }}>
          {filtered.length === 0 ? (
            <div style={{
              padding: 40, textAlign: 'center',
              color: c.muted, fontSize: 13,
            }}>Bu filtreye uygun bildirim bulunmuyor.</div>
          ) : (
            filtered.map((n, i) => (
              <NotifRow key={n.id} n={n} c={c} onClick={() => markOneRead(n.id)} />
            ))
          )}
        </div>

        {/* Footer: timeline group hint */}
        {filtered.length > 0 && (
          <div style={{
            marginTop: 14, textAlign: 'center',
            fontSize: 12, color: c.subtle,
          }}>
            Son 30 günün bildirimleri gösteriliyor.
            <a href="#" style={{ color: c.primary, marginLeft: 6, textDecoration: 'none', fontWeight: 500 }}>
              Bildirim tercihlerini düzenle →
            </a>
          </div>
        )}
      </div>

      <style>{`
        @keyframes popDown { from { opacity: 0; transform: translateY(-6px) scale(.98) } to { opacity: 1; transform: none } }
      `}</style>
    </div>
  );
}

// ─────────── Catalog-with-bell-open: katalog sayfası üzerinde dropdown açık ───────────
function CatalogWithNotifDropdown({ initialDark = false }) {
  return <CatalogPage initialDark={initialDark} initialBellOpen={true} />;
}

Object.assign(window, {
  NOTIFICATIONS, NOTIF_KINDS, NotifIcon, NotifDropdown, NotifRow,
  NotificationsPage, CatalogWithNotifDropdown, unreadCount,
});
