/**
 * Oveyo PWA — Application principale (style Vivinter)
 *
 * 5 onglets : Accueil, Carte, Partager, Pharmacie, Moi
 * + Vue Espace Commerçant (depuis profil)
 *
 * Toutes les pages sont branchées sur l'API V4.1+PWA d'Oveyo.
 */

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

// Import lucide-react via UMD global
const Lu = window.lucide || {};
const {
  Home, MapPin, Camera, Cross, User, ChevronRight, ChevronLeft,
  TrendingDown, TrendingUp, AlertTriangle, Bell, Plus, Check, Clock,
  Phone, Navigation, Award, Gift, Eye, Sparkles, Store,
  Users, ShieldCheck, Edit3, Wifi, WifiOff, Shield, X,
  RefreshCw, Search, Filter, Loader2, Send, ArrowRight, Lock,
  ChevronDown, ChevronUp, Pill,
} = window.LucideReact || {};

// Components partagés
const { GradientBar, Card, IconBubble, FlashProvider, useFlash, Sheet, EmptyState, Spinner } = window.OveyoUI;
const {
  loadState, saveState, defaultState, api,
  usePrices, useCatalog, usePharmaciesOnDuty, useShops, usePulseFeed,
  useAmbassador, useTrustIndex, useGroupBuys, useGeolocation, useOnlineStatus,
  formatRelative, formatPhone, compressImage,
} = window.OveyoState;

// ============================================================
// HEADER GRADIENT (top bar Oveyo)
// ============================================================
const TopBar = ({ state, onBellClick }) => {
  const online = useOnlineStatus();
  const neighborhood = state.user.neighborhood_slug
    ? state.user.neighborhood_slug.replace(/-/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase())
    : 'Dakar';

  return (
    <div
      className="px-5 pt-12 sm:pt-6 pb-5 relative"
      style={{
        background: 'linear-gradient(115deg, #102A43 0%, #1f3a5f 55%, #F4632B 130%)',
      }}
    >
      <div className="absolute inset-0 grain opacity-20 pointer-events-none" />
      <div className="relative flex items-center justify-between">
        <div>
          <div className="font-display text-[26px] font-bold text-white leading-none">Oveyo</div>
          <div className="flex items-center gap-1.5 mt-1.5 text-xs text-white/80">
            <MapPin size={11} strokeWidth={2.5} />
            <span className="font-medium">{neighborhood}</span>
            <span
              className="ml-2 inline-flex items-center gap-1 text-[10px] font-bold uppercase tracking-wider px-1.5 py-0.5 rounded"
              style={{
                background: online ? 'rgba(255,164,91,0.2)' : 'rgba(220,38,38,0.25)',
                color: online ? '#FFA45B' : '#FCA5A5',
              }}
            >
              {online ? <Wifi size={9} /> : <WifiOff size={9} />}
              {online ? 'Synchro' : 'Hors-ligne'}
            </span>
          </div>
        </div>
        <button
          className="relative w-10 h-10 rounded-full bg-white/15 backdrop-blur flex items-center justify-center"
          onClick={onBellClick}
          aria-label="Notifications"
        >
          <Bell size={17} className="text-white" strokeWidth={2.2} />
          <span
            className="absolute top-2 right-2 w-2 h-2 rounded-full"
            style={{ background: '#F4632B' }}
          />
        </button>
      </div>
    </div>
  );
};

// ============================================================
// PAGE : ACCUEIL
// ============================================================
const HomePage = ({ state, setActiveTab, onOpenSheet }) => {
  const { feed, loading: pulseLoading } = usePulseFeed(state.user.neighborhood_slug);
  const { data: pricesData } = usePrices(state.user.neighborhood_slug, 7);
  const trustIndex = useTrustIndex(state.user.neighborhood_slug);
  const groupBuys = useGroupBuys(state.user.neighborhood_slug);

  const products = (pricesData?.products || []).slice(0, 4).filter((p) => p.avg_price);

  return (
    <div className="px-5 pt-4 space-y-4 pb-4">

      {/* Pulse du quartier */}
      <Card className="anim-slide">
        <div className="p-4">
          <div className="flex items-center justify-between mb-3">
            <div className="flex items-center gap-2">
              <div className="relative">
                <div className="w-2 h-2 rounded-full bg-success" />
                <span className="absolute inset-0 rounded-full pulse-ring" style={{ color: '#15803D' }} />
              </div>
              <h3 className="font-display font-bold text-sm text-ink">Pulse de ton quartier</h3>
            </div>
            <span className="text-[10px] font-bold uppercase tracking-wider text-slate">en direct</span>
          </div>
          {pulseLoading ? (
            <div className="py-4 text-center"><Spinner size={20} /></div>
          ) : feed.length === 0 ? (
            <p className="text-xs text-slate text-center py-3">Pas encore d'activité dans ton quartier — sois la première à signaler !</p>
          ) : (
            <div className="space-y-2.5">
              {feed.slice(0, 3).map((p, i) => (
                <div key={i} className="flex items-center gap-2.5 text-xs">
                  <div
                    className="w-7 h-7 rounded-full flex items-center justify-center font-display font-bold text-[10px] text-white flex-shrink-0 relative"
                    style={{ background: p.anonymous ? '#6B7891' : (p.color || '#102A43') }}
                  >
                    {p.anonymous ? <Shield size={12} /> : (p.user || '?')[0].toUpperCase()}
                    {!!p.ambassador && (
                      <div
                        className="absolute -bottom-0.5 -right-0.5 w-3.5 h-3.5 rounded-full flex items-center justify-center"
                        style={{ background: '#F4632B', border: '1.5px solid white' }}
                      >
                        <Check size={7} className="text-white" strokeWidth={4} />
                      </div>
                    )}
                  </div>
                  <div className="flex-1 min-w-0 text-ink">
                    {p.anonymous ? (
                      <>
                        <span className="font-bold uppercase text-[10px] tracking-wider text-slate">Anonyme</span>{' '}
                        <span className="text-slate">· {p.action}</span>{' '}
                        <span className="font-semibold">{p.place}</span>
                      </>
                    ) : (
                      <>
                        <span className="font-bold">{p.user}</span>
                        <span className="font-medium text-slate"> de {p.area} </span>
                        <span className="text-slate">{p.action}</span>{' '}
                        <span className="font-semibold">{p.place}</span>
                      </>
                    )}
                  </div>
                  <span className="text-[10px] flex-shrink-0 text-slate">{formatRelative(p.created_at) || p.time}</span>
                </div>
              ))}
            </div>
          )}
        </div>
      </Card>

      {/* Quick actions */}
      <div className="grid grid-cols-2 gap-3 anim-slide" style={{ animationDelay: '60ms' }}>
        <button
          onClick={() => setActiveTab('report')}
          className="rounded-2xl p-4 text-left relative overflow-hidden"
          style={{ background: '#102A43' }}
        >
          <Camera size={22} className="text-white mb-7" strokeWidth={2.2} />
          <div className="font-display font-bold text-white text-base leading-tight">Partager<br/>un prix</div>
          <div className="text-[10px] mt-1 font-medium uppercase tracking-wider" style={{ color: '#FFA45B' }}>+5 points</div>
        </button>
        <button
          onClick={() => setActiveTab('map')}
          className="rounded-2xl p-4 text-left relative overflow-hidden"
          style={{ background: '#F4632B' }}
        >
          <MapPin size={22} className="text-white mb-7" strokeWidth={2.2} />
          <div className="font-display font-bold text-white text-base leading-tight">Trouver<br/>du stock</div>
          <div className="text-[10px] text-white/80 mt-1 font-medium uppercase tracking-wider">Boutiques près</div>
        </button>
        <button
          onClick={() => setActiveTab('pharmacy')}
          className="rounded-2xl p-4 text-left relative overflow-hidden bg-white"
          style={{ border: '1px solid #DDE3EC' }}
        >
          <Cross size={22} className="mb-7 text-navy" strokeWidth={2.2} />
          <div className="font-display font-bold text-base leading-tight text-ink">Pharmacie<br/>de garde</div>
          <div className="text-[10px] mt-1 font-medium uppercase tracking-wider text-success">Ouvertes 24h</div>
        </button>
        <button
          onClick={() => onOpenSheet('report-fraud')}
          className="rounded-2xl p-4 text-left relative overflow-hidden bg-white"
          style={{ border: '1px solid #DDE3EC' }}
        >
          <AlertTriangle size={22} className="mb-7 text-orange" strokeWidth={2.2} />
          <div className="font-display font-bold text-base leading-tight text-ink">Signaler<br/>un écart</div>
          <div className="text-[10px] mt-1 font-medium uppercase tracking-wider text-slate">Anonyme</div>
        </button>
      </div>

      {/* Groupe d'achat (si présent) — cliquable */}
      {groupBuys.length > 0 && (
        <button
          onClick={() => onOpenSheet('join-group-buy', { group: groupBuys[0] })}
          className="anim-slide rounded-2xl overflow-hidden text-left w-full"
          style={{
            animationDelay: '100ms',
            background: 'linear-gradient(120deg, #FFA45B 0%, #F4632B 100%)',
          }}
        >
          <div className="p-4 flex items-center gap-3">
            <div className="w-12 h-12 rounded-xl bg-white/20 backdrop-blur flex items-center justify-center flex-shrink-0">
              <Users size={22} className="text-white" />
            </div>
            <div className="flex-1 text-white">
              <div className="text-[10px] font-bold uppercase tracking-wider opacity-90">Nouveau · Groupe d'achat</div>
              <div className="font-display font-bold text-sm leading-tight mt-0.5">
                {groupBuys[0].nb_members} voisins veulent du {groupBuys[0].product_name}
              </div>
              <div className="text-xs opacity-90 mt-0.5">{groupBuys[0].description}</div>
            </div>
            <ChevronRight size={18} className="text-white/80 flex-shrink-0" />
          </div>
        </button>
      )}

      {/* Prix du jour */}
      <div className="anim-slide" style={{ animationDelay: '140ms' }}>
        <div className="flex items-end justify-between mb-2.5 mt-1">
          <h2 className="font-display font-bold text-lg text-ink">Prix du jour</h2>
          <span className="text-[11px] font-medium text-slate">moyenne {state.user.neighborhood_slug ? 'quartier' : 'Dakar'}</span>
        </div>
        <Card>
          {products.length === 0 ? (
            <div className="p-6 text-center text-slate text-sm">
              Pas encore de prix cette semaine. Sois la première à en signaler un !
            </div>
          ) : (
            products.map((p, i) => {
              const diff = Math.round(p.avg_price - (p.price_official || p.avg_price));
              const overpriced = diff > 0;
              return (
                <button
                  key={i}
                  onClick={() => onOpenSheet('price-compare', { product_slug: p.slug })}
                  className={`w-full flex items-center gap-3 px-4 py-3.5 text-left active:bg-bg ${i < products.length - 1 ? 'border-b border-bg-2' : ''}`}
                >
                  <div className="w-10 h-10 rounded-xl flex items-center justify-center text-xl bg-bg">{p.icon}</div>
                  <div className="flex-1 min-w-0">
                    <div className="font-semibold text-sm text-ink">{p.name_fr}</div>
                    <div className="text-[11px] text-slate">{p.unit} · officiel {p.price_official} F</div>
                  </div>
                  <div className="text-right">
                    <div
                      className="font-display font-bold text-base"
                      style={{ color: overpriced ? '#F4632B' : '#0F1F36' }}
                    >
                      {Math.round(p.avg_price)} F
                    </div>
                    <div
                      className="flex items-center justify-end gap-0.5 text-[10px] font-medium"
                      style={{ color: overpriced ? '#F4632B' : diff < 0 ? '#15803D' : '#6B7891' }}
                    >
                      {overpriced ? <TrendingUp size={10} /> : diff < 0 ? <TrendingDown size={10} /> : null}
                      {overpriced ? `+${diff} F` : diff < 0 ? `${diff} F` : 'stable'}
                    </div>
                  </div>
                  <ChevronRight size={14} className="text-slate flex-shrink-0" />
                </button>
              );
            })
          )}
        </Card>

        {/* CTA Comparer — gros bouton pleine largeur */}
        <button
          onClick={() => onOpenSheet('price-compare', {})}
          className="w-full mt-3 rounded-2xl p-4 flex items-center gap-3 text-left relative overflow-hidden anim-slide"
          style={{
            background: 'linear-gradient(120deg, #102A43 0%, #1f3a5f 60%, #F4632B 130%)',
            animationDelay: '160ms',
          }}
        >
          <div className="absolute inset-0 grain opacity-15" />
          <div className="relative w-12 h-12 rounded-xl bg-white/15 backdrop-blur flex items-center justify-center flex-shrink-0">
            <Search size={22} className="text-white" strokeWidth={2.2} />
          </div>
          <div className="relative flex-1 text-white">
            <div className="font-display font-bold text-base leading-tight">Comparer les prix</div>
            <div className="text-xs opacity-90 mt-0.5">Trouve le moins cher près de chez toi</div>
          </div>
          <ChevronRight size={20} className="relative text-white/90 flex-shrink-0" />
        </button>
      </div>

      {/* Indice de confiance */}
      {trustIndex && (
        <Card className="anim-slide" noBar style={{ animationDelay: '180ms' }}>
          <div className="p-4 flex items-center gap-3">
            <div className="relative w-14 h-14 flex items-center justify-center">
              <svg className="absolute inset-0 -rotate-90" viewBox="0 0 56 56">
                <circle cx="28" cy="28" r="24" stroke="#EAEEF4" strokeWidth="4" fill="none"/>
                <circle
                  cx="28" cy="28" r="24"
                  stroke={trustIndex.score >= 0.7 ? '#15803D' : trustIndex.score >= 0.4 ? '#F4632B' : '#DC2626'}
                  strokeWidth="4" fill="none"
                  strokeDasharray={`${150 * trustIndex.score} 150`}
                  strokeLinecap="round"
                />
              </svg>
              <span className="font-display font-bold text-sm text-ink">{Math.round(trustIndex.score * 100)}%</span>
            </div>
            <div className="flex-1">
              <div className="text-[10px] font-bold uppercase tracking-wider text-slate">Indice de confiance</div>
              <div className="font-display font-bold text-base leading-tight text-ink">
                {trustIndex.neighborhood_name || 'Dakar'} cette semaine
              </div>
              <div className="text-[11px] mt-0.5 text-success">
                {trustIndex.honest_shops} boutiques honnêtes · {trustIndex.abuses} abus signalés
              </div>
            </div>
          </div>
        </Card>
      )}

    </div>
  );
};

// Export
window.OveyoPages = window.OveyoPages || {};
window.OveyoPages.HomePage = HomePage;
window.OveyoPages.TopBar = TopBar;
