const { useEffect, useState, useRef } = React;

function formatNumber(value) {
  return Number(value).toLocaleString('fr-FR');
}

function fetchJson(url) {
  return fetch(url).then((res) => {
    if (!res.ok) {
      throw new Error(`${res.status} ${res.statusText}`);
    }
    return res.json();
  });
}

function useQuartiers() {
  const [quartiers, setQuartiers] = useState([]);
  const [loadingQuartiers, setLoadingQuartiers] = useState(true);

  useEffect(() => {
    let active = true;

    fetchJson('/api/data')
      .then((data) => {
        if (!active) return;
        const names = [...new Set(data.map((item) => item.quartier).filter(Boolean))].sort();
        setQuartiers(names);
      })
      .catch(() => {
        if (active) setQuartiers([]);
      })
      .finally(() => {
        if (active) setLoadingQuartiers(false);
      });

    return () => {
      active = false;
    };
  }, []);

  return { quartiers, loadingQuartiers };
}

// Tile providers available for the map. Keys are stable identifiers used for
// persistence and switching at runtime.
const TILE_PROVIDERS = [
  { key: 'tileProxy', label: 'OSM proxy local', url: '/tiles/{z}/{x}/{y}.png', attribution: '© OpenStreetMap contributors' },
  { key: 'osm', label: 'OpenStreetMap', url: 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', attribution: '© OpenStreetMap contributors' },
  { key: 'osmfr', label: 'OSM France (osmfr)', url: 'https://tile.openstreetmap.fr/osmfr/{z}/{x}/{y}.png', attribution: '© OpenStreetMap contributors — osmfr' },
  { key: 'stamen', label: 'Stamen Toner', url: 'https://stamen-tiles.a.ssl.fastly.net/toner/{z}/{x}/{y}.png', attribution: 'Map tiles by Stamen' },
  { key: 'carto', label: 'Carto Voyager', url: 'https://cartodb-basemaps-a.global.ssl.fastly.net/rastertiles/voyager/{z}/{x}/{y}.png', attribution: '© Carto' },
  { key: 'embedded', label: 'Embedded (fallback)', url: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAgAAAAICAYAAADED76LAAAALUlEQVQoU2NkYGD4z0AEYBxVSFGBgYGBgYGBg+M8wMDAwMDAwMDAwMDAwMAAA5YQEuWqz8OAAAAAElFTkSuQmCC', attribution: 'Local fallback' }
];

// Custom simple router based on window location hash
function useHashRouter() {
  const normalizeHash = (hash) => {
    if (!hash) return '/';
    const normalized = hash.startsWith('#') ? hash.slice(1) : hash;
    if (normalized === '') return '/';
    if (normalized.endsWith('/') && normalized !== '/') {
      return normalized.slice(0, -1);
    }
    return normalized;
  };

  const [currentHash, setCurrentHash] = useState(normalizeHash(window.location.hash));

  useEffect(() => {
    const handleHashChange = () => {
      setCurrentHash(normalizeHash(window.location.hash));
    };
    window.addEventListener('hashchange', handleHashChange);
    return () => window.removeEventListener('hashchange', handleHashChange);
  }, []);

  return {
    go: (path) => {
      const normalizedPath = path.startsWith('/') ? path : `/${path}`;
      window.location.hash = normalizedPath;
    },
    path: currentHash,
  };
}

function Sidebar({ router, currentPath }) {
  const mapPaths = ['/', '/carte'];
  const isActive = (path) => {
    if (mapPaths.includes(path)) {
      return mapPaths.includes(currentPath);
    }
    return currentPath === path;
  };
  
  return (
    <aside className="sidebar w-[260px] self-start text-white flex flex-col border-r border-slate-800">
      <div className="h-20 flex items-center gap-3 px-4 border-b border-slate-800 shrink-0">
        <img src="/static/images/logo.png" alt="Logo PASTEF" className="w-10 h-10 rounded-xl" />
        <div className="leading-tight overflow-hidden">
          <h1 className="text-sm font-bold truncate">PASTEF</h1>
          <p className="text-xs text-slate-400 truncate">SIG Saint-Louis</p>
        </div>
      </div>
      <nav className="sidebar-nav py-4 flex flex-col gap-2 px-2 flex-1 overflow-y-auto">
        <div>
          <p className="text-xs uppercase text-slate-500 font-semibold px-2 mb-2">Navigation</p>
          <button 
            onClick={() => router.go('/carte')} 
            className={`nav-item flex items-center gap-3 h-11 px-4 rounded-xl w-full text-left transition-all ${isActive('/carte') ? 'bg-emerald-500 text-white' : 'text-slate-300 hover:bg-slate-800'}`}
          >
            <i className="fas fa-map"></i>
            <span>Carte interactive</span>
          </button>
          <button 
            onClick={() => router.go('/dashboard')} 
            className={`nav-item flex items-center gap-3 h-11 px-4 rounded-xl w-full text-left transition-all ${isActive('/dashboard') ? 'bg-emerald-500 text-white' : 'text-slate-300 hover:bg-slate-800'}`}
          >
            <i className="fas fa-chart-bar"></i>
            <span>Dashboard</span>
          </button>
          <button 
            onClick={() => router.go('/visites')} 
            className={`nav-item flex items-center gap-3 h-11 px-4 rounded-xl w-full text-left transition-all ${isActive('/visites') ? 'bg-emerald-500 text-white' : 'text-slate-300 hover:bg-slate-800'}`}
          >
            <i className="fas fa-calendar-check"></i>
            <span>Visites</span>
          </button>
          <button 
            onClick={() => router.go('/ventes')} 
            className={`nav-item flex items-center gap-3 h-11 px-4 rounded-xl w-full text-left transition-all ${isActive('/ventes') ? 'bg-emerald-500 text-white' : 'text-slate-300 hover:bg-slate-800'}`}
          >
            <i className="fas fa-shopping-cart"></i>
            <span>Ventes</span>
          </button>
          <button 
            onClick={() => router.go('/activites')} 
            className={`nav-item flex items-center gap-3 h-11 px-4 rounded-xl w-full text-left transition-all ${isActive('/activites') ? 'bg-emerald-500 text-white' : 'text-slate-300 hover:bg-slate-800'}`}
          >
            <i className="fas fa-users"></i>
            <span>Activités</span>
          </button>
        </div>
      </nav>
      <div className="px-4 py-6 border-t border-slate-800">
        <div className="profile-card flex items-center gap-3">
          <div className="avatar flex items-center justify-center w-8 h-8 bg-slate-700 rounded-lg font-semibold">A</div>
          <div>
            <p className="text-sm font-semibold text-slate-200">Admin SIG</p>
            <p className="text-xs text-slate-500">Administrateur</p>
          </div>
        </div>
      </div>
    </aside>
  );
}

function PageHeader({ title, subtitle }) {
  return (
    <div className="page-header flex flex-col gap-4 sm:flex-row sm:items-end sm:justify-between mb-8">
      <div>
        <h1 className="text-5xl font-black tracking-tight text-slate-900 leading-tight">{title}</h1>
        {subtitle ? <p className="text-slate-500 mt-3 max-w-3xl">{subtitle}</p> : null}
      </div>
    </div>
  );
}

function CartePage() {
  const [data, setData] = useState([]);
  const [stats, setStats] = useState(null);
  const [error, setError] = useState(null);
  const [tileProvider, setTileProvider] = useState(localStorage.getItem('tile_provider') || 'tileProxy');
  const mapRef = useRef(null);
  const leafletMap = useRef(null);
  const markers = useRef(null);

  useEffect(() => {
    async function loadPageData() {
      try {
        const [dataResult, statsResult] = await Promise.all([fetchJson('/api/data'), fetchJson('/api/stats')]);
        // Extract array from { data: [...] } response format
        setData(Array.isArray(dataResult) ? dataResult : (dataResult?.data || []));
        setStats(statsResult);
        if (window.enableLegacyDataAccess) {
          window.enableLegacyDataAccess();
        }
      } catch (err) {
        setError(err.message);
      }
    }
    loadPageData();
  }, []);

  useEffect(() => {
    if (!mapRef.current || leafletMap.current) return;

    leafletMap.current = L.map(mapRef.current, {
      center: [16.0326, -16.4818],
      zoom: 13,
      zoomControl: true,
    });

    // Use TILE_PROVIDERS list and expose a runtime switch to change provider.
    let providerIndex = 0;
    let currentLayer = null;
    let providerOk = false;

    function applyProviderByKey(key) {
      const p = TILE_PROVIDERS.find(t => t.key === key) || TILE_PROVIDERS[0];
      if (!leafletMap.current) return;
      try { if (currentLayer) leafletMap.current.removeLayer(currentLayer); } catch (e) {}
      providerOk = false;
      // Use tileSize small for embedded data URI provider
      const opts = p.key === 'embedded' ? { tileSize: 8, attribution: p.attribution } : { attribution: p.attribution };
      // Add a cache-busting query param for the local proxy provider to avoid stale/blocked tiles
      const url = p.key === 'tileProxy' ? `${p.url}?v=${Date.now()}` : p.url;
      currentLayer = L.tileLayer(url, opts);
      const onTileLoad = () => {
        providerOk = true;
        currentLayer.off('tileload', onTileLoad);
        currentLayer.off('tileerror', onTileError);
      };
      const onTileError = () => {
        setTimeout(() => {
          if (!providerOk && p.key !== 'embedded') {
            applyProviderByKey('embedded');
          }
        }, 800);
      };
      currentLayer.on('tileload', onTileLoad);
      currentLayer.on('tileerror', onTileError);
      currentLayer.addTo(leafletMap.current);
    }

    // Expose global switch for other code and for runtime changes
    window.setTileProvider = function (key) {
      try {
        applyProviderByKey(key);
      } catch (e) {
        applyProviderByKey('embedded');
      }
    };

    // apply initial provider (from persisted selection)
    try {
      window.setTileProvider(localStorage.getItem('tile_provider') || tileProvider || 'osm');
    } catch (e) { window.setTileProvider('embedded'); }

    markers.current = L.markerClusterGroup();
    leafletMap.current.addLayer(markers.current);

    // Force-add proxy TileLayer shortly after initialization to ensure tiles
    // are attached to the existing Leaflet instance even if provider logic failed.
    setTimeout(() => {
      try {
        if (leafletMap.current) {
          const forced = L.tileLayer('/tiles/{z}/{x}/{y}.png?v=' + Date.now(), {
            attribution: '&copy; OpenStreetMap contributors',
            maxZoom: 19
          }).addTo(leafletMap.current);
          try {
            // Ask Leaflet to redraw the forced layer and invalidate size
            if (typeof forced.redraw === 'function') forced.redraw();
            leafletMap.current.invalidateSize(true);
            // Update any already-created tile <img> elements to include a cache-busting param
            const now = Date.now();
            document.querySelectorAll('.leaflet-tile').forEach((img) => {
              try {
                if (img && img.src) {
                  const hasV = /[?&]v=/.test(img.src);
                  if (!hasV) {
                    img.src = img.src + (img.src.includes('?') ? '&' : '?') + 'v=' + now;
                  }
                }
              } catch (e) {}
            });
          } catch (e) {}
          // If tiles remain blocked, try switching to a different public provider
          try {
            if (window.setTileProvider) window.setTileProvider('carto');
          } catch (e) {}
        }
      } catch (e) {
        console.warn('Force tileLayer add failed', e);
      }
    }, 500);

    return () => {
      if (leafletMap.current) {
        leafletMap.current.remove();
        leafletMap.current = null;
      }
    };
  }, []);

  useEffect(() => {
    if (!markers.current || !leafletMap.current) return;
    if (!Array.isArray(data) || data.length === 0) return;

    markers.current.clearLayers();
    const markerItems = [];

    data.forEach((item) => {
      const lat = Number(item.latitude);
      const lng = Number(item.longitude);
      if (!Number.isFinite(lat) || !Number.isFinite(lng)) return;

      const marker = L.marker([lat, lng]);
      marker.bindPopup(`
        <div style="font-family: Inter, sans-serif; max-width: 220px;">
          <h3 style="margin: 0 0 8px 0; color: #007A33; font-size: 16px;">${item.quartier || 'Quartier inconnu'}</h3>
          <p style="margin: 4px 0; font-size: 14px;"><strong>Population :</strong> ${formatNumber(item.population)}</p>
          <p style="margin: 4px 0; font-size: 14px;"><strong>Cartes vendues :</strong> ${formatNumber(item.cartes_vendues)}</p>
          <p style="margin: 4px 0; font-size: 14px;"><strong>Montant :</strong> ${formatNumber(item.montant)} FCFA</p>
        </div>
      `);

      markers.current.addLayer(marker);
      markerItems.push(marker);
    });

    console.log('CartePage: data items=', data.length, 'markerItems=', markerItems.length);
    if (leafletMap.current) {
      try {
        // ensure map redraw and marker clusters are visible
        leafletMap.current.invalidateSize(true);
      } catch (e) {}
    }

    if (markerItems.length > 0) {
      // Keep the map centered and zoomed on Saint-Louis. Do not use automatic bounds fitting.
    }
  }, [data]);

  useEffect(() => {
    if (mapRef.current && leafletMap.current) {
      leafletMap.current.setView([16.0326, -16.4818], 13);
    }
  }, []);

  // When the React state `tileProvider` changes, instruct the map to switch provider.
  useEffect(() => {
    try {
      if (window.setTileProvider) {
        window.setTileProvider(tileProvider);
      }
      localStorage.setItem('tile_provider', tileProvider);
    } catch (e) {}
  }, [tileProvider]);


  return (
    <section className="flex flex-col gap-5">
      <PageHeader title="Carte Interactive" subtitle="Map et données géographiques Saint-Louis" />
      {error ? <div className="bg-red-100 border border-red-200 rounded-xl p-4 text-red-700">Erreur : {error}</div> : null}
      <div className="grid grid-cols-1 lg:grid-cols-[1.5fr_0.9fr] gap-5">
        <div className="card p-0 overflow-hidden bg-white rounded-[32px] shadow-xl border border-slate-100">
          <div className="map-panel border-b border-slate-100 bg-slate-50/50 px-6 py-4 flex items-center justify-between gap-4">
            <div>
              <p className="text-xs uppercase tracking-[0.24em] text-slate-400">Carte</p>
              <h3 className="text-xl font-semibold text-slate-900">Saint-Louis</h3>
            </div>
            <div className="flex items-center gap-3">
              <span className="inline-flex items-center gap-2 rounded-full bg-emerald-500/10 px-3 py-1 text-sm font-semibold text-emerald-700 ring-1 ring-emerald-500/20">● Live</span>
              <button className="btn-secondary btn-sm">Layers</button>
            </div>
          </div>
          <div className="map-container w-full">
            <div ref={mapRef} className="map w-full relative overflow-hidden bg-white" style={{ minHeight: '650px' }}></div>
          </div>
        </div>
        <div className="space-y-5">
          <div className="card p-5">
            <h2 className="text-lg font-semibold text-slate-900 mb-4">Statistiques géographiques</h2>
            {stats ? (
              <div className="grid grid-cols-1 gap-4">
                <div className="bg-slate-50 rounded-2xl p-4 border border-slate-200">
                  <p className="text-sm text-slate-500">Quartiers analysés</p>
                  <p className="text-3xl font-bold text-slate-900">{formatNumber(stats.quartiers_count)}</p>
                </div>
                <div className="bg-slate-50 rounded-2xl p-4 border border-slate-200">
                  <p className="text-sm text-slate-500">Population totale</p>
                  <p className="text-3xl font-bold text-slate-900">{formatNumber(stats.population_totale)}</p>
                </div>
                <div className="bg-slate-50 rounded-2xl p-4 border border-slate-200">
                  <p className="text-sm text-slate-500">Montant total</p>
                  <p className="text-3xl font-bold text-slate-900">{formatNumber(stats.ventes_total)} FCFA</p>
                </div>
                <div className="bg-slate-50 rounded-2xl p-4 border border-slate-200">
                  <p className="text-sm text-slate-500">Taux de couverture</p>
                  <p className="text-3xl font-bold text-slate-900">{stats.couverture_pct ?? 0}%</p>
                </div>
              </div>
            ) : (
              <p className="text-sm text-slate-500">Chargement des statistiques...</p>
            )}
          </div>
          <div className="card p-5">
            <h2 className="text-lg font-semibold text-slate-900 mb-4">Filtres associés</h2>
            <div className="grid grid-cols-1 gap-4">
              <label className="text-sm font-medium text-slate-700">Quartier</label>
              <select className="input-field">
                <option>Tous les quartiers</option>
                {data.slice(0, 8).map((item, index) => (
                  <option key={index} value={item.quartier}>{item.quartier || 'Inconnu'}</option>
                ))}
              </select>
              <label className="text-sm font-medium text-slate-700">Type</label>
              <select className="input-field">
                <option>Toutes les couches</option>
                <option>URBAIN</option>
                <option>RURAL</option>
              </select>
              <label className="text-sm font-medium text-slate-700">Fond de carte</label>
              <select className="input-field" value={tileProvider} onChange={(e) => setTileProvider(e.target.value)}>
                {TILE_PROVIDERS.map((p) => (
                  <option key={p.key} value={p.key}>{p.label}</option>
                ))}
              </select>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

function DashboardPage() {
  const [stats, setStats] = useState(null);
  const [data, setData] = useState([]);
  const [error, setError] = useState(null);
  const chartRef = useRef(null);
  const chartInstance = useRef(null);

  useEffect(() => {
    async function loadStats() {
      try {
        const [statsResult, dataResult] = await Promise.all([fetchJson('/api/stats'), fetchJson('/api/data')]);
        setStats(statsResult);
        setData(Array.isArray(dataResult) ? dataResult : (dataResult?.data || []));
      } catch (err) {
        setError(err.message);
      }
    }
    loadStats();
  }, []);

  useEffect(() => {
    if (!chartRef.current || !data.length) return;
    const phases = ['Jan', 'Fév', 'Mar', 'Avr', 'Mai', 'Juin'];
    const values = [12, 18, 26, 23, 29, data.length];
    if (chartInstance.current) {
      chartInstance.current.destroy();
    }
    chartInstance.current = new Chart(chartRef.current, {
      type: 'line',
      data: {
        labels: phases,
        datasets: [{
          label: 'Evolution des quartiers',
          data: values,
          borderColor: '#10b981',
          backgroundColor: 'rgba(16, 185, 129, 0.15)',
          fill: true,
          tension: 0.3,
        }],
      },
      options: {
        responsive: true,
        plugins: {
          legend: { display: false },
        },
        scales: {
          x: { grid: { display: false } },
          y: { beginAtZero: true },
        },
      },
    });
  }, [data]);

  return (
    <section className="flex flex-col gap-5">
      <PageHeader title="Dashboard" subtitle="KPIs et analytics globaux" />
      {error ? <div className="bg-red-100 border border-red-200 rounded-xl p-4 text-red-700">Erreur : {error}</div> : null}
      <div className="grid grid-cols-1 xl:grid-cols-4 gap-5">
        <div className="card p-5">
          <p className="text-sm text-slate-500">Population totale</p>
          <p className="text-3xl font-bold text-slate-900">{stats ? formatNumber(stats.population_totale) : '...'}</p>
        </div>
        <div className="card p-5">
          <p className="text-sm text-slate-500">Quartiers suivis</p>
          <p className="text-3xl font-bold text-slate-900">{stats ? formatNumber(stats.quartiers_count) : '...'}</p>
        </div>
        <div className="card p-5">
          <p className="text-sm text-slate-500">Total ventes</p>
          <p className="text-3xl font-bold text-slate-900">{stats ? formatNumber(stats.ventes_total) + ' FCFA' : '...'}</p>
        </div>
        <div className="card p-5">
          <p className="text-sm text-slate-500">Couverture</p>
          <p className="text-3xl font-bold text-slate-900">{stats ? `${stats.couverture_pct ?? 0}%` : '...'}</p>
        </div>
      </div>
      <div className="grid grid-cols-1 lg:grid-cols-[0.7fr_1.3fr] gap-5">
        <div className="card p-5">
          <h2 className="text-lg font-semibold text-slate-900 mb-4">Statistiques globales</h2>
          <div className="space-y-4">
            <div className="flex items-center justify-between gap-4 bg-slate-50 rounded-2xl p-4 border border-slate-200">
              <span className="text-sm text-slate-500">Taux de couverture</span>
              <strong className="text-xl text-slate-900">{stats ? `${stats.couverture_pct ?? 0}%` : '...'}</strong>
            </div>
            <div className="flex items-center justify-between gap-4 bg-slate-50 rounded-2xl p-4 border border-slate-200">
              <span className="text-sm text-slate-500">Quartiers nouveaux</span>
              <strong className="text-xl text-slate-900">{stats ? formatNumber(stats.quartiers_count) : '...'}</strong>
            </div>
            <div className="flex items-center justify-between gap-4 bg-slate-50 rounded-2xl p-4 border border-slate-200">
              <span className="text-sm text-slate-500">Valeur moyenne par quartier</span>
              <strong className="text-xl text-slate-900">{stats ? formatNumber(Math.round(stats.ventes_total / Math.max(stats.quartiers_count, 1))) : '...'}</strong>
            </div>
          </div>
        </div>
        <div className="card p-5">
          <h2 className="text-lg font-semibold text-slate-900 mb-4">Tendance</h2>
          <canvas ref={chartRef} height="180"></canvas>
        </div>
      </div>
    </section>
  );
}

function VisitesPage() {
  const [visites, setVisites] = useState([]);
  const [error, setError] = useState(null);
  const { quartiers, loadingQuartiers } = useQuartiers();

  useEffect(() => {
    fetchJson('/api/visites')
      .then((res) => {
        // Extract array from response if needed
        setVisites(Array.isArray(res) ? res : (res?.visites || []));
      })
      .catch((err) => setError(err.message));
  }, []);

  return (
    <section className="flex flex-col gap-5">
      <PageHeader title="Visites" subtitle="Toutes les visites terrain" />
      {error ? <div className="bg-red-100 border border-red-200 rounded-xl p-4 text-red-700">Erreur : {error}</div> : null}
      <div className="grid grid-cols-1 lg:grid-cols-[1.2fr_0.8fr] gap-5">
        <div className="card p-5">
          <h2 className="text-lg font-semibold text-slate-900 mb-4">Liste des visites</h2>
          <div className="space-y-4">
            {visites.length === 0 ? (
              <p className="text-slate-500">Aucune visite enregistrée.</p>
            ) : (
              visites.map((visite) => (
                <div key={visite.id} className="rounded-2xl border border-slate-200 bg-slate-50 p-4">
                  <div className="flex items-center justify-between">
                    <strong className="text-slate-900">{visite.quartier || 'Quartier inconnu'}</strong>
                    <span className="text-sm text-slate-500">{visite.date_visite || 'Date indisponible'}</span>
                  </div>
                  <p className="text-sm text-slate-600 mt-2">Statut : {visite.statut || 'N/A'}</p>
                  <p className="text-sm text-slate-500 mt-2">Notes : {visite.notes || 'Aucune note'}</p>
                </div>
              ))
            )}
          </div>
        </div>
        <div className="space-y-5">
          <div className="card p-5">
            <h2 className="text-lg font-semibold text-slate-900 mb-4">Statistiques visites</h2>
            <p className="text-sm text-slate-500 mb-4">Nombre total de visites enregistrées</p>
            <div className="rounded-2xl bg-slate-50 p-5 border border-slate-200">
              <p className="text-4xl font-bold text-slate-900">{visites.length}</p>
            </div>
          </div>
          <div className="card p-5">
            <h2 className="text-lg font-semibold text-slate-900 mb-4">Nouvelle visite</h2>
            <form id="visites-form" className="space-y-4">
              <div>
                <label htmlFor="visite-quartier" className="block text-sm font-medium text-slate-700">Quartier</label>
                <select id="visite-quartier" name="quartier" required className="input-field mt-2 w-full">
                  {loadingQuartiers ? (
                    <option value="">Chargement des quartiers...</option>
                  ) : (
                    <>
                      <option value="">Sélectionner quartier</option>
                      {quartiers.map((quartier) => (
                        <option key={quartier} value={quartier}>{quartier}</option>
                      ))}
                    </>
                  )}
                </select>
              </div>
              <div>
                <label htmlFor="visite-date" className="block text-sm font-medium text-slate-700">Date de visite</label>
                <input id="visite-date" name="date" type="date" required className="input-field mt-2 w-full" />
              </div>
              <div>
                <label htmlFor="visite-statut" className="block text-sm font-medium text-slate-700">Statut</label>
                <select id="visite-statut" name="statut" required className="input-field mt-2 w-full">
                  <option value="">Sélectionner un statut</option>
                  <option value="planifiee">Planifiée</option>
                  <option value="realisee">Réalisée</option>
                  <option value="annulee">Annulée</option>
                </select>
              </div>
              <div>
                <button type="submit" className="btn-primary w-full">Enregistrer la visite</button>
              </div>
            </form>
          </div>
        </div>
      </div>
    </section>
  );
}

function VentesPage() {
  const [ventes, setVentes] = useState([]);
  const [error, setError] = useState(null);
  const { quartiers, loadingQuartiers } = useQuartiers();

  useEffect(() => {
    fetchJson('/api/ventes')
      .then((res) => {
        // Extract array from response if needed
        setVentes(Array.isArray(res) ? res : (res?.ventes || []));
      })
      .catch((err) => setError(err.message));
  }, []);

  const totalMontant = ventes.reduce((sum, vente) => sum + Number(vente.montant || 0), 0);
  const totalCartes = ventes.reduce((sum, vente) => sum + Number(vente.cartes || 0), 0);

  return (
    <section className="flex flex-col gap-5">
      <PageHeader title="Ventes" subtitle="Suivi des transactions" />
      {error ? <div className="bg-red-100 border border-red-200 rounded-xl p-4 text-red-700">Erreur : {error}</div> : null}
      <div className="grid grid-cols-1 xl:grid-cols-3 gap-5">
        <div className="card p-5">
          <p className="text-sm text-slate-500">Transactions</p>
          <p className="text-3xl font-bold text-slate-900">{ventes.length}</p>
        </div>
        <div className="card p-5">
          <p className="text-sm text-slate-500">Total cartes</p>
          <p className="text-3xl font-bold text-slate-900">{formatNumber(totalCartes)}</p>
        </div>
        <div className="card p-5">
          <p className="text-sm text-slate-500">Montant total</p>
          <p className="text-3xl font-bold text-slate-900">{formatNumber(totalMontant)} FCFA</p>
        </div>
      </div>
      <div className="grid grid-cols-1 lg:grid-cols-[0.75fr_1fr] gap-5">
        <div className="card p-5">
          <h2 className="text-lg font-semibold text-slate-900 mb-4">Historique des ventes</h2>
          <div className="space-y-4">
            {ventes.length === 0 ? (
              <p className="text-slate-500">Aucune vente enregistrée.</p>
            ) : (
              ventes.map((vente) => (
                <div key={vente.id} className="rounded-2xl border border-slate-200 bg-slate-50 p-4">
                  <div className="flex items-center justify-between gap-4">
                    <strong className="text-slate-900">{vente.quartier || 'Quartier inconnu'}</strong>
                    <span className="text-sm text-slate-500">{vente.cartes || 0} cartes</span>
                  </div>
                  <p className="text-sm text-slate-600 mt-2">Montant : {formatNumber(vente.montant || 0)} FCFA</p>
                  <p className="text-sm text-slate-500 mt-2">Date : {vente.date || 'N/A'}</p>
                </div>
              ))
            )}
          </div>
        </div>
        <div className="card p-5">
          <h2 className="text-lg font-semibold text-slate-900 mb-4">Nouvelle vente</h2>
          <form id="ventes-form" className="space-y-4">
            <div>
              <label htmlFor="vente-quartier" className="block text-sm font-medium text-slate-700">Quartier</label>
              <select id="vente-quartier" name="quartier" required className="input-field mt-2 w-full">
                {loadingQuartiers ? (
                  <option value="">Chargement des quartiers...</option>
                ) : (
                  <>
                    <option value="">Sélectionner quartier</option>
                    {quartiers.map((quartier) => (
                      <option key={quartier} value={quartier}>{quartier}</option>
                    ))}
                  </>
                )}
              </select>
            </div>
            <div>
              <label htmlFor="vente-cartes" className="block text-sm font-medium text-slate-700">Nombre de cartes</label>
              <input id="vente-cartes" name="cartes" type="number" min="1" required className="input-field mt-2 w-full" />
            </div>
            <div>
              <label htmlFor="vente-montant" className="block text-sm font-medium text-slate-700">Montant (FCFA)</label>
              <input id="vente-montant" name="montant" type="number" min="1" required className="input-field mt-2 w-full" />
            </div>
            <div>
              <button type="submit" className="btn-primary w-full">Enregistrer la vente</button>
            </div>
          </form>
        </div>
      </div>
    </section>
  );
}

function ActivitesPage() {
  const [activites, setActivites] = useState([]);
  const [error, setError] = useState(null);
  const { quartiers, loadingQuartiers } = useQuartiers();

  useEffect(() => {
    fetchJson('/api/activites')
      .then((res) => {
        // Extract array from response if needed
        setActivites(Array.isArray(res) ? res : (res?.activites || []));
      })
      .catch((err) => setError(err.message));
  }, []);

  return (
    <section className="flex flex-col gap-5">
      <PageHeader title="Activités" subtitle="Événements et actions terrain" />
      {error ? <div className="bg-red-100 border border-red-200 rounded-xl p-4 text-red-700">Erreur : {error}</div> : null}
      <div className="grid grid-cols-1 lg:grid-cols-[1.2fr_0.8fr] gap-5">
        <div className="card p-5">
          <h2 className="text-lg font-semibold text-slate-900 mb-4">Liste des activités</h2>
          <div className="space-y-4">
            {activites.length === 0 ? (
              <p className="text-slate-500">Aucune activité enregistrée.</p>
            ) : (
              activites.map((activite) => (
                <div key={activite.id} className="rounded-2xl border border-slate-200 bg-slate-50 p-4">
                  <div className="flex items-center justify-between gap-4">
                    <strong className="text-slate-900">{activite.quartier || 'Quartier inconnu'}</strong>
                    <span className="text-sm text-slate-500">{activite.type_activite || activite.type || 'Type inconnu'}</span>
                  </div>
                  <p className="text-sm text-slate-600 mt-2">Participants : {activite.participants || 'N/A'}</p>
                  <p className="text-sm text-slate-500 mt-2">Date : {activite.date || 'N/A'}</p>
                </div>
              ))
            )}
          </div>
        </div>
        <div className="space-y-5">
          <div className="card p-5">
            <h2 className="text-lg font-semibold text-slate-900 mb-4">Statistiques activités</h2>
            <div className="space-y-4">
              <div className="rounded-2xl bg-slate-50 p-5 border border-slate-200">
                <p className="text-sm text-slate-500">Total activités</p>
                <p className="text-3xl font-bold text-slate-900">{activites.length}</p>
              </div>
              <div className="rounded-2xl bg-slate-50 p-5 border border-slate-200">
                <p className="text-sm text-slate-500">Participants totaux</p>
                <p className="text-3xl font-bold text-slate-900">{activites.reduce((sum, item) => sum + Number(item.participants || 0), 0)}</p>
              </div>
            </div>
          </div>
          <div className="card p-5">
            <h2 className="text-lg font-semibold text-slate-900 mb-4">Nouvelle activité</h2>
            <form id="activites-form" className="space-y-4">
              <div>
                <label htmlFor="activite-type" className="block text-sm font-medium text-slate-700">Type d'activité</label>
                <input id="activite-type" name="type" type="text" required className="input-field mt-2 w-full" />
              </div>
              <div>
                <label htmlFor="activite-quartier" className="block text-sm font-medium text-slate-700">Quartier</label>
                <select id="activite-quartier" name="quartier" required className="input-field mt-2 w-full">
                  {loadingQuartiers ? (
                    <option value="">Chargement des quartiers...</option>
                  ) : (
                    <>
                      <option value="">Sélectionner quartier</option>
                      {quartiers.map((quartier) => (
                        <option key={quartier} value={quartier}>{quartier}</option>
                      ))}
                    </>
                  )}
                </select>
              </div>
              <div>
                <label htmlFor="activite-participants" className="block text-sm font-medium text-slate-700">Participants</label>
                <input id="activite-participants" name="participants" type="number" min="1" required className="input-field mt-2 w-full" />
              </div>
              <div>
                <button type="submit" className="btn-primary w-full">Enregistrer l'activité</button>
              </div>
            </form>
          </div>
        </div>
      </div>
    </section>
  );
}

function App() {
  const router = useHashRouter();
  const path = router.path.split('?')[0] || '/';

  const renderPage = () => {
    switch (path) {
      case '/':
      case '/carte':
        return <CartePage />;
      case '/dashboard':
        return <DashboardPage />;
      case '/visites':
        return <VisitesPage />;
      case '/ventes':
        return <VentesPage />;
      case '/activites':
        return <ActivitesPage />;
      default:
        return <CartePage />;
    }
  };

  return (
    <div className="flex min-h-screen bg-[#f4f7fb]">
      <Sidebar router={router} currentPath={path} />
      <main className="app-main flex-1 overflow-auto">
        {renderPage()}
      </main>
    </div>
  );
}

const root = ReactDOM.createRoot(document.getElementById('react-root'));
root.render(<App />);
