// gov-page.jsx — APIs Gouvernementales : SIRENE · BAN · Cadastre · Catalogue FROST
// Portage de pg-gov (audits-energies.html) vers design-v1

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

/* ─── Catalogue FROST complet (extrait de audits-energies.html) ────────────── */
const FROST_CATALOGUE = [
  {code:'BAT-TH-134',desc:'Régulation HP flottante — froid commercial tertiaire',filiere:'BAT',priority:true},
  {code:'BAT-TH-139',desc:'Récupération de chaleur sur groupe de production de froid',filiere:'BAT',priority:true},
  {code:'BAT-TH-145',desc:'Régulation BP flottante — froid tertiaire',filiere:'BAT',priority:true},
  {code:'BAT-TH-116',desc:'Système de gestion technique du bâtiment / GTB tertiaire',filiere:'BAT',priority:true},
  {code:'BAT-TH-113',desc:'PAC air/eau ou eau/eau tertiaire — chauffage et ECS',filiere:'BAT',priority:true},
  {code:'BAT-TH-129',desc:'PAC air/air — système multi-split ou VRF tertiaire',filiere:'BAT',priority:true},
  {code:'BAT-TH-127',desc:'VMC à double flux hygroréglable en bâtiment tertiaire',filiere:'BAT',priority:false},
  {code:'BAT-TH-142',desc:'Déstratificateur d\'air ou brasseur grand volume',filiere:'BAT',priority:false},
  {code:'BAT-TH-143',desc:'Ventilo-convecteur à moteur brushless haute performance',filiere:'BAT',priority:false},
  {code:'BAT-TH-156',desc:'Système de freecooling par eau glacée',filiere:'BAT',priority:false},
  {code:'BAT-TH-153',desc:'Confinement des baies informatiques — data center',filiere:'BAT',priority:false},
  {code:'BAT-TH-102',desc:'Isolation des combles perdus par soufflage',filiere:'BAT',priority:false},
  {code:'BAT-TH-104',desc:'Isolation des murs par l\'extérieur (ITE)',filiere:'BAT',priority:false},
  {code:'BAT-TH-146',desc:'Déstratification air intérieur — grande hauteur',filiere:'BAT',priority:false},
  {code:'BAT-EQ-117',desc:'Éclairage intérieur LED — bâtiment tertiaire',filiere:'BAT-EQ',priority:true},
  {code:'BAT-EQ-134',desc:'Meubles frigorifiques à haute performance énergétique',filiere:'BAT-EQ',priority:true},
  {code:'BAR-TH-129',desc:'PAC air/eau résidentiel — chauffage + ECS',filiere:'BAR',priority:false},
  {code:'BAR-TH-143',desc:'CET thermodynamique (chauffe-eau thermodynamique)',filiere:'BAR',priority:false},
  {code:'BAR-TH-102',desc:'Isolation combles perdus résidentiel',filiere:'BAR',priority:false},
  {code:'IND-UT-102',desc:'Récupération de chaleur sur effluents industriels',filiere:'IND',priority:true},
  {code:'IND-UT-115',desc:'Isolation des réseaux de vapeur / fluides chauds process',filiere:'IND',priority:true},
  {code:'IND-UT-116',desc:'Régulation BP flottante — process industriel',filiere:'IND',priority:false},
  {code:'IND-UT-113',desc:'Remplacement moteur électrique haute efficacité IE3/IE4',filiere:'IND',priority:false},
  {code:'AGR-BA-102',desc:'Isolation thermique de bâtiments agricoles',filiere:'AGR',priority:false},
];

const FILIERE_COLORS = {
  'BAT':   { bg:'#3b5bdb18', text:'#3b5bdb' },
  'BAT-EQ':{ bg:'#00c48c18', text:'#00c48c' },
  'BAR':   { bg:'#f59e0b18', text:'#b45309' },
  'IND':   { bg:'#ef444418', text:'#dc2626' },
  'AGR':   { bg:'#22c55e18', text:'#16a34a' },
};

/* ─── Debounce helper ────────────────────────────────────────────────────────── */
function useDebounce(fn, delay) {
  const timer = useRef(null);
  return useCallback((...args) => {
    clearTimeout(timer.current);
    timer.current = setTimeout(() => fn(...args), delay);
  }, [fn, delay]);
}

/* ─── Autocomplete Entreprise (SIRENE) ──────────────────────────────────────── */
function EntrepriseSearch({ onSelect }) {
  const [query, setQuery] = useState('');
  const [results, setResults] = useState([]);
  const [loading, setLoading] = useState(false);
  const [selected, setSelected] = useState(null);
  const [open, setOpen] = useState(false);
  const ref = useRef(null);

  const doSearch = useCallback(async (q) => {
    if (q.length < 2) { setResults([]); return; }
    setLoading(true);
    try {
      const data = await window.AE_API.fetch(`/api/gov/entreprises?q=${encodeURIComponent(q)}&limit=8`);
      setResults(data?.results || []);
      setOpen(true);
    } catch { setResults([]); }
    finally { setLoading(false); }
  }, []);

  const debouncedSearch = useDebounce(doSearch, 320);

  const handleChange = (e) => {
    const v = e.target.value;
    setQuery(v);
    setSelected(null);
    debouncedSearch(v);
  };

  const handleSelect = (r) => {
    const nom = r.nom_complet || r.nom_raison_sociale || r.nom || query;
    const siret = r.siege?.siret || r.matching_etablissements?.[0]?.siret || '';
    const adresse = r.siege?.adresse || '';
    const naf = r.siege?.activite_principale || r.activite_principale || '';
    const item = { nom, siret, adresse, naf, raw: r };
    setSelected(item);
    setQuery(nom);
    setOpen(false);
    onSelect?.(item);
  };

  useEffect(() => {
    const onOut = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', onOut);
    return () => document.removeEventListener('mousedown', onOut);
  }, []);

  return (
    <div ref={ref} style={{position:'relative'}}>
      <div style={{position:'relative'}}>
        <input
          className="fi"
          value={query}
          onChange={handleChange}
          onFocus={() => results.length && setOpen(true)}
          placeholder="Ex: Carrefour, BITZER, Froid Express…"
          autoComplete="off"
        />
        {loading && <span style={{position:'absolute',right:10,top:'50%',transform:'translateY(-50%)',fontSize:11,color:'var(--t2)'}}>⏳</span>}
      </div>
      {open && results.length > 0 && (
        <div style={{position:'absolute',top:'calc(100% + 4px)',left:0,right:0,background:'var(--bg2)',border:'1px solid var(--border)',borderRadius:8,boxShadow:'0 8px 24px rgba(0,0,0,.12)',zIndex:200,maxHeight:280,overflowY:'auto'}}>
          {results.map((r,i) => {
            const nom = r.nom_complet || r.nom_raison_sociale || r.nom || '–';
            const siret = r.siege?.siret || r.matching_etablissements?.[0]?.siret || '';
            const ville = r.siege?.commune || '';
            return (
              <div key={i} onClick={() => handleSelect(r)} style={{padding:'9px 14px',cursor:'pointer',borderBottom:'1px solid var(--border)',transition:'background .15s'}}
                onMouseEnter={e=>e.currentTarget.style.background='var(--bg3)'}
                onMouseLeave={e=>e.currentTarget.style.background=''}>
                <div style={{fontWeight:600,fontSize:12}}>{nom}</div>
                <div style={{fontSize:10,color:'var(--t2)',marginTop:2}}>{siret && `SIRET: ${siret}`} {ville && `· ${ville}`}</div>
              </div>
            );
          })}
        </div>
      )}
      {selected && (
        <div style={{marginTop:8,padding:'10px 12px',background:'var(--signal-tint)',borderRadius:8,border:'1px solid var(--signal)',fontSize:11}}>
          <div style={{fontWeight:700,fontSize:12,marginBottom:4}}>🏢 {selected.nom}</div>
          {selected.siret && <div style={{color:'var(--t2)'}}>SIRET : <strong>{selected.siret}</strong></div>}
          {selected.adresse && <div style={{color:'var(--t2)'}}>{selected.adresse}</div>}
          {selected.naf && <div style={{color:'var(--t2)'}}>NAF : {selected.naf}</div>}
          <div style={{marginTop:6,display:'flex',gap:6}}>
            <button className="btn b-ghost" style={{fontSize:10,padding:'2px 8px'}}
              onClick={() => window.AE_NAV?.('crm')}>👤 Voir CRM</button>
            <button className="btn b-ghost" style={{fontSize:10,padding:'2px 8px'}}
              onClick={() => { navigator.clipboard?.writeText(selected.siret); }}>📋 Copier SIRET</button>
          </div>
        </div>
      )}
    </div>
  );
}

/* ─── Recherche par SIRET ───────────────────────────────────────────────────── */
function SiretSearch({ onSelect }) {
  const [siret, setSiret] = useState('');
  const [result, setResult] = useState(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  const handleSearch = async () => {
    const s = siret.replace(/\s/g, '');
    if (!/^\d{14}$/.test(s)) { setError('SIRET invalide (14 chiffres)'); return; }
    setError(''); setLoading(true);
    try {
      const data = await window.AE_API.fetch(`/api/gov/siret/${s}`);
      const r = data?.results?.[0];
      if (!r) { setError('Entreprise non trouvée'); setResult(null); return; }
      const item = {
        nom: r.nom_complet || r.nom_raison_sociale || r.nom || '–',
        siret: r.siege?.siret || s,
        adresse: r.siege?.adresse || '',
        naf: r.siege?.activite_principale || '',
      };
      setResult(item);
      onSelect?.(item);
    } catch { setError('Erreur API'); }
    finally { setLoading(false); }
  };

  return (
    <div>
      <div style={{display:'flex',gap:6}}>
        <input className="fi" value={siret} onChange={e=>setSiret(e.target.value)} placeholder="14 chiffres…"
          onKeyDown={e=>e.key==='Enter'&&handleSearch()} style={{flex:1}} maxLength={18} />
        <button className="btn b-primary" onClick={handleSearch} disabled={loading} style={{whiteSpace:'nowrap'}}>
          {loading ? '…' : '🔍 Chercher'}
        </button>
      </div>
      {error && <div style={{fontSize:11,color:'var(--rouge)',marginTop:6}}>{error}</div>}
      {result && (
        <div style={{marginTop:8,padding:'10px 12px',background:'var(--signal-tint)',borderRadius:8,border:'1px solid var(--signal)',fontSize:11}}>
          <div style={{fontWeight:700,fontSize:12,marginBottom:4}}>🏢 {result.nom}</div>
          {result.adresse && <div style={{color:'var(--t2)'}}>{result.adresse}</div>}
          {result.naf && <div style={{color:'var(--t2)'}}>NAF : {result.naf}</div>}
        </div>
      )}
    </div>
  );
}

/* ─── Autocomplete Adresse (BAN) ────────────────────────────────────────────── */
function AdresseSearch({ onSelect, placeholder }) {
  const [query, setQuery] = useState('');
  const [results, setResults] = useState([]);
  const [open, setOpen] = useState(false);
  const [loading, setLoading] = useState(false);
  const [selected, setSelected] = useState(null);
  const ref = useRef(null);

  const doSearch = useCallback(async (q) => {
    if (q.length < 3) { setResults([]); return; }
    setLoading(true);
    try {
      const data = await window.AE_API.fetch(`/api/gov/adresses?q=${encodeURIComponent(q)}&limit=6`);
      setResults(data?.features || []);
      setOpen(true);
    } catch { setResults([]); }
    finally { setLoading(false); }
  }, []);

  const debouncedSearch = useDebounce(doSearch, 300);

  const handleChange = (e) => {
    const v = e.target.value; setQuery(v); setSelected(null); debouncedSearch(v);
  };

  const handleSelect = (f) => {
    const label = f.properties?.label || '';
    const lat = f.geometry?.coordinates?.[1];
    const lon = f.geometry?.coordinates?.[0];
    setQuery(label); setOpen(false);
    const item = { label, lat, lon };
    setSelected(item);
    onSelect?.(item);
  };

  useEffect(() => {
    const onOut = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', onOut);
    return () => document.removeEventListener('mousedown', onOut);
  }, []);

  return (
    <div ref={ref} style={{position:'relative'}}>
      <div style={{position:'relative'}}>
        <input className="fi" value={query} onChange={handleChange}
          onFocus={() => results.length && setOpen(true)}
          placeholder={placeholder || 'Rue, ville…'} autoComplete="off" />
        {loading && <span style={{position:'absolute',right:10,top:'50%',transform:'translateY(-50%)',fontSize:11,color:'var(--t2)'}}>⏳</span>}
      </div>
      {open && results.length > 0 && (
        <div style={{position:'absolute',top:'calc(100% + 4px)',left:0,right:0,background:'var(--bg2)',border:'1px solid var(--border)',borderRadius:8,boxShadow:'0 8px 24px rgba(0,0,0,.12)',zIndex:200,maxHeight:240,overflowY:'auto'}}>
          {results.map((f,i) => (
            <div key={i} onClick={() => handleSelect(f)}
              style={{padding:'8px 14px',cursor:'pointer',borderBottom:'1px solid var(--border)',fontSize:12,transition:'background .15s'}}
              onMouseEnter={e=>e.currentTarget.style.background='var(--bg3)'}
              onMouseLeave={e=>e.currentTarget.style.background=''}>
              <div style={{fontWeight:600}}>{f.properties?.label}</div>
              <div style={{fontSize:10,color:'var(--t2)',marginTop:2}}>
                {f.properties?.postcode} {f.properties?.city} · {f.properties?.type}
              </div>
            </div>
          ))}
        </div>
      )}
      {selected && (
        <div style={{marginTop:6,fontSize:11,color:'var(--t2)'}}>
          📍 {selected.label} &nbsp;·&nbsp; lat: <strong>{selected.lat?.toFixed(5)}</strong> &nbsp; lon: <strong>{selected.lon?.toFixed(5)}</strong>
        </div>
      )}
    </div>
  );
}

/* ─── Carte Leaflet + Cadastre ──────────────────────────────────────────────── */
function CadastreMap({ center, onParcelle }) {
  const mapRef = useRef(null);
  const leafletMap = useRef(null);
  const markerRef = useRef(null);
  const parcelleLayer = useRef(null);

  useEffect(() => {
    if (!window.L || leafletMap.current) return;
    leafletMap.current = window.L.map(mapRef.current, { center: [46.5, 2.5], zoom: 5 });
    window.L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
      attribution: '© OpenStreetMap',
      maxZoom: 20,
    }).addTo(leafletMap.current);
    // IGN orthophoto overlay
    window.L.tileLayer(
      'https://data.geopf.fr/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=ORTHOIMAGERY.ORTHOPHOTOS&STYLE=normal&TILEMATRIXSET=PM&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&FORMAT=image%2Fjpeg',
      { maxZoom: 20, opacity: 0, attribution: '© IGN' }
    ).addTo(leafletMap.current);

    leafletMap.current.on('click', async (e) => {
      const { lat, lng } = e.latlng;
      if (markerRef.current) markerRef.current.remove();
      markerRef.current = window.L.marker([lat, lng]).addTo(leafletMap.current);
      try {
        const data = await window.AE_API.fetch(`/api/gov/cadastre?lat=${lat}&lon=${lng}`);
        if (parcelleLayer.current) parcelleLayer.current.remove();
        if (data?.features?.length) {
          parcelleLayer.current = window.L.geoJSON(data, {
            style: { color: '#3b5bdb', weight: 2, fillOpacity: 0.15 },
          }).addTo(leafletMap.current);
          onParcelle?.(data.features[0]?.properties);
        }
      } catch { /* ignore */ }
    });
  }, []);

  // Center map when external coordinate is given
  useEffect(() => {
    if (!leafletMap.current || !center) return;
    leafletMap.current.setView([center.lat, center.lon], 16);
    if (markerRef.current) markerRef.current.remove();
    markerRef.current = window.L.marker([center.lat, center.lon]).addTo(leafletMap.current);
  }, [center]);

  return (
    <div ref={mapRef} style={{height:340,borderRadius:'0 0 12px 12px',background:'var(--paper-3)'}} />
  );
}

/* ─── Tableau FROST ─────────────────────────────────────────────────────────── */
function FrostTable({ filter, onStudy }) {
  const filtered = useMemo(() => {
    if (!filter) return FROST_CATALOGUE;
    const q = filter.toLowerCase();
    return FROST_CATALOGUE.filter(f =>
      f.code.toLowerCase().includes(q) || f.desc.toLowerCase().includes(q) || f.filiere.toLowerCase().includes(q)
    );
  }, [filter]);

  return (
    <div style={{overflowY:'auto',maxHeight:560}}>
      <table style={{width:'100%',borderCollapse:'collapse',fontSize:11}}>
        <thead>
          <tr style={{background:'var(--bg3)',position:'sticky',top:0}}>
            <th style={{padding:'7px 10px',textAlign:'left',fontSize:10,color:'var(--t2)',fontWeight:600}}>Code</th>
            <th style={{padding:'7px 10px',textAlign:'left',fontSize:10,color:'var(--t2)',fontWeight:600}}>Description</th>
            <th style={{padding:'7px 10px',textAlign:'left',fontSize:10,color:'var(--t2)',fontWeight:600}}>Filière</th>
            <th style={{padding:'7px 10px',textAlign:'center',fontSize:10,color:'var(--t2)',fontWeight:600}}>Action</th>
          </tr>
        </thead>
        <tbody>
          {filtered.map((f,i) => {
            const col = FILIERE_COLORS[f.filiere] || {bg:'#6b728018',text:'#6b7280'};
            return (
              <tr key={f.code} style={{background: i%2===0?'':'var(--bg3)', borderBottom:'1px solid var(--border)'}}>
                <td style={{padding:'7px 10px',whiteSpace:'nowrap'}}>
                  <div style={{display:'flex',alignItems:'center',gap:4}}>
                    {f.priority && <span title="Prioritaire" style={{fontSize:9}}>⭐</span>}
                    <span style={{fontWeight:700,color:'var(--plasma)',fontFamily:'monospace'}}>{f.code}</span>
                  </div>
                </td>
                <td style={{padding:'7px 10px',lineHeight:1.45}}>{f.desc}</td>
                <td style={{padding:'7px 10px'}}>
                  <span style={{fontSize:9,fontWeight:700,color:col.text,background:col.bg,padding:'2px 7px',borderRadius:10,whiteSpace:'nowrap'}}>
                    {f.filiere}
                  </span>
                </td>
                <td style={{padding:'7px 10px',textAlign:'center',whiteSpace:'nowrap'}}>
                  <button className="btn b-ghost" style={{fontSize:10,padding:'3px 8px',marginRight:4}}
                    onClick={() => onStudy?.(f.code)} title="Ouvrir l'étude CEE">
                    📋 Étude
                  </button>
                  <a href={`https://www.ecologie.gouv.fr/operations-standardisees-deconomies-denergie`}
                    target="_blank" rel="noopener"
                    className="btn b-ghost"
                    style={{fontSize:10,padding:'3px 8px',textDecoration:'none',color:'var(--t2)'}}>
                    🔗
                  </a>
                </td>
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
}

/* ─── Parcelle info panel ───────────────────────────────────────────────────── */
function ParcellePanel({ parcelle }) {
  if (!parcelle) return (
    <div style={{padding:'12px 14px',fontSize:11,color:'var(--t2)'}}>
      📍 Cliquez sur la carte pour obtenir les données cadastrales de la parcelle.
    </div>
  );
  return (
    <div style={{padding:'12px 14px',fontSize:11}}>
      <div style={{fontWeight:700,marginBottom:6}}>📐 Parcelle cadastrale</div>
      {parcelle.section && <div>Section : <strong>{parcelle.section}</strong></div>}
      {parcelle.numero && <div>Numéro : <strong>{parcelle.numero}</strong></div>}
      {parcelle.commune && <div>Commune : <strong>{parcelle.commune}</strong></div>}
      {parcelle.surface_ha && <div>Surface : <strong>{(parcelle.surface_ha * 10000).toFixed(0)} m²</strong></div>}
      {parcelle.code_insee && <div style={{color:'var(--t2)'}}>INSEE : {parcelle.code_insee}</div>}
    </div>
  );
}

/* ─── Page principale ───────────────────────────────────────────────────────── */
function GovPage() {
  const [mapCenter, setMapCenter] = useState(null);
  const [parcelle, setParcelle] = useState(null);
  const [frostFilter, setFrostFilter] = useState('');
  const [selectedEnt, setSelectedEnt] = useState(null);
  const [tab, setTab] = useState('search'); // 'search' | 'frost'

  const handleAddressSelect = (item) => {
    setMapCenter({ lat: item.lat, lon: item.lon });
    setParcelle(null);
  };

  const handleStudy = (code) => {
    // Navigate to dimensionnement with the FROST pre-selected
    sessionStorage.setItem('ae_nav_context', JSON.stringify({ screen:'dim', context:{ frostCode: code }, ts: Date.now() }));
    window.AE_NAV?.('dim');
  };

  const frostCount = useMemo(() => ({
    total: FROST_CATALOGUE.length,
    priority: FROST_CATALOGUE.filter(f=>f.priority).length,
  }), []);

  return (
    <div style={{display:'flex',flexDirection:'column',height:'100%',overflow:'hidden'}}>
      {/* Header */}
      <div style={{padding:'18px 24px 12px',borderBottom:'1px solid var(--border)',flexShrink:0}}>
        <div style={{display:'flex',alignItems:'center',justifyContent:'space-between'}}>
          <div>
            <div style={{fontSize:18,fontWeight:800,letterSpacing:'-0.5px'}}>
              🏛️ APIs <span style={{color:'var(--signal)'}}>Gouvernementales</span>
            </div>
            <div style={{fontSize:12,color:'var(--t2)',marginTop:3}}>
              SIRENE INSEE · BAN Adresses · Cadastre IGN · Catalogue FROST officiel
            </div>
          </div>
          <div style={{display:'flex',gap:8}}>
            <button className={`btn ${tab==='search'?'b-primary':'b-ghost'}`}
              onClick={()=>setTab('search')}>🔍 Recherche</button>
            <button className={`btn ${tab==='frost'?'b-primary':'b-ghost'}`}
              onClick={()=>setTab('frost')}>
              📋 FROST
              <span style={{marginLeft:6,fontSize:9,background:'var(--plasma)',color:'#fff',borderRadius:10,padding:'1px 5px'}}>{frostCount.total}</span>
            </button>
          </div>
        </div>
      </div>

      {tab === 'search' && (
        <div style={{flex:1,overflow:'auto',padding:'16px 24px'}}>
          <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:14,alignItems:'start'}}>

            {/* Colonne gauche */}
            <div style={{display:'flex',flexDirection:'column',gap:14}}>

              {/* SIRENE */}
              <div style={{background:'var(--bg2)',borderRadius:12,border:'1px solid var(--border)',overflow:'hidden'}}>
                <div style={{padding:'10px 14px',borderBottom:'1px solid var(--border)',display:'flex',alignItems:'center',gap:10}}>
                  <div style={{width:26,height:26,borderRadius:8,background:'var(--plasma)',display:'flex',alignItems:'center',justifyContent:'center',fontSize:12,color:'#fff',fontWeight:700}}>S</div>
                  <div>
                    <div style={{fontSize:12,fontWeight:700}}>Recherche Entreprise <span style={{fontSize:10,background:'var(--plasma-tint)',color:'var(--plasma)',borderRadius:10,padding:'1px 6px',marginLeft:4}}>🏛️ SIRENE INSEE</span></div>
                    <div style={{fontSize:10,color:'var(--t2)'}}>Dénomination, SIRET, SIREN</div>
                  </div>
                </div>
                <div style={{padding:'12px 14px',display:'flex',flexDirection:'column',gap:10}}>
                  <div>
                    <label style={{fontSize:11,color:'var(--t2)',display:'block',marginBottom:4}}>Nom d'entreprise</label>
                    <EntrepriseSearch onSelect={setSelectedEnt} />
                  </div>
                  <div>
                    <label style={{fontSize:11,color:'var(--t2)',display:'block',marginBottom:4}}>Recherche par SIRET</label>
                    <SiretSearch onSelect={setSelectedEnt} />
                  </div>
                </div>
              </div>

              {/* BAN */}
              <div style={{background:'var(--bg2)',borderRadius:12,border:'1px solid var(--border)',overflow:'hidden'}}>
                <div style={{padding:'10px 14px',borderBottom:'1px solid var(--border)',display:'flex',alignItems:'center',gap:10}}>
                  <div style={{width:26,height:26,borderRadius:8,background:'var(--signal)',display:'flex',alignItems:'center',justifyContent:'center',fontSize:12,color:'#fff',fontWeight:700}}>A</div>
                  <div>
                    <div style={{fontSize:12,fontWeight:700}}>Recherche Adresse <span style={{fontSize:10,background:'var(--signal-tint)',color:'var(--signal-deep)',borderRadius:10,padding:'1px 6px',marginLeft:4}}>📍 BAN</span></div>
                    <div style={{fontSize:10,color:'var(--t2)'}}>Base Adresses Nationales — géocodage</div>
                  </div>
                </div>
                <div style={{padding:'12px 14px'}}>
                  <AdresseSearch onSelect={handleAddressSelect} placeholder="Rue, ville…" />
                </div>
              </div>
            </div>

            {/* Colonne droite — Carte + Cadastre */}
            <div style={{background:'var(--bg2)',borderRadius:12,border:'1px solid var(--border)',overflow:'hidden'}}>
              <div style={{padding:'10px 14px',borderBottom:'1px solid var(--border)',display:'flex',alignItems:'center',gap:10}}>
                <div style={{width:26,height:26,borderRadius:8,background:'#7c3aed',display:'flex',alignItems:'center',justifyContent:'center',fontSize:14}}>🗺️</div>
                <div>
                  <div style={{fontSize:12,fontWeight:700}}>Carte & Cadastre</div>
                  <div style={{fontSize:10,color:'var(--t2)'}}>Leaflet + IGN — cliquez sur la carte pour les données cadastrales</div>
                </div>
              </div>
              {window.L ? (
                <CadastreMap center={mapCenter} onParcelle={setParcelle} />
              ) : (
                <div style={{height:340,display:'flex',alignItems:'center',justifyContent:'center',color:'var(--t2)',fontSize:12,padding:24,textAlign:'center'}}>
                  🗺️ Leaflet non chargé — vérifiez la connexion internet
                </div>
              )}
              <ParcellePanel parcelle={parcelle} />
            </div>
          </div>
        </div>
      )}

      {tab === 'frost' && (
        <div style={{flex:1,overflow:'hidden',display:'flex',flexDirection:'column',padding:'16px 24px'}}>
          {/* Barre outils FROST */}
          <div style={{display:'flex',alignItems:'center',gap:10,marginBottom:12,flexShrink:0}}>
            <div style={{position:'relative',flex:1,maxWidth:360}}>
              <input className="fi" value={frostFilter} onChange={e=>setFrostFilter(e.target.value)}
                placeholder="Filtrer par code ou description…" style={{paddingLeft:32}} />
              <span style={{position:'absolute',left:10,top:'50%',transform:'translateY(-50%)',fontSize:14}}>🔍</span>
            </div>
            <div style={{display:'flex',gap:6}}>
              {Object.entries(FILIERE_COLORS).map(([k,v]) => (
                <button key={k} className="btn b-ghost" style={{fontSize:10,padding:'3px 9px',color:v.text,background:v.bg,border:`1px solid ${v.text}33`}}
                  onClick={()=>setFrostFilter(k)}>
                  {k}
                </button>
              ))}
              {frostFilter && <button className="btn b-ghost" style={{fontSize:10,padding:'3px 8px'}} onClick={()=>setFrostFilter('')}>✕</button>}
            </div>
            <div style={{fontSize:11,color:'var(--t2)',whiteSpace:'nowrap'}}>
              {frostCount.priority} ⭐ prioritaires · {frostCount.total} total
            </div>
          </div>

          {/* Table */}
          <div style={{flex:1,overflow:'hidden',background:'var(--bg2)',borderRadius:12,border:'1px solid var(--border)'}}>
            <FrostTable filter={frostFilter} onStudy={handleStudy} />
          </div>

          {/* Footer liens officiels */}
          <div style={{marginTop:10,display:'flex',gap:12,flexShrink:0}}>
            <a href="https://www.emmy.fr" target="_blank" rel="noopener" className="btn b-ghost" style={{fontSize:11,textDecoration:'none'}}>
              🔗 Portail EMMY
            </a>
            <a href="https://www.ecologie.gouv.fr/politiques-publiques/certificats-economies-denergie" target="_blank" rel="noopener" className="btn b-ghost" style={{fontSize:11,textDecoration:'none'}}>
              🔗 PNCEE ecologie.gouv.fr
            </a>
            <a href="https://www.ecologie.gouv.fr/operations-standardisees-deconomies-denergie" target="_blank" rel="noopener" className="btn b-ghost" style={{fontSize:11,textDecoration:'none'}}>
              🔗 Opérations standardisées
            </a>
          </div>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { GovPage });
