// ============================================================================
// Restaurateur Pro - Shared components (notifications, sheet, etc.)
// ============================================================================

const { useState, useEffect, useRef, useCallback, useMemo } = React;

// ──────────────── Notifications ────────────────
const useNotifications = () => {
  const showNotification = useCallback((message, type = 'info') => {
    const existing = document.querySelectorAll('.notification');
    existing.forEach((n, i) => {
      const top = 20 + ((i + 1) * 78);
      n.style.top = `${top}px`;
    });

    const notification = document.createElement('div');
    notification.className = `notification ${type}`;
    const iconSvg = type === 'success'
      ? '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>'
      : type === 'error'
        ? '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="15" y1="9" x2="9" y2="15"/><line x1="9" y1="9" x2="15" y2="15"/></svg>'
        : '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></svg>';
    notification.innerHTML = `${iconSvg}<div class="notification-content">${message}</div>`;

    document.body.appendChild(notification);

    const remove = () => {
      if (notification.classList.contains('slide-out')) return;
      notification.classList.add('slide-out');
      setTimeout(() => notification.remove(), 300);
    };

    setTimeout(remove, 4000);
    notification.addEventListener('click', remove);
  }, []);

  return useMemo(() => ({
    success: (m) => showNotification(m, 'success'),
    error: (m) => showNotification(m, 'error'),
    info: (m) => showNotification(m, 'info'),
  }), [showNotification]);
};

// ──────────────── Bottom Sheet ────────────────
function Sheet({ open, onClose, title, children }) {
  const [visible, setVisible] = useState(false);

  useEffect(() => {
    if (open) {
      requestAnimationFrame(() => setVisible(true));
    } else {
      setVisible(false);
    }
  }, [open]);

  if (!open) return null;

  return (
    <div
      className={`sheet-overlay ${visible ? 'visible' : ''}`}
      onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}
    >
      <div className="sheet">
        <div className="sheet-handle" />
        {title && <h3 className="sheet-title">{title}</h3>}
        {children}
      </div>
    </div>
  );
}

// ──────────────── Spinner ────────────────
function Spinner({ size = 'md', center = false }) {
  const cls = size === 'sm' ? 'spinner spinner-sm' : 'spinner';
  if (center) {
    return (
      <div className="flex items-center justify-center py-12">
        <div className={cls} />
      </div>
    );
  }
  return <div className={cls} />;
}

// ──────────────── Empty State ────────────────
function EmptyState({ icon: Icon, title, description }) {
  return (
    <div className="empty-state animate-fade-in-up">
      <div className="empty-icon">{Icon ? <Icon /> : null}</div>
      <div className="empty-title">{title}</div>
      {description && <div className="empty-desc">{description}</div>}
    </div>
  );
}

// ──────────────── Stat Card ────────────────
function StatCard({ icon: Icon, color = 'teal', value, label, onClick }) {
  return (
    <div className="stat-card stagger-item" onClick={onClick} style={{ cursor: onClick ? 'pointer' : 'default' }}>
      <div className={`stat-icon ${color}`}><Icon /></div>
      <div>
        <div className="stat-value">{value}</div>
        <div className="stat-label">{label}</div>
      </div>
    </div>
  );
}

// ──────────────── Status Badge ────────────────
const STATUS_LABELS = {
  pending: 'En attente',
  confirmed: 'Confirmée',
  cancelled: 'Annulée',
  no_show: 'No-show',
  completed: 'Terminée',
};
function StatusBadge({ status }) {
  return <span className={`status-badge ${status}`}>{STATUS_LABELS[status] || status}</span>;
}

// ──────────────── Top Header ────────────────
function AppHeader({ title, subtitle, action, onBack }) {
  return (
    <header className="app-header">
      {onBack && (
        <button className="btn-icon" onClick={onBack} aria-label="Retour">
          <Icons.ChevronLeft size={20} />
        </button>
      )}
      <div className="flex-1 min-w-0">
        <div className="app-header-title truncate">{title}</div>
        {subtitle && <div className="app-header-sub truncate">{subtitle}</div>}
      </div>
      {action}
    </header>
  );
}

// ──────────────── Bottom Nav ────────────────
function BottomNav({ current, onChange, pendingCount }) {
  const items = [
    { id: 'dashboard', label: 'Accueil', icon: Icons.Home },
    { id: 'bookings', label: 'Réservations', icon: Icons.Inbox, badge: pendingCount > 0 ? pendingCount : null },
    { id: 'calendar', label: 'Horaires', icon: Icons.Calendar },
    { id: 'profile', label: 'Profil', icon: Icons.User },
  ];
  return (
    <nav className="bottom-nav">
      <div className="bottom-nav-inner">
        {items.map((it) => {
          const Icon = it.icon;
          return (
            <button
              key={it.id}
              className={`nav-item ${current === it.id ? 'active' : ''}`}
              onClick={() => onChange(it.id)}
            >
              <Icon size={22} />
              <span>{it.label}</span>
              {it.badge && <span className="nav-badge">{it.badge > 9 ? '9+' : it.badge}</span>}
            </button>
          );
        })}
      </div>
    </nav>
  );
}

// ──────────────── Date Helpers ────────────────
const JOURS = ['dimanche','lundi','mardi','mercredi','jeudi','vendredi','samedi'];
const JOURS_SHORT = ['Dim','Lun','Mar','Mer','Jeu','Ven','Sam'];
const MOIS = ['janvier','février','mars','avril','mai','juin','juillet','août','septembre','octobre','novembre','décembre'];

function todayStr() {
  const d = new Date();
  return `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`;
}

function formatDate(dateStr) {
  if (!dateStr) return '';
  const d = new Date(dateStr + 'T12:00:00');
  return `${JOURS[d.getDay()]} ${d.getDate()} ${MOIS[d.getMonth()]}`;
}

function formatDateShort(dateStr) {
  if (!dateStr) return '';
  const d = new Date(dateStr + 'T12:00:00');
  return `${String(d.getDate()).padStart(2,'0')}/${String(d.getMonth()+1).padStart(2,'0')}`;
}

function formatRelativeDate(dateStr) {
  if (!dateStr) return '';
  const today = todayStr();
  if (dateStr === today) return "Aujourd'hui";
  const d = new Date(dateStr + 'T12:00:00');
  const t = new Date(today + 'T12:00:00');
  const diff = Math.round((d - t) / (24*60*60*1000));
  if (diff === 1) return 'Demain';
  if (diff === -1) return 'Hier';
  return formatDate(dateStr);
}

function getInitials(name) {
  if (!name) return '?';
  return name.split(' ').filter(Boolean).slice(0, 2).map(s => s[0].toUpperCase()).join('');
}

window.useNotifications = useNotifications;
window.Sheet = Sheet;
window.Spinner = Spinner;
window.EmptyState = EmptyState;
window.StatCard = StatCard;
window.StatusBadge = StatusBadge;
window.AppHeader = AppHeader;
window.BottomNav = BottomNav;
window.todayStr = todayStr;
window.formatDate = formatDate;
window.formatDateShort = formatDateShort;
window.formatRelativeDate = formatRelativeDate;
window.getInitials = getInitials;
window.JOURS = JOURS;
window.JOURS_SHORT = JOURS_SHORT;
window.MOIS = MOIS;
window.STATUS_LABELS = STATUS_LABELS;
