// ============================================================================
// Restaurateur Pro - Views (Login, Dashboard, Bookings, Calendar, Profile)
// ============================================================================

// ════════════════════════════════════════════
// LOGIN VIEW
// ════════════════════════════════════════════

function LoginView({ onLoggedIn }) {
  const [step, setStep] = useState('email');
  const [email, setEmail] = useState('');
  const [code, setCode] = useState(['', '', '', '', '', '']);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const codeRefs = useRef([]);
  const notify = useNotifications();

  async function submitEmail(e) {
    e.preventDefault();
    if (!email.trim()) return;
    setError('');
    setLoading(true);
    try {
      const res = await RchAPI.requestCode(email.trim().toLowerCase());
      if (res?.error) {
        setError(res.error);
      } else {
        setStep('code');
        setTimeout(() => codeRefs.current[0]?.focus(), 200);
      }
    } catch (err) {
      setError(err.message || 'Erreur');
    }
    setLoading(false);
  }

  function handleCodeChange(idx, value) {
    const cleaned = value.replace(/\D/g, '');
    if (cleaned.length > 1) {
      // paste
      const digits = cleaned.slice(0, 6).split('');
      const newCode = [...code];
      digits.forEach((d, i) => { if (idx + i < 6) newCode[idx + i] = d; });
      setCode(newCode);
      const lastFilled = Math.min(idx + digits.length, 5);
      codeRefs.current[lastFilled]?.focus();
      if (newCode.every(d => d) && newCode.join('').length === 6) {
        submitCode(newCode.join(''));
      }
      return;
    }
    const newCode = [...code];
    newCode[idx] = cleaned;
    setCode(newCode);
    if (cleaned && idx < 5) codeRefs.current[idx + 1]?.focus();
    if (newCode.every(d => d) && newCode.join('').length === 6) {
      submitCode(newCode.join(''));
    }
  }

  function handleCodeKey(idx, e) {
    if (e.key === 'Backspace' && !code[idx] && idx > 0) {
      codeRefs.current[idx - 1]?.focus();
    }
  }

  async function submitCode(codeStr) {
    setError('');
    setLoading(true);
    try {
      const res = await RchAPI.verifyCode(email.trim().toLowerCase(), codeStr);
      if (res?.success && res?.session_token) {
        notify.success('Connexion réussie');
        onLoggedIn();
      } else {
        setError(res?.error || 'Code invalide');
        setCode(['', '', '', '', '', '']);
        codeRefs.current[0]?.focus();
      }
    } catch (err) {
      setError(err.message || 'Code invalide');
      setCode(['', '', '', '', '', '']);
      codeRefs.current[0]?.focus();
    }
    setLoading(false);
  }

  return (
    <div className="login-screen">
      <div className="login-hero">
        <div className="login-logo">
          <svg viewBox="0 0 100 100" fill="none">
            <rect x="20" y="25" width="60" height="50" rx="6" fill="white"/>
            <line x1="20" y1="40" x2="80" y2="40" stroke="#14B8A6" strokeWidth="3"/>
            <circle cx="35" cy="55" r="4" fill="#14B8A6"/>
            <circle cx="50" cy="55" r="4" fill="#14B8A6"/>
            <circle cx="65" cy="55" r="4" fill="#14B8A6"/>
          </svg>
        </div>
        <div>
          <h1 className="login-title">Restaurateur Pro</h1>
          <p className="login-subtitle">L'app des restaurateurs indépendants suisses. Vos réservations, votre calendrier, votre liberté.</p>
        </div>
      </div>

      <div className="login-form">
        {step === 'email' ? (
          <form onSubmit={submitEmail}>
            <label className="form-label">Adresse email du restaurant</label>
            <input
              type="email"
              className="input-field"
              value={email}
              onChange={e => setEmail(e.target.value)}
              placeholder="restaurant@exemple.ch"
              autoFocus
              required
            />
            {error && <div className="text-red-500 text-sm mt-2">{error}</div>}
            <button type="submit" className="btn-primary w-full mt-4" disabled={loading || !email.trim()}>
              {loading ? <Spinner size="sm" /> : <Icons.Send size={18} />}
              {loading ? 'Envoi…' : 'Recevoir mon code'}
            </button>
            <p className="text-xs text-center text-secondary mt-3">Vous recevrez un code à 6 chiffres par email.</p>
          </form>
        ) : (
          <div>
            <button
              className="text-rch-teal-600 text-sm font-semibold flex items-center gap-1 mb-3"
              onClick={() => { setStep('email'); setCode(['','','','','','']); setError(''); }}
            >
              <Icons.ChevronLeft size={16} /> Modifier l'email
            </button>
            <label className="form-label">Code reçu par email</label>
            <p className="text-xs text-secondary mb-2">Envoyé à <strong className="text-slate-900">{email}</strong></p>
            <div className="code-inputs">
              {code.map((d, i) => (
                <input
                  key={i}
                  ref={el => codeRefs.current[i] = el}
                  className="code-digit"
                  type="tel"
                  inputMode="numeric"
                  maxLength="6"
                  value={d}
                  onChange={e => handleCodeChange(i, e.target.value)}
                  onKeyDown={e => handleCodeKey(i, e)}
                  disabled={loading}
                />
              ))}
            </div>
            {error && <div className="text-red-500 text-sm text-center">{error}</div>}
            {loading && <div className="flex justify-center mt-3"><Spinner size="sm" /></div>}
            <p className="text-xs text-center text-secondary mt-4">Code valable 15 minutes.</p>
          </div>
        )}
      </div>
    </div>
  );
}

// ════════════════════════════════════════════
// DASHBOARD VIEW
// ════════════════════════════════════════════

function DashboardView({ restaurant, onNavigate, onRefresh, refreshKey }) {
  const [bookings, setBookings] = useState([]);
  const [stats, setStats] = useState({ today: 0, pending: 0, confirmed: 0, week: 0 });
  const [loading, setLoading] = useState(true);
  const notify = useNotifications();

  useEffect(() => { load(); }, [refreshKey]);

  async function load() {
    setLoading(true);
    try {
      const today = todayStr();
      const [todayData, pendingData, allData] = await Promise.all([
        RchAPI.getBookings({ date: today }),
        RchAPI.getBookings({ status: 'pending' }),
        RchAPI.getBookings(),
      ]);
      const all = allData.bookings || [];
      const today7 = new Date(); today7.setDate(today7.getDate() + 7);
      const t7str = `${today7.getFullYear()}-${String(today7.getMonth()+1).padStart(2,'0')}-${String(today7.getDate()).padStart(2,'0')}`;

      setBookings((todayData.bookings || []).slice(0, 5));
      setStats({
        today: (todayData.bookings || []).length,
        pending: (pendingData.bookings || []).length,
        confirmed: all.filter(b => b.status === 'confirmed').length,
        week: all.filter(b => b.booking_date >= today && b.booking_date <= t7str).length,
      });
    } catch (e) {
      notify.error('Erreur de chargement');
    }
    setLoading(false);
  }

  if (loading) return <Spinner center />;

  const todayBookings = bookings.filter(b => b.status !== 'cancelled');

  return (
    <div className="animate-fade-in">
      <div className="mb-5">
        <p className="text-sm text-secondary mb-1">Bonjour 👋</p>
        <h1 className="text-2xl font-extrabold tracking-tight">{restaurant?.name}</h1>
        <p className="text-sm text-secondary mt-1">{formatDate(todayStr())}</p>
      </div>

      <div className="grid grid-cols-2 gap-3 mb-6">
        <StatCard icon={Icons.CalendarDay} color="teal" value={stats.today} label="Aujourd'hui" onClick={() => onNavigate('bookings')} />
        <StatCard icon={Icons.Clock} color="amber" value={stats.pending} label="En attente" onClick={() => onNavigate('bookings')} />
        <StatCard icon={Icons.CheckCircle} color="green" value={stats.confirmed} label="Confirmées" />
        <StatCard icon={Icons.TrendingUp} color="blue" value={stats.week} label="Cette semaine" />
      </div>

      <div className="flex items-center justify-between mb-3 px-1">
        <h2 className="section-title m-0">Aujourd'hui</h2>
        <button className="text-xs font-bold text-rch-teal-600" onClick={() => onNavigate('bookings')}>
          Tout voir →
        </button>
      </div>

      {todayBookings.length === 0 ? (
        <EmptyState
          icon={Icons.Sun}
          title="Pas de réservation aujourd'hui"
          description="Profitez de cette journée ! Les nouvelles demandes apparaîtront ici."
        />
      ) : (
        <div className="flex flex-col gap-2.5">
          {todayBookings.map((b) => (
            <BookingCard key={b.token} booking={b} onChange={load} />
          ))}
        </div>
      )}
    </div>
  );
}

// ════════════════════════════════════════════
// BOOKINGS VIEW
// ════════════════════════════════════════════

function BookingsView({ restaurant, refreshKey, onChange }) {
  const [bookings, setBookings] = useState([]);
  const [filter, setFilter] = useState('today');
  const [loading, setLoading] = useState(true);
  const notify = useNotifications();
  const [counts, setCounts] = useState({ today: 0, pending: 0, upcoming: 0, all: 0 });

  useEffect(() => { load(); }, [refreshKey]);

  async function load() {
    setLoading(true);
    try {
      const all = (await RchAPI.getBookings()).bookings || [];
      const today = todayStr();
      setBookings(all);
      setCounts({
        today: all.filter(b => b.booking_date === today && b.status !== 'cancelled').length,
        pending: all.filter(b => b.status === 'pending').length,
        upcoming: all.filter(b => b.booking_date > today && b.status !== 'cancelled').length,
        all: all.length,
      });
    } catch (e) {
      notify.error('Erreur de chargement');
    }
    setLoading(false);
  }

  const today = todayStr();
  const filtered = bookings.filter(b => {
    if (filter === 'today') return b.booking_date === today && b.status !== 'cancelled';
    if (filter === 'pending') return b.status === 'pending';
    if (filter === 'upcoming') return b.booking_date > today && b.status !== 'cancelled';
    return true;
  });

  return (
    <div className="animate-fade-in">
      <div className="tabs">
        <button className={`tab-pill ${filter === 'today' ? 'active' : ''}`} onClick={() => setFilter('today')}>
          Aujourd'hui <span className="tab-count">{counts.today}</span>
        </button>
        <button className={`tab-pill ${filter === 'pending' ? 'active' : ''}`} onClick={() => setFilter('pending')}>
          À traiter <span className="tab-count">{counts.pending}</span>
        </button>
        <button className={`tab-pill ${filter === 'upcoming' ? 'active' : ''}`} onClick={() => setFilter('upcoming')}>
          À venir <span className="tab-count">{counts.upcoming}</span>
        </button>
        <button className={`tab-pill ${filter === 'all' ? 'active' : ''}`} onClick={() => setFilter('all')}>
          Toutes <span className="tab-count">{counts.all}</span>
        </button>
      </div>

      {loading ? (
        <Spinner center />
      ) : filtered.length === 0 ? (
        <EmptyState icon={Icons.Inbox} title="Aucune réservation" description="Aucune réservation dans cette catégorie." />
      ) : (
        <div className="flex flex-col gap-2.5">
          {filtered.map(b => (
            <BookingCard key={b.token} booking={b} onChange={load} showDate />
          ))}
        </div>
      )}
    </div>
  );
}

// ════════════════════════════════════════════
// BOOKING CARD
// ════════════════════════════════════════════

function BookingCard({ booking, onChange, showDate = false }) {
  const [acting, setActing] = useState(false);
  const [showDetails, setShowDetails] = useState(false);
  const notify = useNotifications();

  async function updateStatus(status, label) {
    setActing(true);
    try {
      await RchAPI.updateBookingStatus(booking.token, status);
      notify.success(label);
      if (onChange) onChange();
    } catch (e) {
      notify.error('Erreur: ' + e.message);
    }
    setActing(false);
  }

  return (
    <>
      <div className={`booking-card ${booking.status} stagger-item`}>
        <div className="booking-header" onClick={() => setShowDetails(true)}>
          <div className="booking-avatar">{getInitials(booking.guest_name)}</div>
          <div className="flex-1 min-w-0">
            <div className="booking-name truncate">{booking.guest_name}</div>
            <div className="booking-contact truncate">{booking.guest_email}</div>
          </div>
          <StatusBadge status={booking.status} />
        </div>

        <div className="booking-meta">
          <span className="booking-meta-pill">
            <Icons.Clock size={14} />
            {booking.booking_time}
          </span>
          {showDate && (
            <span className="booking-meta-pill">
              <Icons.Calendar size={14} />
              {formatRelativeDate(booking.booking_date)}
            </span>
          )}
          <span className="booking-meta-pill">
            <Icons.Users size={14} />
            {booking.party_size || 1}
          </span>
          {booking.discount_percent > 0 && (
            <span className="booking-meta-pill discount">
              <Icons.Percent size={14} />
              -{booking.discount_percent}%
            </span>
          )}
        </div>

        {booking.notes && (
          <div className="booking-notes">📝 {booking.notes}</div>
        )}

        {booking.status === 'pending' && (
          <div className="booking-actions">
            <button className="btn-success" onClick={() => updateStatus('confirmed', 'Réservation confirmée')} disabled={acting}>
              <Icons.Check size={16} /> Confirmer
            </button>
            <button className="btn-danger" onClick={() => updateStatus('cancelled', 'Réservation refusée')} disabled={acting}>
              <Icons.X size={16} /> Refuser
            </button>
          </div>
        )}
      </div>

      <Sheet open={showDetails} onClose={() => setShowDetails(false)} title="Détails de la réservation">
        <div className="flex items-center gap-3 mb-4">
          <div className="booking-avatar" style={{ width: 56, height: 56, fontSize: 18 }}>
            {getInitials(booking.guest_name)}
          </div>
          <div className="flex-1 min-w-0">
            <div className="font-bold text-lg truncate">{booking.guest_name}</div>
            <StatusBadge status={booking.status} />
          </div>
        </div>

        <div className="grid grid-cols-2 gap-2.5 mb-3">
          <DetailField icon={Icons.Calendar} label="Date" value={formatDate(booking.booking_date)} />
          <DetailField icon={Icons.Clock} label="Heure" value={booking.booking_time} mono />
          <DetailField icon={Icons.Users} label="Personnes" value={booking.party_size || 1} />
          {booking.discount_percent > 0 && (
            <DetailField icon={Icons.Percent} label="Rabais" value={`-${booking.discount_percent}%`} highlight />
          )}
          <DetailField icon={Icons.Mail} label="Email" value={booking.guest_email} small />
          <DetailField icon={Icons.Phone} label="Téléphone" value={booking.guest_phone || '—'} small />
        </div>

        {booking.notes && (
          <div className="booking-notes mb-3">📝 {booking.notes}</div>
        )}

        <div className="flex flex-col gap-2 mt-4">
          {booking.status === 'pending' && (
            <button className="btn-primary" onClick={() => updateStatus('confirmed', 'Réservation confirmée')}>
              <Icons.Check size={18} /> Confirmer la réservation
            </button>
          )}
          {booking.status === 'confirmed' && (
            <button className="btn-secondary" onClick={() => updateStatus('no_show', 'Marqué comme no-show')}>
              <Icons.UserSlash size={18} /> Marquer no-show
            </button>
          )}
          {booking.status !== 'cancelled' && (
            <button className="btn-danger" onClick={() => updateStatus('cancelled', 'Réservation annulée')}>
              <Icons.X size={18} /> Annuler
            </button>
          )}
          <button className="btn-secondary" onClick={() => setShowDetails(false)}>Fermer</button>
        </div>

        {booking.guest_phone && (
          <a href={`tel:${booking.guest_phone}`} className="btn-secondary mt-2 w-full">
            <Icons.Phone size={16} /> Appeler le client
          </a>
        )}

        <p className="text-xs text-muted text-center mt-3">Réf : {booking.token}</p>
      </Sheet>
    </>
  );
}

function DetailField({ icon: Icon, label, value, mono, small, highlight }) {
  return (
    <div className={`rounded-xl p-2.5 ${highlight ? 'bg-emerald-50' : 'bg-slate-50'}`}>
      <div className="flex items-center gap-1.5 text-xs font-semibold text-slate-500 mb-0.5">
        <Icon size={12} /> {label}
      </div>
      <div className={`font-bold truncate ${mono ? 'font-mono' : ''} ${small ? 'text-sm' : 'text-base'} ${highlight ? 'text-emerald-700' : 'text-slate-900'}`}>
        {value}
      </div>
    </div>
  );
}

// ════════════════════════════════════════════
// CALENDAR VIEW
// ════════════════════════════════════════════

function CalendarView({ refreshKey }) {
  const [config, setConfig] = useState([]);
  const [loading, setLoading] = useState(true);
  const [savingDay, setSavingDay] = useState(null);
  const notify = useNotifications();

  useEffect(() => { load(); }, [refreshKey]);

  async function load() {
    setLoading(true);
    try {
      const res = await RchAPI.getConfig();
      setConfig(res.weekConfig || []);
    } catch (e) {
      notify.error('Erreur de chargement');
    }
    setLoading(false);
  }

  function update(dow, field, value) {
    setConfig(prev => prev.map(c => c.day_of_week === dow ? { ...c, [field]: value } : c));
  }

  async function save(dow) {
    const day = config.find(c => c.day_of_week === dow);
    setSavingDay(dow);
    try {
      await RchAPI.updateDayConfig(dow, {
        is_open: day.is_open,
        discount_percent: day.discount_percent,
        open_time: day.open_time,
        close_time: day.close_time,
        slot_duration_min: day.slot_duration_min,
        max_bookings_per_slot: day.max_bookings_per_slot,
      });
      notify.success(`${JOURS[dow]} mis à jour`);
    } catch (e) {
      notify.error('Erreur: ' + e.message);
    }
    setSavingDay(null);
  }

  if (loading) return <Spinner center />;

  return (
    <div className="animate-fade-in">
      <p className="text-sm text-secondary mb-4 px-1">
        Configurez vos horaires et rabais pour chaque jour de la semaine.
      </p>

      {config.sort((a,b) => a.day_of_week - b.day_of_week).map(day => (
        <div key={day.day_of_week} className="day-card stagger-item">
          <div className="day-card-header">
            <div className="flex items-center gap-2.5 flex-1">
              <div
                className={`toggle-switch ${day.is_open ? 'active' : ''}`}
                onClick={() => update(day.day_of_week, 'is_open', day.is_open ? 0 : 1)}
              />
              <div className={`day-name ${!day.is_open ? 'closed' : ''}`}>
                {JOURS[day.day_of_week]}
              </div>
            </div>
            <button
              className="btn-icon"
              onClick={() => save(day.day_of_week)}
              disabled={savingDay === day.day_of_week}
              title="Enregistrer"
            >
              {savingDay === day.day_of_week ? <Spinner size="sm" /> : <Icons.Save size={18} />}
            </button>
          </div>

          {day.is_open && (
            <div className="day-fields">
              <div className="day-field">
                <label>Ouverture</label>
                <input type="time" value={day.open_time || '09:00'} onChange={e => update(day.day_of_week, 'open_time', e.target.value)} />
              </div>
              <div className="day-field">
                <label>Fermeture</label>
                <input type="time" value={day.close_time || '22:00'} onChange={e => update(day.day_of_week, 'close_time', e.target.value)} />
              </div>
              <div className="day-field">
                <label>Rabais (%)</label>
                <input type="number" min="0" max="100" value={day.discount_percent || 0} onChange={e => update(day.day_of_week, 'discount_percent', parseInt(e.target.value) || 0)} />
              </div>
              <div className="day-field">
                <label>Durée (min)</label>
                <input type="number" min="15" max="240" step="15" value={day.slot_duration_min || 60} onChange={e => update(day.day_of_week, 'slot_duration_min', parseInt(e.target.value) || 60)} />
              </div>
              <div className="day-field" style={{ gridColumn: '1 / -1' }}>
                <label>Couverts max par créneau</label>
                <input type="number" min="1" max="100" value={day.max_bookings_per_slot || 5} onChange={e => update(day.day_of_week, 'max_bookings_per_slot', parseInt(e.target.value) || 5)} />
              </div>
            </div>
          )}
        </div>
      ))}
    </div>
  );
}

// ════════════════════════════════════════════
// PROFILE VIEW
// ════════════════════════════════════════════

function ProfileView({ restaurant, onLogout, onUpdate }) {
  const [showProfileEdit, setShowProfileEdit] = useState(false);
  const [showLink, setShowLink] = useState(false);
  const [showWidget, setShowWidget] = useState(false);
  const notify = useNotifications();

  const bookingLink = `https://app.restaurateur.ch/${restaurant?.slug || ''}`;

  function copyLink() {
    navigator.clipboard.writeText(bookingLink);
    notify.success('Lien copié !');
  }

  function copyWidgetCode() {
    const code = `<script src="https://widget.restaurateur.ch/assets/js/restaurateur-widget.js"></script>\n<script>RestaurateurWidget.init({token:'${restaurant?.admin_token}'});</script>`;
    navigator.clipboard.writeText(code);
    notify.success('Code widget copié !');
  }

  return (
    <div className="animate-fade-in">
      <div className="profile-card">
        <div className="flex items-center gap-3">
          <div className="w-14 h-14 rounded-2xl bg-white/20 backdrop-blur flex items-center justify-center text-2xl font-extrabold">
            {(restaurant?.name || '?').charAt(0).toUpperCase()}
          </div>
          <div className="flex-1 min-w-0">
            <div className="profile-name truncate">{restaurant?.name}</div>
            <div className="profile-slug">restaurateur.ch/{restaurant?.slug}</div>
          </div>
        </div>
      </div>

      <h2 className="section-title">Mon restaurant</h2>
      <div className="rounded-2xl overflow-hidden mb-6 stagger-item">
        <button className="list-item w-full text-left" onClick={() => setShowProfileEdit(true)}>
          <div className="list-item-icon"><Icons.Edit /></div>
          <div className="list-item-content">
            <div className="list-item-title">Informations</div>
            <div className="list-item-sub">Nom, contact, adresse, couleur</div>
          </div>
          <Icons.ChevronRight size={20} className="list-item-chevron" />
        </button>
        <button className="list-item w-full text-left" onClick={() => setShowLink(true)}>
          <div className="list-item-icon"><Icons.Link /></div>
          <div className="list-item-content">
            <div className="list-item-title">Lien de réservation</div>
            <div className="list-item-sub truncate">{bookingLink}</div>
          </div>
          <Icons.ChevronRight size={20} className="list-item-chevron" />
        </button>
        <button className="list-item w-full text-left" onClick={() => setShowWidget(true)}>
          <div className="list-item-icon"><Icons.Code /></div>
          <div className="list-item-content">
            <div className="list-item-title">Widget pour mon site</div>
            <div className="list-item-sub">Intégration JavaScript</div>
          </div>
          <Icons.ChevronRight size={20} className="list-item-chevron" />
        </button>
      </div>

      <h2 className="section-title">Compte</h2>
      <div className="rounded-2xl overflow-hidden mb-6 stagger-item">
        <a href={`mailto:contact@restaurateur.ch?subject=Support%20${encodeURIComponent(restaurant?.name || '')}`} className="list-item">
          <div className="list-item-icon"><Icons.Mail /></div>
          <div className="list-item-content">
            <div className="list-item-title">Contacter le support</div>
            <div className="list-item-sub">contact@restaurateur.ch</div>
          </div>
          <Icons.ChevronRight size={20} className="list-item-chevron" />
        </a>
        <a href="https://admin.restaurateur.ch" target="_blank" rel="noopener" className="list-item">
          <div className="list-item-icon"><Icons.Globe /></div>
          <div className="list-item-content">
            <div className="list-item-title">Admin web</div>
            <div className="list-item-sub">Accès depuis ordinateur</div>
          </div>
          <Icons.ChevronRight size={20} className="list-item-chevron" />
        </a>
        <button className="list-item w-full text-left" onClick={onLogout}>
          <div className="list-item-icon" style={{ background: 'rgba(239,68,68,0.1)', color: '#DC2626' }}>
            <Icons.LogOut />
          </div>
          <div className="list-item-content">
            <div className="list-item-title" style={{ color: '#DC2626' }}>Se déconnecter</div>
          </div>
        </button>
      </div>

      <p className="text-xs text-center text-muted py-4">
        Restaurateur.ch • Version 1.0<br />
        Le circuit court de la restauration en Suisse 🇨🇭
      </p>

      <ProfileEditSheet open={showProfileEdit} onClose={() => setShowProfileEdit(false)} restaurant={restaurant} onUpdate={onUpdate} />
      <LinkSheet open={showLink} onClose={() => setShowLink(false)} link={bookingLink} onCopy={copyLink} />
      <WidgetSheet open={showWidget} onClose={() => setShowWidget(false)} restaurant={restaurant} onCopy={copyWidgetCode} />
    </div>
  );
}

function LinkSheet({ open, onClose, link, onCopy }) {
  return (
    <Sheet open={open} onClose={onClose} title="Lien de réservation">
      <p className="text-sm text-secondary mb-3">
        Partagez ce lien sur vos réseaux sociaux, votre site ou imprimez-le en QR code pour vos clients.
      </p>
      <div className="bg-slate-50 rounded-xl p-3 break-all font-mono text-sm mb-3 border border-slate-200">
        {link}
      </div>
      <div className="flex flex-col gap-2">
        <button className="btn-primary" onClick={onCopy}>
          <Icons.Copy size={18} /> Copier le lien
        </button>
        <a href={link} target="_blank" rel="noopener" className="btn-secondary">
          <Icons.Eye size={18} /> Aperçu
        </a>
      </div>
    </Sheet>
  );
}

function WidgetSheet({ open, onClose, restaurant, onCopy }) {
  const code = `<script src="https://widget.restaurateur.ch/assets/js/restaurateur-widget.js"></script>
<script>
  RestaurateurWidget.init({
    token: '${restaurant?.admin_token}',
  });
</script>

<button onclick="openWidgetTable()">Réserver</button>`;
  return (
    <Sheet open={open} onClose={onClose} title="Widget pour votre site web">
      <p className="text-sm text-secondary mb-3">
        Collez ce code dans votre site web pour ajouter un bouton de réservation.
      </p>
      <pre className="bg-slate-900 text-slate-100 rounded-xl p-3 overflow-x-auto text-xs leading-relaxed mb-3" style={{ fontFamily: "ui-monospace, monospace" }}>
        {code}
      </pre>
      <button className="btn-primary w-full" onClick={onCopy}>
        <Icons.Copy size={18} /> Copier le code
      </button>
      <p className="text-xs text-muted text-center mt-3">
        Le domaine de votre site sera détecté automatiquement et devra être approuvé via l'admin web.
      </p>
    </Sheet>
  );
}

function ProfileEditSheet({ open, onClose, restaurant, onUpdate }) {
  const [form, setForm] = useState({});
  const [saving, setSaving] = useState(false);
  const notify = useNotifications();

  useEffect(() => {
    if (open && restaurant) {
      setForm({
        name: restaurant.name || '',
        description: restaurant.description || '',
        phone: restaurant.phone || '',
        email: restaurant.email || '',
        address: restaurant.address || '',
        website: restaurant.website || '',
        primary_color: restaurant.primary_color || '#14B8A6',
      });
    }
  }, [open, restaurant]);

  async function save() {
    setSaving(true);
    try {
      const res = await RchAPI.updateRestaurant(form);
      notify.success('Profil mis à jour');
      if (onUpdate && res?.restaurant) onUpdate(res.restaurant);
      onClose();
    } catch (e) {
      notify.error('Erreur: ' + e.message);
    }
    setSaving(false);
  }

  if (!open) return null;

  return (
    <Sheet open={open} onClose={onClose} title="Modifier mes infos">
      <div className="flex flex-col gap-3">
        <div>
          <label className="form-label">Nom du restaurant</label>
          <input className="input-field" value={form.name || ''} onChange={e => setForm({ ...form, name: e.target.value })} />
        </div>
        <div>
          <label className="form-label">Description</label>
          <textarea className="input-field" rows="3" value={form.description || ''} onChange={e => setForm({ ...form, description: e.target.value })} />
        </div>
        <div>
          <label className="form-label">Téléphone</label>
          <input type="tel" className="input-field" value={form.phone || ''} onChange={e => setForm({ ...form, phone: e.target.value })} />
        </div>
        <div>
          <label className="form-label">Email</label>
          <input type="email" className="input-field" value={form.email || ''} onChange={e => setForm({ ...form, email: e.target.value })} />
        </div>
        <div>
          <label className="form-label">Adresse</label>
          <input className="input-field" value={form.address || ''} onChange={e => setForm({ ...form, address: e.target.value })} />
        </div>
        <div>
          <label className="form-label">Site web</label>
          <input type="url" className="input-field" value={form.website || ''} onChange={e => setForm({ ...form, website: e.target.value })} placeholder="https://" />
        </div>
        <div>
          <label className="form-label">Couleur principale</label>
          <div className="flex items-center gap-2">
            <input type="color" value={form.primary_color || '#14B8A6'} onChange={e => setForm({ ...form, primary_color: e.target.value })}
              style={{ width: 48, height: 48, padding: 0, border: '2px solid #E2E8F0', borderRadius: 12, background: 'transparent' }} />
            <input className="input-field" value={form.primary_color || ''} onChange={e => setForm({ ...form, primary_color: e.target.value })} />
          </div>
        </div>
        <div className="flex gap-2 mt-2">
          <button className="btn-secondary flex-1" onClick={onClose} disabled={saving}>Annuler</button>
          <button className="btn-primary flex-1" onClick={save} disabled={saving}>
            {saving ? <Spinner size="sm" /> : <Icons.Save size={18} />} Enregistrer
          </button>
        </div>
      </div>
    </Sheet>
  );
}

window.LoginView = LoginView;
window.DashboardView = DashboardView;
window.BookingsView = BookingsView;
window.CalendarView = CalendarView;
window.ProfileView = ProfileView;
