'use client';
import { useEffect, useRef, useState } from 'react';
import { Icon } from '@/lib/icons';
import { useGo } from '@/lib/router';
import { useAuth } from './AuthProvider';

const TYPE_ICON: Record<string, string> = {
  message: 'message',
  reservation: 'calendar',
  review: 'star',
};

export function NotificationsBell({ dark }: { dark?: boolean }) {
  const { notifications, notifUnread, markNotifsRead } = useAuth();
  const { go } = useGo();
  const [open, setOpen] = useState(false);
  const ref = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!open) return;
    const onDoc = (e: MouseEvent) => {
      if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false);
    };
    document.addEventListener('mousedown', onDoc);
    return () => document.removeEventListener('mousedown', onDoc);
  }, [open]);

  const toggle = () => {
    const next = !open;
    setOpen(next);
    if (next && notifUnread > 0) markNotifsRead();
  };

  const openItem = (link: string) => {
    setOpen(false);
    if (!link) return;
    // Convert an app path back into a go() call.
    const [path, query] = link.split('?');
    const params: Record<string, string> = {};
    if (query) for (const kv of query.split('&')) { const [k, v] = kv.split('='); params[k] = decodeURIComponent(v || ''); }
    if (path === '/compte') go('compte', params);
    else if (path === '/pro') go('pro');
    else if (path.startsWith('/commerce/')) go('detail', { id: path.split('/')[2] });
    else if (path.startsWith('/annonces/')) go('annonce', { id: path.split('/')[2] });
    else window.location.href = link;
  };

  return (
    <div ref={ref} style={{ position: 'relative' }}>
      <button
        className="btn btn-ghost btn-sm bell-btn"
        style={{ padding: '9px 11px', position: 'relative', ...(dark ? { background: 'transparent' } : {}) }}
        onClick={toggle}
        aria-label="Notifications"
      >
        <Icon name="bell" size={17} />
        {notifUnread > 0 && (
          <span className="notif-badge">{notifUnread > 9 ? '9+' : notifUnread}</span>
        )}
      </button>
      {open && (
        <div className="notif-pop">
          <div className="notif-pop-head">
            <span style={{ fontWeight: 700, fontSize: 14 }}>Notifications</span>
          </div>
          <div className="notif-pop-list">
            {notifications.length === 0 ? (
              <div style={{ padding: '28px 16px', textAlign: 'center' }}>
                <Icon name="bell" size={26} stroke={1.5} style={{ color: 'var(--faint)' }} />
                <p className="small" style={{ marginTop: 8 }}>Aucune notification</p>
              </div>
            ) : (
              notifications.map((n) => (
                <div
                  key={n.id}
                  className={'notif-item ' + (n.read ? '' : 'unread')}
                  onClick={() => openItem(n.link)}
                >
                  <div className="notif-ic"><Icon name={TYPE_ICON[n.type] || 'bell'} size={16} stroke={1.8} /></div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontWeight: 600, fontSize: 13.5 }}>{n.title}</div>
                    {n.body && <div className="small" style={{ marginTop: 2 }}>{n.body}</div>}
                    <div className="tiny" style={{ marginTop: 3, color: 'var(--faint)' }}>{n.when}</div>
                  </div>
                  {!n.read && <span className="notif-dot" />}
                </div>
              ))
            )}
          </div>
        </div>
      )}
    </div>
  );
}
