/**
 * Oveyo PWA — Pages : Pharmacies de garde, Profil, Espace Commerçant
 */

const Lu4 = window.LucideReact || {};
const { Card: C4, Spinner: Sp4, EmptyState: ES4, useFlash: uF4 } = window.OveyoUI;
const {
  usePharmaciesOnDuty: uPh, useAmbassador: uAmb, api: api4,
} = window.OveyoState;

// ============================================================
// PAGE PHARMACIES
// ============================================================
const PharmacyPage = ({ state, onOpenSheet }) => {
  const { Cross, Camera, ChevronRight, Phone, Navigation, Clock, Pill } = Lu4;
  const { pharmacies, loading } = uPh();

  return (
    <div className="px-5 pt-5 space-y-4 pb-4">
      <div>
        <h2 className="font-display font-bold text-2xl text-ink">De garde ce soir</h2>
        <div className="flex items-center gap-1.5 text-xs mt-1 text-slate">
          <Clock size={11} /> Mis à jour il y a peu
        </div>
      </div>

      {/* SOS Ordonnance — feature avancée */}
      <button
        onClick={() => onOpenSheet('sos-prescription')}
        className="w-full rounded-2xl p-4 text-left flex items-center gap-3 relative overflow-hidden"
        style={{ background: 'linear-gradient(135deg, #102A43 0%, #1f3a5f 100%)' }}
      >
        <div className="w-11 h-11 rounded-xl bg-white/15 flex items-center justify-center backdrop-blur">
          <Camera size={20} className="text-white" />
        </div>
        <div className="flex-1">
          <div className="font-display font-bold text-white text-base">SOS Ordonnance</div>
          <div className="text-xs text-white/70">Photographie ta prescription · les pharmacies te disent qui a le médicament</div>
        </div>
        <ChevronRight size={20} className="text-white/80" />
      </button>

      {/* Liste pharmacies */}
      {loading ? (
        <div className="text-center py-10"><Sp4 /></div>
      ) : pharmacies.length === 0 ? (
        <ES4
          icon={Cross}
          title="Aucune pharmacie de garde"
          subtitle="Les pharmacies de garde sont mises à jour quotidiennement par notre équipe."
        />
      ) : (
        <div className="space-y-3">
          {pharmacies.map((p, i) => (
            <C4 key={i}>
              <div className="p-4">
                <div className="flex items-start gap-3">
                  <div
                    className="w-12 h-12 rounded-xl flex items-center justify-center flex-shrink-0 relative"
                    style={{ background: '#E8F5E9' }}
                  >
                    <Cross size={22} style={{ color: '#15803D' }} strokeWidth={2.5} />
                    <div
                      className="absolute -top-1 -right-1 w-3 h-3 rounded-full"
                      style={{ background: '#15803D' }}
                    />
                  </div>
                  <div className="flex-1 min-w-0">
                    <div className="font-display font-bold text-base leading-tight text-ink">{p.name}</div>
                    <div className="text-xs mt-1 text-slate">{p.neighborhood_name || ''} {p.distance && `· ${p.distance}`}</div>
                    <div
                      className="inline-flex items-center gap-1 mt-2 px-2 py-0.5 rounded-full text-[10px] font-bold uppercase tracking-wide"
                      style={{ background: '#E8F5E9', color: '#15803D' }}
                    >
                      <span className="w-1.5 h-1.5 rounded-full" style={{ background: '#15803D' }} />
                      {p.duty_label || 'Garde 24h'}
                    </div>
                  </div>
                </div>
                <div className="flex gap-2 mt-3 pt-3" style={{ borderTop: '1px solid #EAEEF4' }}>
                  {p.phone && (
                    <a
                      href={`tel:${p.phone}`}
                      className="flex-1 py-2.5 rounded-xl font-semibold text-xs flex items-center justify-center gap-1.5"
                      style={{ background: '#F1F4F9', color: '#0F1F36' }}
                    >
                      <Phone size={13} /> Appeler
                    </a>
                  )}
                  {p.lat && p.lng && (
                    <a
                      href={`https://www.google.com/maps/dir/?api=1&destination=${p.lat},${p.lng}`}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="flex-1 py-2.5 rounded-xl font-semibold text-xs text-white flex items-center justify-center gap-1.5"
                      style={{ background: '#102A43' }}
                    >
                      <Navigation size={13} /> Itinéraire
                    </a>
                  )}
                </div>
              </div>
            </C4>
          ))}
        </div>
      )}
    </div>
  );
};

// ============================================================
// PAGE PROFIL
// ============================================================
const ProfilePage = ({ state, setState, onOpenSheet, onSwitchView }) => {
  const {
    Award, Gift, Eye, ChevronRight, Sparkles, Store, Shield, Bell,
    LogOut, WifiOff, Lock, BellRing,
  } = Lu4;
  const { data: ambData } = uAmb(state.user.phone);
  const flash = uF4();

  // Pas connectée — invitation
  if (!state.user.phone) {
    return (
      <div className="px-5 pt-6 space-y-4 pb-4">
        <div>
          <h2 className="font-display font-bold text-2xl text-ink">Mon compte</h2>
          <p className="text-sm mt-1 text-slate">Connecte-toi pour gagner des points et débloquer ton espace ambassadeur</p>
        </div>

        <div
          className="rounded-3xl p-6 relative overflow-hidden text-white"
          style={{ background: 'linear-gradient(135deg, #102A43 0%, #1f3a5f 100%)' }}
        >
          <div className="absolute inset-0 grain opacity-20" />
          <div className="relative">
            <div className="w-16 h-16 rounded-2xl bg-white/15 backdrop-blur flex items-center justify-center mb-4">
              <Sparkles size={28} className="text-white" />
            </div>
            <h3 className="font-display font-bold text-xl">Devenir Ambassadrice</h3>
            <p className="text-sm text-white/80 mt-2 leading-relaxed">
              Gagne des points à chaque prix partagé, débloque des badges, et reçois des récompenses Orange.
            </p>
            <button
              onClick={() => onOpenSheet('login')}
              className="mt-4 px-5 py-2.5 rounded-xl font-bold text-sm flex items-center gap-2"
              style={{ background: '#F4632B', color: 'white' }}
            >
              Me connecter avec WhatsApp <ChevronRight size={16} />
            </button>
          </div>
        </div>

        {/* Liens secondaires */}
        <C4 noBar>
          <button
            onClick={() => onOpenSheet('login', { redirect: 'merchant' })}
            className="w-full p-4 flex items-center gap-3 text-left border-b border-bg-2"
          >
            <div
              className="w-12 h-12 rounded-xl flex items-center justify-center"
              style={{ background: 'linear-gradient(135deg, #102A43 0%, #F4632B 130%)' }}
            >
              <Store size={22} className="text-white" />
            </div>
            <div className="flex-1">
              <div className="font-display font-bold text-base text-ink">Espace Commerçant</div>
              <div className="text-xs text-slate">Réclame ta boutique, justifie tes prix</div>
            </div>
            <ChevronRight size={20} className="text-slate" />
          </button>
          <button
            onClick={() => onOpenSheet('notifications')}
            className="w-full flex items-center gap-3 p-4 text-left border-b border-bg-2"
          >
            <div className="w-9 h-9 rounded-xl flex items-center justify-center" style={{ background: '#F1F4F9' }}>
              <BellRing size={16} style={{ color: '#102A43' }} />
            </div>
            <span className="flex-1 font-semibold text-sm text-ink">Notifications</span>
            <span className="text-xs text-slate">
              {typeof Notification !== 'undefined' && Notification.permission === 'granted' ? 'Activées' : 'Désactivées'}
            </span>
            <ChevronRight size={16} className="text-slate" />
          </button>
          <button
            onClick={() => onOpenSheet('offline-mode')}
            className="w-full flex items-center gap-3 p-4 text-left"
          >
            <div className="w-9 h-9 rounded-xl flex items-center justify-center" style={{ background: '#F1F4F9' }}>
              <WifiOff size={16} style={{ color: '#102A43' }} />
            </div>
            <span className="flex-1 font-semibold text-sm text-ink">Mode hors-ligne</span>
            <span className="text-xs font-medium text-slate">Activé</span>
            <ChevronRight size={16} className="text-slate" />
          </button>
        </C4>
      </div>
    );
  }

  // Connectée
  const stats = ambData?.stats || { nb_observations: 0, nb_badges: 0, points: 0, rank_in_neighborhood: null };
  const badges = ambData?.badges || [];
  const recent = ambData?.recent || [];
  const userInfo = ambData?.user || null;
  const isAmbassador = userInfo?.is_ambassador;

  const logout = async () => {
    if (!confirm('Te déconnecter ?')) return;
    // Révocation server-side (best-effort, ne bloque pas si réseau KO)
    const token = state.user?.session_token;
    if (token) {
      try {
        await fetch('/api/pwa/logout', {
          method: 'POST',
          headers: { 'Authorization': 'Bearer ' + token },
        });
      } catch (_) { /* offline → on clear quand même côté client */ }
    }
    setState({
      ...state,
      user: {
        phone: null, pseudonym: null, neighborhood_slug: null,
        language: 'fr', session_token: null, is_merchant: false,
      },
    });
    flash.show('info', 'Tu es déconnectée');
  };

  // Multi-villes : afficher quartier + ville si hors Dakar
  const neighborhoodLabel = userInfo?.neighborhood_name
    || (state.user.neighborhood_slug
        ? state.user.neighborhood_slug.replace(/-/g, ' ').replace(/\b\w/g, c => c.toUpperCase())
        : 'Dakar');
  const cityName = userInfo?.city_name || null;
  const showCity = cityName && cityName.toLowerCase() !== 'dakar';
  const profileSubtitle = showCity
    ? `Pseudonyme actif · ${cityName}`
    : (userInfo?.neighborhood_name ? `Pseudonyme actif · ${userInfo.neighborhood_name}` : 'Pseudonyme actif');

  return (
    <div className="px-5 pt-5 space-y-4 pb-4">
      {/* Carte profil */}
      <div
        className="rounded-3xl p-5 relative overflow-hidden text-white"
        style={{ background: 'linear-gradient(135deg, #102A43 0%, #1f3a5f 100%)' }}
      >
        <div className="absolute inset-0 grain opacity-20" />
        <div className="relative flex items-center gap-3">
          <div
            className="w-16 h-16 rounded-full flex items-center justify-center font-display font-bold text-2xl"
            style={{ background: '#F4632B' }}
          >
            {(state.user.pseudonym || 'O').charAt(0).toUpperCase()}
          </div>
          <div className="flex-1">
            <div className="font-display font-bold text-lg leading-tight">
              {state.user.pseudonym || 'Anonyme'}
            </div>
            <div className="text-xs text-white/70">
              {profileSubtitle}
            </div>
          </div>
        </div>
        <div
          className="relative mt-5 pt-4 grid grid-cols-3 gap-2"
          style={{ borderTop: '1px solid rgba(255,255,255,0.1)' }}
        >
          <div>
            <div className="font-display font-bold text-2xl">{stats.nb_observations}</div>
            <div className="text-[10px] uppercase tracking-wider text-white/60">Signalements</div>
          </div>
          <div>
            <div className="font-display font-bold text-2xl">{stats.points}</div>
            <div className="text-[10px] uppercase tracking-wider text-white/60">Points</div>
          </div>
          <div>
            <div className="font-display font-bold text-2xl" style={{ color: '#FFA45B' }}>
              {stats.rank_in_neighborhood ? `#${stats.rank_in_neighborhood}` : '—'}
            </div>
            <div className="text-[10px] uppercase tracking-wider text-white/60">Quartier</div>
          </div>
        </div>
      </div>

      {/* Identité publique + sub-CTA Devenir Ambassadeur */}
      <C4>
        <div className="p-4">
          <div className="flex items-start gap-3 mb-3">
            <div className="w-10 h-10 rounded-xl flex items-center justify-center flex-shrink-0" style={{ background: '#F1F4F9' }}>
              <Shield size={18} style={{ color: '#102A43' }} />
            </div>
            <div className="flex-1">
              <div className="text-[10px] font-bold uppercase tracking-wider text-slate">Identité publique</div>
              <div className="font-display font-bold text-sm leading-tight text-ink">
                Tu apparais comme « {state.user.pseudonym || 'Anonyme'} de {neighborhoodLabel} »
              </div>
              <div className="text-[11px] mt-1 text-slate">
                Tes signalements restent <strong className="text-ink">100% anonymes</strong>. Aucun numéro n'est partagé.
              </div>
            </div>
          </div>
          {!isAmbassador && (
            <div
              className="rounded-xl p-3 flex items-center gap-3"
              style={{ background: 'linear-gradient(135deg, #FFF8F1 0%, #FEEEE3 100%)', border: '1px solid #FFE0CC' }}
            >
              <div
                className="w-9 h-9 rounded-lg flex items-center justify-center flex-shrink-0"
                style={{ background: 'linear-gradient(135deg, #FFA45B 0%, #F4632B 100%)' }}
              >
                <Sparkles size={15} className="text-white" />
              </div>
              <div className="flex-1 min-w-0">
                <div className="text-xs font-display font-bold text-ink">Devenir Ambassadeur</div>
                <div className="text-[10px] text-slate">Vrai nom + photo + badge vérifié ✓</div>
              </div>
              <button
                onClick={() => onOpenSheet('become-ambassador')}
                className="px-3 py-1.5 rounded-lg text-[10px] font-bold text-white flex-shrink-0"
                style={{ background: '#F4632B' }}
              >Activer</button>
            </div>
          )}
        </div>
      </C4>

      {/* Espace Commerçant */}
      <C4>
        <button
          onClick={() => onSwitchView('merchant')}
          className="w-full p-4 flex items-center gap-3 text-left"
        >
          <div
            className="w-12 h-12 rounded-xl flex items-center justify-center"
            style={{ background: 'linear-gradient(135deg, #102A43 0%, #F4632B 130%)' }}
          >
            <Store size={22} className="text-white" />
          </div>
          <div className="flex-1">
            <div className="font-display font-bold text-base text-ink">Espace Commerçant</div>
            <div className="text-xs text-slate">Réclame ta boutique, justifie tes prix, gagne des étoiles</div>
          </div>
          <ChevronRight size={20} className="text-slate" />
        </button>
      </C4>

      {/* Carte Ambassadeur */}
      <C4 noBar>
        <div className="p-4 flex items-center gap-3">
          <div
            className="w-14 h-14 rounded-2xl flex items-center justify-center"
            style={{ background: 'linear-gradient(135deg, #FFA45B 0%, #F4632B 100%)' }}
          >
            <Award size={26} className="text-white" />
          </div>
          <div className="flex-1">
            <div className="font-display font-bold text-base text-ink">Ambassadeur</div>
            <div className="text-xs text-slate">
              {stats.nb_observations} prix partagé{stats.nb_observations > 1 ? 's' : ''}
              {' · '}
              {stats.nb_badges} badge{stats.nb_badges > 1 ? 's' : ''}
            </div>
          </div>
        </div>
      </C4>

      {/* Récompense Orange — cliquable */}
      <button
        onClick={() => onOpenSheet('reward', { stats })}
        className="w-full rounded-2xl p-4 relative overflow-hidden text-left"
        style={{ background: 'linear-gradient(135deg, #FF7900 0%, #F4632B 100%)' }}
      >
        <div className="flex items-start gap-3">
          <div className="w-12 h-12 rounded-xl bg-white/20 flex items-center justify-center backdrop-blur flex-shrink-0">
            <Gift size={22} className="text-white" />
          </div>
          <div className="flex-1 text-white">
            <div className="text-[10px] font-bold uppercase tracking-wider opacity-90">Récompense ce mois</div>
            <div className="font-display font-bold text-base mt-0.5 leading-tight">500 Mo de DATA Orange</div>
            <div className="text-xs opacity-90 mt-1">
              Top 100 contributeurs · {stats.rank_in_neighborhood ? `Tu es ${stats.rank_in_neighborhood}ème de ton quartier 🔥` : 'Signale pour participer'}
            </div>
          </div>
          <ChevronRight size={18} className="text-white/80 flex-shrink-0 mt-1" />
        </div>
      </button>

      {/* Liste : Mes prix partagés / Mes badges / Mode hors-ligne */}
      <C4 noBar>
        <button
          onClick={() => onOpenSheet('my-reports')}
          className="w-full flex items-center gap-3 p-4 text-left border-b border-bg-2"
        >
          <div className="w-9 h-9 rounded-xl flex items-center justify-center" style={{ background: '#F1F4F9' }}>
            <Eye size={16} style={{ color: '#102A43' }} />
          </div>
          <span className="flex-1 font-semibold text-sm text-ink">Mes prix partagés</span>
          <span className="text-xs font-medium text-slate">{stats.nb_observations}</span>
          <ChevronRight size={16} className="text-slate" />
        </button>
        <button
          onClick={() => onOpenSheet('my-badges')}
          className="w-full flex items-center gap-3 p-4 text-left border-b border-bg-2"
        >
          <div className="w-9 h-9 rounded-xl flex items-center justify-center" style={{ background: '#F1F4F9' }}>
            <Award size={16} style={{ color: '#102A43' }} />
          </div>
          <span className="flex-1 font-semibold text-sm text-ink">Mes badges</span>
          <span className="text-xs font-medium text-slate">{stats.nb_badges}</span>
          <ChevronRight size={16} className="text-slate" />
        </button>
        <button
          onClick={() => onOpenSheet('offline-mode')}
          className="w-full flex items-center gap-3 p-4 text-left"
        >
          <div className="w-9 h-9 rounded-xl flex items-center justify-center" style={{ background: '#F1F4F9' }}>
            <WifiOff size={16} style={{ color: '#102A43' }} />
          </div>
          <span className="flex-1 font-semibold text-sm text-ink">Mode hors-ligne</span>
          <span className="text-xs font-medium text-slate">Activé</span>
          <ChevronRight size={16} className="text-slate" />
        </button>
      </C4>

      {/* Notifications + déconnexion */}
      <C4 noBar>
        <button
          onClick={() => onOpenSheet('notifications')}
          className="w-full flex items-center gap-3 p-4 text-left border-b border-bg-2"
        >
          <div className="w-9 h-9 rounded-xl flex items-center justify-center" style={{ background: '#F1F4F9' }}>
            <BellRing size={16} style={{ color: '#102A43' }} />
          </div>
          <span className="flex-1 font-semibold text-sm text-ink">Notifications</span>
          <span className="text-xs text-slate">
            {typeof Notification !== 'undefined' && Notification.permission === 'granted' ? 'Activées' : 'Désactivées'}
          </span>
          <ChevronRight size={16} className="text-slate" />
        </button>
        <button
          onClick={logout}
          className="w-full flex items-center gap-3 p-4 text-left"
        >
          <div className="w-9 h-9 rounded-xl flex items-center justify-center" style={{ background: '#FEEEE3' }}>
            <LogOut size={16} style={{ color: '#F4632B' }} />
          </div>
          <span className="flex-1 font-semibold text-sm text-orange">Se déconnecter</span>
        </button>
      </C4>
    </div>
  );
};

// ============================================================
// VUE COMMERÇANT
// ============================================================
// ============================================================
// VUE COMMERÇANT — V3 live (sessions, actions réelles)
// ============================================================
const MerchantView = ({ state, setState, onBack, onOpenSheet }) => {
  const {
    ChevronLeft, AlertTriangle, Edit3, ShieldCheck, Eye, Store,
    Loader2, Lock, RefreshCw, Check, X,
  } = Lu4;
  const flash = uF4();
  const [data, setData] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState(null);
  const [busy, setBusy] = React.useState(null); // id de l'action en cours
  const [justifyFor, setJustifyFor] = React.useState(null); // alert id
  const [justifyText, setJustifyText] = React.useState('');
  const [editPrice, setEditPrice] = React.useState(null); // {product_id, price, justification}

  const token = state.user?.session_token;

  const fetchMe = React.useCallback(async () => {
    if (!token) {
      setLoading(false);
      setError('login');
      return;
    }
    setLoading(true);
    // V3.8 P3 — important : reset l'erreur AVANT le fetch.
    // Sans ça, après login, fetchMe est rappelé mais on garde error='login'
    // pendant le fetch → l'écran "Connexion requise" reste affiché.
    setError(null);
    try {
      const r = await api4('/api/pwa/merchant/me', {
        headers: { Authorization: 'Bearer ' + token },
      });
      setData(r);
      setError(null);
    } catch (e) {
      if (String(e).match(/401|403/)) {
        setError('login');
      } else {
        setError('network');
      }
    } finally {
      setLoading(false);
    }
  }, [token]);

  React.useEffect(() => { fetchMe(); }, [fetchMe]);

  const authedFetch = async (url, options = {}) => {
    return api4(url, {
      ...options,
      headers: {
        ...(options.headers || {}),
        Authorization: 'Bearer ' + token,
      },
    });
  };

  // --- Actions ---
  const dismissAlert = async (alertId) => {
    setBusy('dismiss-' + alertId);
    try {
      await authedFetch(`/api/pwa/merchant/alerts/${alertId}/dismiss`, { method: 'POST' });
      flash.show('success', 'Alerte fermée');
      await fetchMe();
    } catch (e) {
      flash.show('error', 'Erreur — réessaie');
    } finally { setBusy(null); }
  };

  const submitJustification = async (alertId) => {
    if (justifyText.trim().length < 10) {
      flash.show('error', 'Justification trop courte (10 caractères min)');
      return;
    }
    setBusy('justify-' + alertId);
    try {
      await authedFetch(`/api/pwa/merchant/alerts/${alertId}/justify`, {
        method: 'POST',
        body: JSON.stringify({ justification: justifyText.trim() }),
      });
      flash.show('success', 'Justification envoyée');
      setJustifyFor(null);
      setJustifyText('');
      await fetchMe();
    } catch {
      flash.show('error', 'Erreur — réessaie');
    } finally { setBusy(null); }
  };

  const toggleStock = async (shopId, productId, available) => {
    setBusy(`stock-${shopId}-${productId}`);
    try {
      await authedFetch(`/api/pwa/merchant/shops/${shopId}/stock`, {
        method: 'POST',
        body: JSON.stringify({ product_id: productId, available }),
      });
      flash.show('success', available ? 'Marqué disponible' : 'Marqué en rupture');
      await fetchMe();
    } catch {
      flash.show('error', 'Erreur');
    } finally { setBusy(null); }
  };

  const submitPrice = async (shopId) => {
    if (!editPrice) return;
    const p = parseInt(editPrice.price, 10);
    if (!p || p < 1) { flash.show('error', 'Prix invalide'); return; }
    setBusy(`price-${editPrice.product_id}`);
    try {
      await authedFetch(`/api/pwa/merchant/shops/${shopId}/prices`, {
        method: 'POST',
        body: JSON.stringify({
          product_id: editPrice.product_id,
          price: p,
          justification: editPrice.justification?.trim() || null,
        }),
      });
      flash.show('success', 'Prix mis à jour');
      setEditPrice(null);
      await fetchMe();
    } catch (e) {
      const msg = String(e.message || e);
      if (msg.includes('Justification obligatoire')) {
        flash.show('error', 'Justification obligatoire si prix > 110% officiel');
      } else {
        flash.show('error', 'Erreur — réessaie');
      }
    } finally { setBusy(null); }
  };

  // --- Rendus états spéciaux ---

  // Pas de session : invite à se connecter
  if (error === 'login') {
    return (
      <div className="min-h-screen" style={{ background: '#F1F4F9' }}>
        <Header onBack={onBack} title="Espace Commerçant" subtitle="Connecte-toi" />
        <div className="p-5">
          <C4>
            <div className="p-5 text-center">
              <div className="w-16 h-16 rounded-2xl mx-auto mb-3 flex items-center justify-center" style={{ background: '#FEEEE3' }}>
                <Lock size={28} style={{ color: '#F4632B' }} />
              </div>
              <h3 className="font-display font-bold text-base text-ink mb-2">Connexion requise</h3>
              <p className="text-sm text-slate mb-4 leading-relaxed">
                L'Espace Commerçant nécessite une connexion vérifiée par WhatsApp. Tes actions sont signées et tracées pour la sécurité.
              </p>
              <button
                onClick={() => onOpenSheet('login', { redirect: 'merchant' })}
                className="px-5 py-3 rounded-xl font-bold text-white"
                style={{ background: '#F4632B' }}
              >
                Me connecter avec WhatsApp
              </button>
            </div>
          </C4>
        </div>
      </div>
    );
  }

  if (loading) {
    return (
      <div className="min-h-screen" style={{ background: '#F1F4F9' }}>
        <Header onBack={onBack} title="Espace Commerçant" subtitle="Chargement…" />
        <div className="text-center py-20"><Sp4 /></div>
      </div>
    );
  }

  if (error === 'network') {
    return (
      <div className="min-h-screen" style={{ background: '#F1F4F9' }}>
        <Header onBack={onBack} title="Espace Commerçant" subtitle="Erreur" />
        <div className="p-5">
          <ES4 icon={AlertTriangle} title="Connexion impossible" subtitle="Vérifie ton réseau et réessaie." />
          <button
            onClick={fetchMe}
            className="mt-4 mx-auto block px-5 py-3 rounded-xl font-bold text-white"
            style={{ background: '#102A43' }}
          >
            <RefreshCw size={14} className="inline mr-1.5" /> Réessayer
          </button>
        </div>
      </div>
    );
  }

  // Pas encore de boutique vérifiée
  if (data && data.shops.length === 0) {
    return (
      <div className="min-h-screen" style={{ background: '#F1F4F9' }}>
        <Header onBack={onBack} title="Espace Commerçant" subtitle="Aucune boutique" />
        <div className="p-5">
          <C4>
            <div className="p-5 text-center">
              <div className="w-16 h-16 rounded-2xl mx-auto mb-3 flex items-center justify-center" style={{ background: '#F1F4F9' }}>
                <Store size={28} style={{ color: '#102A43' }} />
              </div>
              <h3 className="font-display font-bold text-base text-ink mb-2">Réclame ta boutique</h3>
              <p className="text-sm text-slate mb-4 leading-relaxed">
                Trouve ta boutique sur la Carte et clique sur "Réclame cette boutique". Notre équipe vérifie ton NINEA sous 48h, puis tu peux gérer ton espace ici.
              </p>
              <button
                onClick={onBack}
                className="px-5 py-3 rounded-xl font-bold text-white"
                style={{ background: '#F4632B' }}
              >
                Aller sur la Carte
              </button>
            </div>
          </C4>
        </div>
      </div>
    );
  }

  // --- Vue principale, données live ---
  const myShop = data.shops[0];
  const alerts = data.alerts || [];
  const prices = data.prices || [];
  const stock = data.stock || [];
  const stats = data.stats || {};

  return (
    <div className="min-h-screen" style={{ background: '#F1F4F9' }}>
      <Header
        onBack={onBack}
        title={myShop.name}
        subtitle={`${myShop.area}${myShop.city_name && myShop.city_name !== 'Dakar' ? ' · ' + myShop.city_name : ''}`}
      />

      <div className="px-5 -mt-1 pb-1">
        <div className="flex items-center gap-2 flex-wrap">
          <span className="inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-[10px] font-bold uppercase tracking-wide bg-white/15 text-white backdrop-blur">
            <ShieldCheck size={11} /> Vérifié
          </span>
          {data.shops.length > 1 && (
            <span className="text-xs text-white/80">{data.shops.length} boutiques</span>
          )}
        </div>
      </div>

      <div className="p-5 space-y-4">

        {/* Alertes clients (live) */}
        {alerts.length > 0 ? (
          alerts.map((a) => (
            <C4 key={a.id}>
              <div className="p-4">
                <div className="flex items-start gap-3">
                  <div className="w-10 h-10 rounded-xl flex items-center justify-center flex-shrink-0" style={{ background: '#FEEEE3' }}>
                    <AlertTriangle size={18} style={{ color: '#F4632B' }} />
                  </div>
                  <div className="flex-1 min-w-0">
                    <div className="text-[10px] font-bold uppercase tracking-wider mb-0.5 text-orange">
                      Alerte client · {formatRelativeMerchant(a.created_at)}
                    </div>
                    <div className="font-display font-bold text-sm leading-snug text-ink">
                      {a.customer_message || 'Prix signalé'}
                    </div>
                    {a.product_name && (
                      <div className="text-xs mt-1 text-slate">
                        {a.icon} {a.product_name}
                        {a.price_official ? ` · officiel ${a.price_official} F` : ''}
                      </div>
                    )}
                  </div>
                </div>
                {justifyFor === a.id ? (
                  <div className="mt-3 space-y-2">
                    <textarea
                      value={justifyText}
                      onChange={(e) => setJustifyText(e.target.value)}
                      rows={3}
                      placeholder="Pourquoi ce prix ? (transport, rareté, qualité…)"
                      className="w-full p-3 rounded-xl text-sm outline-none resize-none"
                      style={{ background: '#F1F4F9' }}
                      maxLength={500}
                      minLength={10}
                      autoFocus
                    />
                    <div className="grid grid-cols-2 gap-2">
                      <button
                        onClick={() => { setJustifyFor(null); setJustifyText(''); }}
                        className="py-2.5 rounded-xl text-xs font-semibold text-slate"
                        style={{ background: '#F1F4F9' }}
                      >Annuler</button>
                      <button
                        onClick={() => submitJustification(a.id)}
                        disabled={busy === 'justify-' + a.id || justifyText.trim().length < 10}
                        className="py-2.5 rounded-xl text-xs font-bold text-white disabled:opacity-50"
                        style={{ background: '#15803D' }}
                      >
                        {busy === 'justify-' + a.id ? <Loader2 size={12} className="inline animate-spin" /> : null} Envoyer
                      </button>
                    </div>
                  </div>
                ) : (
                  <div className="grid grid-cols-2 gap-2 mt-3">
                    <button
                      onClick={() => dismissAlert(a.id)}
                      disabled={busy === 'dismiss-' + a.id}
                      className="py-2.5 rounded-xl text-xs font-semibold text-navy disabled:opacity-50"
                      style={{ background: '#F1F4F9' }}
                    >
                      {busy === 'dismiss-' + a.id ? <Loader2 size={12} className="inline animate-spin" /> : null} Ignorer
                    </button>
                    <button
                      onClick={() => { setJustifyFor(a.id); setJustifyText(''); }}
                      className="py-2.5 rounded-xl text-xs font-bold text-white flex items-center justify-center gap-1.5 bg-navy"
                    >
                      <Edit3 size={12} /> Justifier
                    </button>
                  </div>
                )}
              </div>
            </C4>
          ))
        ) : (
          <C4 noBar>
            <div className="p-4 text-center text-sm text-slate">
              ✓ Aucune alerte client en attente
            </div>
          </C4>
        )}

        {/* Mes prix */}
        <C4>
          <div className="p-4">
            <div className="flex items-center justify-between mb-3">
              <h3 className="font-display font-bold text-base text-ink">Mes prix affichés</h3>
              <button
                onClick={() => setEditPrice({ product_id: null, price: '', justification: '' })}
                className="text-xs font-bold text-orange"
              >+ Ajouter</button>
            </div>
            {prices.length === 0 ? (
              <div className="text-sm text-slate text-center py-2">
                Aucun prix défini. Ajoute tes prix officiels pour montrer ta transparence.
              </div>
            ) : (
              <div className="space-y-2.5">
                {prices.map((p) => {
                  const overpriced = p.price_official && p.price > p.price_official * 1.1;
                  const justified = !!p.justification;
                  return (
                    <div key={p.product_id} className="flex items-center justify-between py-1">
                      <div className="flex-1 min-w-0">
                        <div className="text-sm font-semibold text-ink truncate">
                          {p.icon} {p.name_fr}
                        </div>
                        <div className="text-[10px] text-slate">
                          {p.unit}
                          {p.price_official && (
                            <> · <span className="px-1 rounded font-bold" style={{ background: '#DBEAFE', color: '#1E40AF' }}>DGCC</span> {p.price_official} F</>
                          )}
                        </div>
                        {p.justification && (
                          <div className="text-[10px] text-success mt-0.5 italic truncate">
                            "{p.justification}"
                          </div>
                        )}
                      </div>
                      <div className="flex items-center gap-2 flex-shrink-0">
                        {overpriced && !justified && (
                          <span className="text-[9px] font-bold px-1.5 py-0.5 rounded" style={{ background: '#FEEEE3', color: '#F4632B' }}>
                            NON JUSTIFIÉ
                          </span>
                        )}
                        {overpriced && justified && (
                          <span className="text-[9px] font-bold px-1.5 py-0.5 rounded" style={{ background: '#E8F5E9', color: '#15803D' }}>
                            JUSTIFIÉ
                          </span>
                        )}
                        <div className="font-display font-bold text-sm" style={{ color: overpriced && !justified ? '#F4632B' : '#0F1F36' }}>
                          {p.price} F
                        </div>
                        <button
                          onClick={() => setEditPrice({ product_id: p.product_id, price: String(p.price), justification: p.justification || '' })}
                          className="text-orange"
                          aria-label="Modifier"
                        >
                          <Edit3 size={14} />
                        </button>
                      </div>
                    </div>
                  );
                })}
              </div>
            )}
          </div>
        </C4>

        {/* État du stock */}
        <C4>
          <div className="p-4">
            <h3 className="font-display font-bold text-base mb-3 text-ink">État du stock aujourd'hui</h3>
            {stock.length === 0 ? (
              <div className="text-sm text-slate text-center py-2">
                Aucun produit suivi. Marque la dispo de tes produits pour aider tes clients.
              </div>
            ) : (
              <div className="space-y-2.5">
                {stock.map((s) => (
                  <div key={s.product_id} className="flex items-center gap-3">
                    <span className="text-lg">{s.icon}</span>
                    <span className="flex-1 font-semibold text-sm text-ink">{s.name_fr}</span>
                    <div className="flex rounded-full overflow-hidden" style={{ border: '1px solid #DDE3EC' }}>
                      <button
                        onClick={() => toggleStock(myShop.id, s.product_id, 1)}
                        disabled={busy === `stock-${myShop.id}-${s.product_id}`}
                        className="px-3 py-1 text-[11px] font-bold disabled:opacity-50"
                        style={{ background: s.available ? '#15803D' : 'transparent', color: s.available ? 'white' : '#6B7891' }}
                      >Dispo</button>
                      <button
                        onClick={() => toggleStock(myShop.id, s.product_id, 0)}
                        disabled={busy === `stock-${myShop.id}-${s.product_id}`}
                        className="px-3 py-1 text-[11px] font-bold disabled:opacity-50"
                        style={{ background: !s.available ? '#F4632B' : 'transparent', color: !s.available ? 'white' : '#6B7891' }}
                      >Rupture</button>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>
        </C4>

        {/* Stats 30j */}
        <div className="grid grid-cols-2 gap-2">
          <C4 noBar>
            <div className="p-3 text-center">
              <div className="font-display font-bold text-xl text-navy">{stats.nb_observations_30d || 0}</div>
              <div className="text-[9px] uppercase tracking-wider font-bold text-slate">Signalements 30j</div>
            </div>
          </C4>
          <C4 noBar>
            <div className="p-3 text-center">
              <div className="font-display font-bold text-xl" style={{ color: (stats.nb_abuse_signals || 0) > 0 ? '#F4632B' : '#15803D' }}>
                {stats.nb_abuse_signals || 0}
              </div>
              <div className="text-[9px] uppercase tracking-wider font-bold text-slate">Alertes abus</div>
            </div>
          </C4>
        </div>
      </div>

      {/* Modal édition prix (simple inline) */}
      {editPrice && (
        <PriceEditModal
          editPrice={editPrice}
          setEditPrice={setEditPrice}
          prices={prices}
          onSubmit={() => submitPrice(myShop.id)}
          busy={busy && busy.startsWith('price-')}
        />
      )}
    </div>
  );
};

// Header partagé
const Header = ({ onBack, title, subtitle }) => {
  const { ChevronLeft } = Lu4;
  return (
    <div
      className="px-5 pt-12 sm:pt-6 pb-5 relative"
      style={{ background: 'linear-gradient(115deg, #102A43 0%, #1f3a5f 60%, #F4632B 130%)' }}
    >
      <div className="absolute inset-0 grain opacity-20" />
      <div className="relative flex items-center gap-3">
        <button
          onClick={onBack}
          className="w-9 h-9 rounded-full bg-white/15 backdrop-blur flex items-center justify-center"
          aria-label="Retour"
        >
          <ChevronLeft size={18} className="text-white" />
        </button>
        <div>
          <div className="text-[10px] uppercase tracking-widest font-bold" style={{ color: '#FFA45B' }}>
            Espace Commerçant
          </div>
          <div className="font-display text-xl font-bold text-white leading-tight">{title}</div>
          {subtitle && <div className="text-xs text-white/80 mt-0.5">{subtitle}</div>}
        </div>
      </div>
    </div>
  );
};

// Modal édition prix
const PriceEditModal = ({ editPrice, setEditPrice, prices, onSubmit, busy }) => {
  const { X, Loader2 } = Lu4;
  const { useCatalog } = window.OveyoState;
  const { products } = useCatalog();

  const isNew = !editPrice.product_id;
  const product = isNew ? null : products.find(p => p.id === editPrice.product_id);

  // Pour le mode "ajouter", offrir la liste des produits non encore tarifés
  const tariffedIds = new Set(prices.map(p => p.product_id));
  const candidateProducts = products.filter(p => !tariffedIds.has(p.id));

  return (
    <div
      className="fixed inset-0 z-[60] flex items-end sm:items-center justify-center p-4"
      style={{ background: 'rgba(15,31,54,0.65)' }}
      onClick={() => setEditPrice(null)}
    >
      <div
        className="bg-white rounded-2xl w-full max-w-md p-5 max-h-[90vh] overflow-y-auto"
        onClick={(e) => e.stopPropagation()}
      >
        <div className="flex items-center justify-between mb-4">
          <h3 className="font-display font-bold text-lg text-ink">
            {isNew ? 'Ajouter un prix' : `Modifier ${product?.name_fr || ''}`}
          </h3>
          <button onClick={() => setEditPrice(null)} className="p-1"><X size={20} className="text-slate" /></button>
        </div>

        <div className="space-y-4">
          {isNew && (
            <div>
              <label className="text-[11px] font-bold uppercase tracking-wider text-slate">Produit</label>
              <select
                value={editPrice.product_id || ''}
                onChange={(e) => setEditPrice({ ...editPrice, product_id: parseInt(e.target.value, 10) || null })}
                className="mt-1.5 w-full p-3 rounded-xl text-sm outline-none"
                style={{ background: '#F1F4F9' }}
              >
                <option value="">Sélectionner</option>
                {candidateProducts.map(p => (
                  <option key={p.id} value={p.id}>{p.icon} {p.name_fr} ({p.unit})</option>
                ))}
              </select>
            </div>
          )}

          <div>
            <label className="text-[11px] font-bold uppercase tracking-wider text-slate">
              Prix affiché (FCFA)
              {product?.price_official && <span className="text-orange ml-2">officiel {product.price_official} F</span>}
            </label>
            <input
              type="number"
              value={editPrice.price}
              onChange={(e) => setEditPrice({ ...editPrice, price: e.target.value })}
              placeholder="Ex: 750"
              className="mt-1.5 w-full p-3 rounded-xl text-base outline-none font-display font-bold"
              style={{ background: '#F1F4F9' }}
              min={1}
              max={10000000}
              inputMode="numeric"
            />
          </div>

          <div>
            <label className="text-[11px] font-bold uppercase tracking-wider text-slate">
              Justification {product?.price_official && parseInt(editPrice.price, 10) > product.price_official * 1.1 && <span className="text-orange">(obligatoire)</span>}
            </label>
            <textarea
              value={editPrice.justification}
              onChange={(e) => setEditPrice({ ...editPrice, justification: e.target.value })}
              rows={3}
              placeholder="Ex: prix de gros augmenté de 15% chez le fournisseur"
              className="mt-1.5 w-full p-3 rounded-xl text-sm outline-none resize-none"
              style={{ background: '#F1F4F9' }}
              maxLength={500}
            />
            <div className="text-[10px] text-slate mt-1">
              Une justification claire améliore la confiance des clients.
            </div>
          </div>

          <button
            onClick={onSubmit}
            disabled={busy || !editPrice.product_id || !editPrice.price}
            className="w-full py-3.5 rounded-xl font-display font-bold text-white text-sm flex items-center justify-center gap-2 disabled:opacity-60"
            style={{ background: '#F4632B' }}
          >
            {busy ? <Loader2 size={16} className="animate-spin" /> : null}
            Enregistrer
          </button>
        </div>
      </div>
    </div>
  );
};

// Helper local
const formatRelativeMerchant = (iso) => {
  if (!iso) return '';
  try {
    const d = new Date(iso + 'Z');
    const m = Math.floor((Date.now() - d.getTime()) / 60000);
    if (m < 1) return "à l'instant";
    if (m < 60) return `il y a ${m} min`;
    if (m < 1440) return `il y a ${Math.floor(m/60)} h`;
    return `il y a ${Math.floor(m/1440)} j`;
  } catch { return ''; }
};

window.OveyoPages = window.OveyoPages || {};
window.OveyoPages.PharmacyPage = PharmacyPage;
window.OveyoPages.ProfilePage = ProfilePage;
window.OveyoPages.MerchantView = MerchantView;
