/* foodtrucks.jsx — Food Trucks: Leaflet map + list, live from /api/foodtrucks */

const TRUCK_ICON_SVG = (color) => `
  <svg xmlns="http://www.w3.org/2000/svg" width="32" height="40" viewBox="0 0 32 40">
    <path d="M16 39C10 31 4 26 4 16a12 12 0 0 1 24 0c0 10-6 15-12 23z"
      fill="${color}" stroke="#fff" stroke-width="2"/>
    <circle cx="16" cy="15" r="6" fill="#fff8ee"/>
    <text x="16" y="19" text-anchor="middle" font-size="9" fill="${color}" font-family="system-ui" font-weight="700">🚚</text>
  </svg>`;

function FoodTrucks() {
  const { go } = useFF();
  const [trucks,   setTrucks]   = React.useState(null);
  const [selected, setSelected] = React.useState(null);
  const [cuisine,  setCuisine]  = React.useState('All');
  const mapRef     = React.useRef(null);
  const leafletRef = React.useRef(null);
  const markersRef = React.useRef([]);

  /* ── Fetch data ── */
  React.useEffect(() => {
    fetch('/api/foodtrucks')
      .then(r => r.ok ? r.json() : [])
      .then(data => setTrucks(Array.isArray(data) ? data : []))
      .catch(() => setTrucks([]));
  }, []);

  /* ── Init Leaflet once component mounts ── */
  React.useEffect(() => {
    if (!mapRef.current || leafletRef.current) return;
    const L = window.L;
    if (!L) return;
    const map = L.map(mapRef.current, { zoomControl: false }).setView([53.9171, -122.7497], 12);
    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
      attribution: '© OpenStreetMap contributors', maxZoom: 19
    }).addTo(map);
    L.control.zoom({ position:'bottomright' }).addTo(map);
    leafletRef.current = map;
    return () => { map.remove(); leafletRef.current = null; };
  }, []);

  /* ── Sync markers when trucks or filter changes ── */
  React.useEffect(() => {
    const map = leafletRef.current;
    const L = window.L;
    if (!map || !L || !trucks) return;

    markersRef.current.forEach(m => m.remove());
    markersRef.current = [];

    const visible = cuisine === 'All' ? trucks : trucks.filter(t => t.cuisine === cuisine);
    visible.forEach(t => {
      if (!t.lat || !t.lng) return;
      const color = selected?.id === t.id ? '#c4612e' : '#41431b';
      const icon = L.divIcon({
        html: TRUCK_ICON_SVG(color),
        className: '', iconSize:[32,40], iconAnchor:[16,40], popupAnchor:[0,-44]
      });
      L.marker([t.lat, t.lng], { icon })
        .addTo(map)
        .on('click', () => setSelected(t));
      markersRef.current.push(L.marker([t.lat, t.lng], { icon }));
    });

    // Fit map to markers if any exist
    const withCoords = visible.filter(t => t.lat && t.lng);
    if (withCoords.length > 0) {
      const bounds = L.latLngBounds(withCoords.map(t => [t.lat, t.lng]));
      map.fitBounds(bounds, { padding:[40,40], maxZoom:14 });
    }
  }, [trucks, selected, cuisine]);

  const cuisines = trucks ? ['All', ...Array.from(new Set(trucks.map(t => t.cuisine).filter(Boolean)))] : ['All'];
  const visible  = trucks ? (cuisine === 'All' ? trucks : trucks.filter(t => t.cuisine === cuisine)) : [];
  const loading  = trucks === null;

  return (
    <div>
      <PageBanner eyebrow="Local eats on wheels" title="Food Trucks"
        sub="Find out who's rolling this week, and where they'll be." />

      {/* filter chips */}
      <div className="page-wrap" style={{ padding:'18px 28px 0', display:'flex', gap:8, flexWrap:'wrap' }}>
        {cuisines.map(c => (
          <button key={c} onClick={() => setCuisine(c)} className="chip"
            style={{ cursor:'pointer', fontSize:13.5, padding:'7px 14px',
              background: cuisine===c ? 'var(--spruce)' : 'var(--paper-3)',
              color: cuisine===c ? 'var(--paper)' : 'var(--ink-soft)', borderColor:'transparent' }}>{c}</button>
        ))}
        <button className="btn btn-primary" onClick={() => go('submit')}
          style={{ marginLeft:'auto', padding:'6px 14px', fontSize:13.5, borderRadius:100 }}>
          <IconPlus size={15}/> Add your truck
        </button>
      </div>

      <div className="page-wrap" style={{ padding:'26px 28px 0' }}>
        <div className="explorer" style={{ display:'grid', gridTemplateColumns:'minmax(320px,420px) 1fr', gap:26, alignItems:'start' }}>

          {/* list */}
          <div style={{ display:'flex', flexDirection:'column', gap:12 }}>
            {loading && (
              <p style={{ color:'var(--ink-faint)', fontFamily:'var(--serif)', fontStyle:'italic', fontSize:18, margin:0 }}>
                Loading trucks…
              </p>
            )}
            {!loading && visible.length === 0 && (
              <div className="card" style={{ padding:'32px 28px', textAlign:'center' }}>
                <IconTruck size={40} style={{ color:'var(--ink-faint)', margin:'0 auto 12px' }}/>
                <h3 style={{ fontSize:20, marginBottom:8 }}>No trucks listed yet</h3>
                <p style={{ color:'var(--ink-soft)', marginBottom:16, fontSize:15 }}>
                  {cuisine !== 'All' ? `No ${cuisine} trucks this week.` : 'Got a food truck in Prince George? Get on the map.'}
                </p>
                {cuisine !== 'All'
                  ? <button className="btn btn-ghost" onClick={() => setCuisine('All')}>Show all trucks</button>
                  : <button className="btn btn-primary" onClick={() => go('submit')}><IconPlus size={16}/> Add your truck</button>}
              </div>
            )}
            {!loading && visible.map((t, i) => {
              const sel = selected?.id === t.id;
              return (
                <button key={t.id||i} onClick={() => setSelected(sel ? null : t)} className="card"
                  style={{ textAlign:'left', padding:'16px 18px', cursor:'pointer', border:'none', width:'100%',
                    outline: sel ? '2px solid var(--accent)' : undefined }}>
                  <div style={{ display:'flex', justifyContent:'space-between', alignItems:'flex-start', gap:12 }}>
                    <div style={{ fontFamily:'var(--display)', fontWeight:700, fontSize:19 }}>{t.name}</div>
                    {t.cuisine && <span className="chip">{t.cuisine}</span>}
                  </div>
                  {t.schedule && <p style={{ color:'var(--ink-soft)', fontSize:14, margin:'8px 0 0', whiteSpace:'pre-line' }}>{t.schedule}</p>}
                  {t.address && <div style={{ display:'flex', gap:5, alignItems:'center', color:'var(--ink-faint)', fontSize:13, marginTop:8 }}><IconPin size={14}/>{t.address}</div>}
                  {t.instagram && (
                    <a href={t.instagram.startsWith('http') ? t.instagram : `https://instagram.com/${t.instagram.replace('@','')}`}
                      target="_blank" rel="noopener" onClick={e => e.stopPropagation()}
                      style={{ display:'inline-flex', gap:5, alignItems:'center', color:'var(--accent)', fontSize:13, fontWeight:600, marginTop:8 }}>
                      <IconGlobe size={14}/> {t.instagram}
                    </a>
                  )}
                  {t.photos && t.photos.length > 0 && <PhotoCarousel photos={t.photos} height={180} />}
                </button>
              );
            })}
          </div>

          {/* map — always visible */}
          <div className="explorer-map" style={{ position:'sticky', top:92, height:'calc(100vh - 120px)', minHeight:460 }}>
            <div className="card" style={{ height:'100%', overflow:'hidden', padding:0 }}>
              <div ref={mapRef} style={{ width:'100%', height:'100%' }}/>
            </div>
          </div>

        </div>
      </div>
      <div style={{ height:60 }}/>
    </div>
  );
}

window.Pages = window.Pages || {};
window.Pages.FoodTrucks = FoodTrucks;
