// =============================================================================
// COMPOSANTS RÉUTILISABLES — petits éléments d'UI
// =============================================================================

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

// === Icon ===
function Icon({ name, className = "", strokeWidth = 1.5 }) {
  const paths = ICON_PATHS[name];
  if (!paths) return null;
  return (
    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={strokeWidth} strokeLinecap="round" strokeLinejoin="round" className={className}>{paths}</svg>
  );
}

// === PhotoPicker ===
function PhotoPicker({ value, onChange, size = 'md' }) {
  const [busy, setBusy] = useState(false);
  const inputId = useMemo(() => 'photo-' + Math.random().toString(36).slice(2,8), []);
  const handleFile = async (e) => {
    const file = e.target.files && e.target.files[0];
    if (!file) return;
    setBusy(true);
    try {
      const dataUrl = await processImage(file);
      onChange(dataUrl);
    } catch (err) { console.error('photo error', err); }
    finally { setBusy(false); e.target.value = ''; }
  };
  const previewSize = size === 'sm' ? 'w-12 h-12' : 'w-20 h-20';
  return (
    <div>
      <input type="file" accept="image/*" id={inputId} onChange={handleFile} className="hidden" />
      {value ? (
        <div className="flex items-center gap-3">
          <img src={value} alt="" className={`${previewSize} rounded-lg object-cover bg-stone-100 border border-stone-200`} />
          <div className="flex flex-col gap-1.5">
            <label htmlFor={inputId} className="text-xs bg-stone-100 hover:bg-stone-200 text-stone-700 px-3 py-1.5 rounded-md cursor-pointer text-center font-semibold">Changer</label>
            <button type="button" onClick={() => onChange(null)} className="text-xs text-rose-600 hover:text-rose-700 px-3 py-1 rounded-md font-semibold text-left">Retirer</button>
          </div>
        </div>
      ) : (
        <label htmlFor={inputId} className={`flex items-center justify-center gap-2 w-full bg-stone-50 hover:bg-stone-100 border border-dashed border-stone-300 rounded-lg py-3 text-sm text-stone-600 cursor-pointer ${busy ? 'opacity-50' : ''}`}>
          <Icon name="ImageIcon" className="w-4 h-4" /> {busy ? 'Traitement…' : 'Choisir une photo'}
        </label>
      )}
    </div>
  );
}


// === TabButton (nav du bas) ===
function TabButton({ active, onClick, iconName, label }) {
  return (
    <button onClick={onClick} className={`flex flex-col items-center gap-1 py-3 transition-colors ${active ? 'text-orange-600' : 'text-stone-500 hover:text-stone-800'}`}>
      <Icon name={iconName} className="w-5 h-5" strokeWidth={active ? 2.2 : 1.6} />
      <span className={`text-[10px] uppercase tracking-widest ${active ? 'font-bold' : 'font-semibold'}`}>{label}</span>
    </button>
  );
}

// === CategoryFilter (pills en haut de la liste de ventes) ===
function CategoryFilter({ drinks, activeCategory, setActiveCategory }) {
  const usedCats = useMemo(() => {
    const set = new Set();
    drinks.forEach(d => d.category && set.add(d.category));
    return CATEGORY_KEYS.filter(k => set.has(k));
  }, [drinks]);
  return (
    <div className="flex gap-2 overflow-x-auto scrollbar-thin pb-2 -mx-4 px-4">
      <button onClick={() => setActiveCategory('all')} className={`shrink-0 px-3 py-1.5 rounded-full text-xs font-bold uppercase tracking-wider transition-all ${
        activeCategory === 'all' ? 'bg-stone-900 text-white' : 'bg-white text-stone-700 border border-stone-200'
      }`}>Tout</button>
      {usedCats.map(key => {
        const cat = CATEGORIES[key];
        const active = activeCategory === key;
        return (
          <button key={key} onClick={() => setActiveCategory(key)} className={`shrink-0 px-3 py-1.5 rounded-full text-xs font-bold uppercase tracking-wider transition-all ${
            active ? 'bg-stone-900 text-white' : `${cat.bg} ${cat.text}`
          }`}>{cat.label}</button>
        );
      })}
    </div>
  );
}

// === HourlyChart (mini graphique stats) ===
function HourlyChart({ data }) {
  const max = Math.max(...data.map(d => d.revenue), 1);
  const W = 320, H = 140, padX = 16, padY = 24;
  const innerW = W - padX * 2, innerH = H - padY * 2;
  const slot = innerW / Math.max(data.length, 1);
  const barW = Math.max(slot * 0.65, 6);
  return (
    <svg viewBox={`0 0 ${W} ${H}`} className="w-full h-36">
      {data.map((d, i) => {
        const h = (d.revenue / max) * innerH;
        const x = padX + i * slot + (slot - barW) / 2;
        const y = H - padY - h;
        return (
          <g key={d.hour}>
            <rect x={x} y={y} width={barW} height={h} fill="#FF5A3D" rx="3" />
            <text x={x + barW / 2} y={H - 8} textAnchor="middle" fontSize="10" fill="#78716c" fontWeight="600">{d.hour}h</text>
            {h > 16 && <text x={x + barW / 2} y={y - 3} textAnchor="middle" fontSize="9" fill="#1c1917" fontFamily="ui-monospace, monospace" fontWeight="700">{Math.round(d.revenue)}</text>}
          </g>
        );
      })}
    </svg>
  );
}

// === StatCard ===
function StatCard({ label, value }) {
  return (
    <div className="bg-white border border-stone-200 rounded-xl p-3">
      <div className="text-[10px] uppercase tracking-widest text-stone-500 mb-1 font-bold">{label}</div>
      <div className="font-mono tabular-nums text-2xl text-stone-900 font-bold">{value}</div>
    </div>
  );
}

// === CategoryPicker (sélection catégorie dans formulaires) ===
function CategoryPicker({ value, onChange }) {
  return (
    <div className="flex flex-wrap gap-1.5">
      {CATEGORY_KEYS.map(key => {
        const cat = CATEGORIES[key];
        const selected = value === key;
        return (
          <button key={key} type="button" onClick={() => onChange(key)} className={`text-[10px] font-bold uppercase tracking-wider px-2.5 py-1 rounded-full transition-all ${
            selected ? 'bg-stone-900 text-white' : `${cat.bg} ${cat.text}`
          }`}>{cat.label}</button>
        );
      })}
    </div>
  );
}

// === IconPicker (sélection icône dans formulaires) ===
function IconPicker({ value, onChange }) {
  return (
    <div className="grid grid-cols-6 gap-1.5">
      {DRINK_ICON_NAMES.map(name => {
        const selected = value === name;
        return (
          <button key={name} type="button" onClick={() => onChange(name)} className={`aspect-square rounded-lg flex items-center justify-center transition-all ${selected ? 'bg-stone-900 text-white' : 'bg-stone-100 text-stone-600 hover:bg-stone-200'}`}>
            <Icon name={name} className="w-4 h-4" strokeWidth={selected ? 2 : 1.5} />
          </button>
        );
      })}
    </div>
  );
}

// === ConfirmModal — boîte de dialogue de confirmation réutilisable ===
function ConfirmModal({ open, title, body, confirmLabel, confirmVariant, onConfirm, onCancel }) {
  if (!open) return null;
  const danger = confirmVariant === 'danger';
  return (
    <div className="fixed inset-0 z-50 flex items-end sm:items-center justify-center bg-stone-900/40 backdrop-blur-sm" onClick={onCancel}>
      <div className="bg-white border border-stone-200 rounded-t-2xl sm:rounded-2xl p-5 w-full sm:max-w-sm shadow-xl slide-up" onClick={e => e.stopPropagation()}>
        <h3 className="font-display font-bold text-lg text-stone-900 mb-1.5 leading-tight">{title}</h3>
        {body && <p className="text-sm text-stone-600 leading-relaxed mb-4">{body}</p>}
        <div className="grid grid-cols-2 gap-2">
          <button onClick={onCancel} className="bg-stone-100 hover:bg-stone-200 text-stone-700 font-bold py-3 rounded-lg text-sm">
            Annuler
          </button>
          <button onClick={onConfirm} className={`text-white font-bold py-3 rounded-lg text-sm ${danger ? 'bg-rose-500 hover:bg-rose-600' : 'bg-stone-900 hover:bg-stone-700'}`}>
            {confirmLabel || 'Confirmer'}
          </button>
        </div>
      </div>
    </div>
  );
}
