// notificari.jsx — clopotelul din antetul panoului.
//
// Cererea colegilor: "cand un coleg modifica ceva la o campanie, sa stie ceilalti
// ca au de refacut sau de transmis mai departe".
//
// Ce NU face, intentionat: nu notifica pe toata lumea si nu notifica orice. Primesc
// doar campaign managerul si cel care tine legatura cu brandul, si doar pentru
// lucrurile care cer o reactie. Un clopotel care suna la fiecare virgula ajunge sa
// fie ignorat, si atunci nu mai foloseste la nimic.
//
// Cine decide ce se notifica: declansatoarele din baza de date (vezi sql/14).
// Aici doar afisam.
//
// Expune: window.NotificationBell({ profile, onNav })

const { useState: useStateNT, useEffect: useEffectNT, useRef: useRefNT } = React;

const NOTIF_ICONS = {
  campanie: '📣',
  creator: '👤',
  fisier: '📎',
  contract: '📄',
};

function timpRelativ(iso) {
  const d = new Date(iso);
  if (isNaN(d.getTime())) return '';
  const sec = Math.floor((Date.now() - d.getTime()) / 1000);
  if (sec < 60) return 'acum';
  if (sec < 3600) return 'acum ' + Math.floor(sec / 60) + ' min';
  if (sec < 86400) return 'acum ' + Math.floor(sec / 3600) + ' h';
  if (sec < 172800) return 'ieri';
  if (sec < 604800) return 'acum ' + Math.floor(sec / 86400) + ' zile';
  return d.toLocaleDateString('ro-RO');
}

function NotificationBell({ profile, onNav }) {
  const [items, setItems] = useStateNT([]);
  const [open, setOpen] = useStateNT(false);
  const wrapRef = useRefNT(null);

  const necitite = items.filter(n => !n.is_read).length;

  const incarca = async () => {
    if (!profile) return;
    const { data } = await window.sb
      .from('notifications')
      .select('*')
      .order('created_at', { ascending: false })
      .limit(30);
    setItems(data || []);
  };

  useEffectNT(() => {
    if (!profile) return;
    incarca();

    // Livrare in timp real: daca un coleg schimba ceva acum, se vede fara reincarcare.
    const channel = window.sb
      .channel('notificari-' + profile.id)
      .on('postgres_changes',
        { event: 'INSERT', schema: 'public', table: 'notifications', filter: 'recipient_id=eq.' + profile.id },
        () => incarca())
      .subscribe();

    return () => { try { window.sb.removeChannel(channel); } catch (e) {} };
  }, [profile && profile.id]);

  // Click in afara inchide panoul
  useEffectNT(() => {
    if (!open) return;
    const onDoc = (e) => {
      if (wrapRef.current && !wrapRef.current.contains(e.target)) setOpen(false);
    };
    document.addEventListener('mousedown', onDoc);
    return () => document.removeEventListener('mousedown', onDoc);
  }, [open]);

  const marcheazaCitite = async (ids) => {
    if (!ids.length) return;
    setItems(prev => prev.map(n => ids.indexOf(n.id) !== -1 ? Object.assign({}, n, { is_read: true }) : n));
    await window.sb.from('notifications').update({ is_read: true }).in('id', ids);
  };

  const deschide = async (n) => {
    setOpen(false);
    if (!n.is_read) marcheazaCitite([n.id]);
    if (n.campaign_id && onNav) {
      // Pagina de campanii citeste asta la incarcare si deschide direct campania.
      window.__deschideCampania = n.campaign_id;
      onNav('media-admin-campaigns');
    } else if (n.kind === 'contract' && onNav) {
      onNav('media-admin-contracts');
    }
  };

  if (!profile) return null;

  return (
    <div ref={wrapRef} style={{ position: 'relative' }}>
      <button
        type="button"
        onClick={() => setOpen(o => !o)}
        title={necitite > 0 ? necitite + ' notificări necitite' : 'Notificări'}
        aria-label={necitite > 0 ? necitite + ' notificări necitite' : 'Notificări'}
        style={{
          position: 'relative', width: 38, height: 38, borderRadius: 9,
          border: '.5px solid var(--line)', background: open ? 'rgba(82,242,15,.08)' : 'transparent',
          color: open ? 'var(--accent-1)' : 'var(--txt-2)', cursor: 'pointer',
          display: 'grid', placeItems: 'center', transition: 'all .15s',
        }}
      >
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor"
          strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
          <path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9" />
          <path d="M13.73 21a2 2 0 0 1-3.46 0" />
        </svg>
        {necitite > 0 && (
          <span style={{
            position: 'absolute', top: -5, right: -5, minWidth: 18, height: 18, padding: '0 5px',
            borderRadius: 9, background: '#FF5A5A', color: '#fff', fontSize: 10, fontWeight: 700,
            display: 'grid', placeItems: 'center', border: '2px solid #0A0A0F',
          }}>{necitite > 9 ? '9+' : necitite}</span>
        )}
      </button>

      {open && (
        <div style={{
          position: 'absolute', top: 46, right: 0, width: 360, maxWidth: 'calc(100vw - 32px)',
          maxHeight: 440, overflowY: 'auto', zIndex: 300,
          background: '#0d0d12', border: '.5px solid var(--line)', borderRadius: 12,
          boxShadow: '0 12px 40px rgba(0,0,0,.5)',
        }}>
          <div style={{
            display: 'flex', justifyContent: 'space-between', alignItems: 'center',
            padding: '14px 16px', borderBottom: '.5px solid var(--line)', position: 'sticky', top: 0,
            background: '#0d0d12', zIndex: 1,
          }}>
            <span style={{ fontSize: 13, fontWeight: 600 }}>Notificări</span>
            {necitite > 0 && (
              <button type="button"
                onClick={() => marcheazaCitite(items.filter(n => !n.is_read).map(n => n.id))}
                style={{ background: 'transparent', border: 'none', color: 'var(--accent-1)', fontSize: 12, cursor: 'pointer', padding: 0 }}>
                Marchează toate citite
              </button>
            )}
          </div>

          {items.length === 0 ? (
            <div style={{ padding: '36px 20px', textAlign: 'center', color: 'var(--txt-3)', fontSize: 13, lineHeight: 1.6 }}>
              Nicio notificare.<br />
              <span style={{ fontSize: 12 }}>Apar aici când un coleg schimbă ceva la campaniile tale.</span>
            </div>
          ) : items.map(n => (
            <div key={n.id} onClick={() => deschide(n)}
              style={{
                display: 'flex', gap: 10, padding: '12px 16px', cursor: 'pointer',
                borderBottom: '.5px solid var(--line-soft)',
                background: n.is_read ? 'transparent' : 'rgba(82,242,15,.04)',
                transition: 'background .15s',
              }}
              onMouseEnter={e => e.currentTarget.style.background = 'rgba(255,255,255,.04)'}
              onMouseLeave={e => e.currentTarget.style.background = n.is_read ? 'transparent' : 'rgba(82,242,15,.04)'}
            >
              <span style={{ fontSize: 15, lineHeight: 1.3, flexShrink: 0 }}>{NOTIF_ICONS[n.kind] || '•'}</span>
              <div style={{ minWidth: 0, flex: 1 }}>
                <div style={{ fontSize: 13, color: 'var(--txt-0)', fontWeight: n.is_read ? 400 : 600, lineHeight: 1.4 }}>
                  {n.title}
                </div>
                {n.body && (
                  <div style={{ fontSize: 12, color: 'var(--txt-3)', marginTop: 2, lineHeight: 1.4 }}>{n.body}</div>
                )}
                <div style={{ fontSize: 11, color: 'var(--txt-3)', marginTop: 4 }}>
                  {n.actor_name ? n.actor_name + ' · ' : ''}{timpRelativ(n.created_at)}
                </div>
              </div>
              {!n.is_read && (
                <span style={{ width: 7, height: 7, borderRadius: 4, background: 'var(--accent-1)', flexShrink: 0, marginTop: 6 }} />
              )}
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

window.NotificationBell = NotificationBell;
