// Entreprise panel v2 — dramatic header, kinetic info cells
const { useState, useEffect, useRef } = React;
const GEO_CACHE2 = new Map();
let LAST_GEO_REQ2 = 0;

async function geocode2(addr, postalCode) {
  if (!addr) return null;
  const cacheKey = addr + '|' + (postalCode || '');
  if (GEO_CACHE2.has(cacheKey)) return GEO_CACHE2.get(cacheKey);
  const wait = Math.max(0, 1100 - (Date.now() - LAST_GEO_REQ2));
  if (wait) await new Promise(r => setTimeout(r, wait));
  LAST_GEO_REQ2 = Date.now();
  try {
    const suffix = postalCode ? `, ${postalCode}, Canada` : ', Québec, Canada';
    const q = encodeURIComponent(addr + suffix);
    const r = await fetch(`https://nominatim.openstreetmap.org/search?format=json&limit=1&q=${q}`,
      { headers: { 'Accept': 'application/json' } });
    if (!r.ok) throw new Error('geo fail');
    const j = await r.json();
    const hit = j[0];
    if (!hit) { GEO_CACHE2.set(cacheKey, null); return null; }
    const point = { lat: parseFloat(hit.lat), lng: parseFloat(hit.lon) };
    GEO_CACHE2.set(cacheKey, point);
    return point;
  } catch (e) { GEO_CACHE2.set(cacheKey, null); return null; }
}

function MapView({ entreprise, onFail }) {
  const ref = useRef(null);
  const mapRef = useRef(null);
  const [state, setState] = useState('loading');

  useEffect(() => {
    let cancelled = false;
    setState('loading');

    (async () => {
      let point = null;

      // Priorité 1 : coordonnées explicites dans les données
      if (entreprise.latitude != null && entreprise.longitude != null) {
        point = { lat: entreprise.latitude, lng: entreprise.longitude };
      }
      // Priorité 2 : géocodage de l'adresse (comportement actuel)
      else if (entreprise.adresse) {
        point = await geocode2(entreprise.adresse, entreprise.code_postal);
      }

      if (cancelled) return;
      if (!point) { setState('fail'); onFail?.(); return; }
      if (!ref.current) return;
      if (mapRef.current) { mapRef.current.remove(); mapRef.current = null; }
      const map = L.map(ref.current, { zoomControl: true, attributionControl: false, scrollWheelZoom: false });
      mapRef.current = map;
      const regionBounds = L.latLngBounds([45.0, -75.0], [49.0, -68.0]);
      map.fitBounds(regionBounds, { padding: [10, 10] });
      L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        maxZoom: 16, attribution: '© OpenStreetMap',
      }).addTo(map);
      const icon = L.divIcon({
        className: '',
        html: '<div class="sva-pin"></div>',
        iconSize: [24, 24], iconAnchor: [12, 12],
      });
      L.marker([point.lat, point.lng], { icon }).addTo(map);
      setTimeout(() => {
        if (cancelled) return;
        map.flyTo([point.lat, point.lng], 8, { duration: 1.2 });
      }, 350);
      setState('ready');
    })();
    return () => {
      cancelled = true;
      if (mapRef.current) { mapRef.current.remove(); mapRef.current = null; }
    };
  }, [entreprise.latitude, entreprise.longitude, entreprise.adresse, entreprise.code_postal]);

  return (
    <div className={`map-container ${state === 'loading' ? 'loading' : ''}`}>
      <div ref={ref} style={{ width: '100%', height: '100%' }} />
      {state === 'fail' && (
        <div className="map-fail">
          <div>
            <div style={{ fontWeight: 500, color: 'var(--fg2)', marginBottom: 4 }}>Localisation indisponible</div>
            <div style={{ fontSize: 12 }}>
              {entreprise.adresse ? "L'adresse n'a pu être géolocalisée." : "Aucune adresse renseignée."}
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

function CompanyPanel({ entreprise, onClose, isTv }) {
  const [enter, setEnter] = useState(false);
  const [mapFailed, setMapFailed] = useState(false);
  useEffect(() => { requestAnimationFrame(() => setEnter(true)); }, []);
  useEffect(() => { setMapFailed(false); }, [entreprise.adresse]);
  useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [onClose]);

  const phone = window.SVAUtils.formatPhone(entreprise.telephone);

  return (
    <div className="modal-bd2" onClick={onClose}>
      <div
        className="entreprise"
        onClick={(e) => e.stopPropagation()}
        style={{
          transform: enter ? 'translateX(0)' : 'translateX(60px)',
          opacity: enter ? 1 : 0,
          transition: 'transform 360ms cubic-bezier(0.22,1,0.36,1), opacity 360ms cubic-bezier(0.22,1,0.36,1)',
        }}
      >
        <div className="entreprise__header">
          <button className="entreprise__close" onClick={onClose} aria-label="Fermer">
            <span></span>
            <span></span>
          </button>
          <div className="entreprise__eyebrow">Entreprise</div>
          <h2 className="entreprise__name">{entreprise.nom}</h2>
          {entreprise.precision && (
            <div className="entreprise__precision">{entreprise.precision}</div>
          )}
        </div>

        <div className="entreprise__body">
          {entreprise.description && (
            <p className="entreprise__desc">{entreprise.description}</p>
          )}

          <div className="info">
            {entreprise.site_web && (
              <div className="info__cell span2">
                <div className="info__lbl"><span className="ic" />Site web</div>
                <div className="info__val">
                  {isTv
                    ? entreprise.site_web.replace(/^https?:\/\//, '').replace(/\/$/, '')
                    : <a href={entreprise.site_web} target="_blank" rel="noopener noreferrer">
                        {entreprise.site_web.replace(/^https?:\/\//, '').replace(/\/$/, '')}
                      </a>
                  }
                </div>
              </div>
            )}
            {phone && (
              <div className="info__cell">
                <div className="info__lbl"><span className="ic" />Téléphone</div>
                <div className="info__val">
                  {isTv ? phone : <a href={`tel:${entreprise.telephone}`}>{phone}</a>}
                </div>
              </div>
            )}
            {(entreprise.adresse || entreprise.code_postal) && (
              <div className="info__cell span2">
                <div className="info__lbl"><span className="ic" />Adresse</div>
                <div className="info__val">
                  {entreprise.adresse}
                  {entreprise.code_postal && (<><br />{entreprise.code_postal}</>)}
                </div>
              </div>
            )}
            {!entreprise.site_web && !phone && !entreprise.adresse && (
              <div className="info__cell span2">
                <div className="info__lbl">Info</div>
                <div className="info__val empty">Coordonnées non renseignées</div>
              </div>
            )}
          </div>

          {(entreprise.latitude != null || entreprise.adresse) && !mapFailed && (
            <div className="map-section">
              <div className="map-head">
                <div className="map-title">Localisation</div>
              </div>
              <MapView entreprise={entreprise} onFail={() => setMapFailed(true)} />
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

window.CompanyPanel = CompanyPanel;
