/* Map.jsx — stylized daylight terrain map for RaDa Intelligence.
   PortfolioMap: color-coded farm pins. RegionMap: coop heat clusters.
   No external tiles — a hand-drawn highland terrain in Chemeli tones. */

function TerrainDefs() {
  return React.createElement('defs', null,
    React.createElement('linearGradient', { id: 'terra', x1: 0, y1: 0, x2: 0, y2: 1 },
      React.createElement('stop', { offset: 0, stopColor: '#D9E1C6' }),
      React.createElement('stop', { offset: 0.55, stopColor: '#CBD6B4' }),
      React.createElement('stop', { offset: 1, stopColor: '#C2B79A' })),
    React.createElement('linearGradient', { id: 'escarp', x1: 0, y1: 0, x2: 1, y2: 0 },
      React.createElement('stop', { offset: 0, stopColor: '#B7A988', stopOpacity: 0 }),
      React.createElement('stop', { offset: 1, stopColor: '#A6936B', stopOpacity: 0.6 })));
}

/* subtle scattered field parcels — deterministic */
const PARCELS = (() => {
  const out = []; let s = 5;
  const rnd = () => { s = Math.sin(s * 9973) * 10000; return s - Math.floor(s); };
  for (let i = 0; i < 46; i++) {
    const x = rnd() * 940 + 20, y = rnd() * 940 + 20, w = 38 + rnd() * 70, h = 30 + rnd() * 55;
    const greens = ['#BFD0A2', '#C9D6AE', '#B3C593', '#D2CDA6', '#C6B98F'];
    out.push({ x, y, w, h, fill: greens[Math.floor(rnd() * greens.length)], rot: (rnd() - 0.5) * 24, op: 0.45 + rnd() * 0.3 });
  }
  return out;
})();

function MapBase({ children, height = 540, labels = true }) {
  return React.createElement('div', { className: 'mapwrap', style: { height } },
    React.createElement('svg', { width: '100%', height: '100%', viewBox: '0 0 1000 1000', preserveAspectRatio: 'xMidYMid slice', style: { display: 'block' } },
      React.createElement(TerrainDefs),
      React.createElement('rect', { width: 1000, height: 1000, fill: 'url(#terra)' }),
      // field parcels
      PARCELS.map((p, i) => React.createElement('rect', {
        key: i, x: p.x, y: p.y, width: p.w, height: p.h, rx: 7, fill: p.fill, opacity: p.op,
        transform: `rotate(${p.rot} ${p.x + p.w / 2} ${p.y + p.h / 2})`, stroke: '#A9B488', strokeWidth: 0.6, strokeOpacity: 0.5,
      })),
      // Kerio escarpment band (east / Elgeyo Marakwet)
      React.createElement('rect', { x: 680, y: 0, width: 320, height: 1000, fill: 'url(#escarp)' }),
      React.createElement('path', { d: 'M700 0 C 720 250, 690 520, 730 780 C 745 880, 720 960, 760 1000', fill: 'none', stroke: '#8C7A55', strokeWidth: 2, strokeOpacity: 0.45, strokeDasharray: '2 6' }),
      // Kerio river
      React.createElement('path', { d: 'M860 -10 C 840 200, 880 420, 850 640 C 835 760, 865 880, 845 1010', fill: 'none', stroke: '#7FA0B0', strokeWidth: 5, strokeOpacity: 0.55, strokeLinecap: 'round' }),
      // roads
      React.createElement('path', { d: 'M-10 360 C 240 340, 520 420, 1010 380', fill: 'none', stroke: '#E8E0CC', strokeWidth: 6, strokeOpacity: 0.8 }),
      React.createElement('path', { d: 'M300 -10 C 320 280, 280 560, 360 1010', fill: 'none', stroke: '#E8E0CC', strokeWidth: 5, strokeOpacity: 0.7 }),
      labels && [
        ['UASIN GISHU', 250, 110], ['Moiben', 270, 300], ['Soy', 300, 220], ['Kapseret', 180, 560],
        ['Kesses', 430, 525], ['Ainabkoi', 480, 320], ['ELGEYO', 800, 110], ['MARAKWET', 800, 140],
        ['Iten', 760, 350], ['Tambach', 820, 500],
      ].map((l, i) => React.createElement('text', {
        key: i, x: l[1], y: l[2], fontSize: l[0] === l[0].toUpperCase() && l[0].length > 4 ? 15 : 13,
        fontFamily: 'JetBrains Mono, monospace', letterSpacing: l[0].length > 4 && l[0] === l[0].toUpperCase() ? 2 : 0.5,
        fill: l[0] === l[0].toUpperCase() && l[0].length > 4 ? '#8A7A57' : '#6E6347', opacity: 0.75, fontWeight: 500,
        textAnchor: 'middle',
      }, l[0])),
      children));
}

/* Real Google Maps portfolio + per-farm 10m pixel grid tinted by a spectral index. */
const GMAP_API = 'https://europe-west1-root-range-465417-m6.cloudfunctions.net';
const GIDX = [['ndvi', 'Canopy', -0.05, 0.75], ['ndre', 'Nitrogen', 0.05, 0.45], ['ndmi', 'Water', -0.25, 0.40]];
function gtint(v, lo, hi) {
  if (v == null || isNaN(v)) return '#9a9a9a';
  const x = Math.max(0, Math.min(1, (v - lo) / (hi - lo)));
  const r = x < 0.5 ? 230 : Math.round(230 - (x - 0.5) * 2 * 170);
  const g = x < 0.5 ? Math.round(80 + x * 2 * 175) : 220;
  return 'rgb(' + r + ',' + g + ',70)';
}
function PortfolioMap({ farms, selected, onPick, height = 540, t }) {
  const e = React.createElement;
  const ref = useRef(null), mapRef = useRef(null), mk = useRef([]), cells = useRef([]);
  const [idx, setIdx] = useState('ndvi');
  const [info, setInfo] = useState(null);
  const ll = farms.filter(f => f.lat != null && f.lng != null);
  function paint() {
    cells.current.forEach(c => c.setMap(null)); cells.current = [];
    const px = (mapRef.current && mapRef.current._pix) || []; if (!px.length) return;
    const spec = GIDX.find(s => s[0] === idx), d = 0.000055;
    px.forEach(p => cells.current.push(new google.maps.Rectangle({ map: mapRef.current,
      bounds: { north: p.lat + d, south: p.lat - d, east: p.lng + d, west: p.lng - d },
      fillColor: gtint(p[idx], spec[2], spec[3]), fillOpacity: 0.78, strokeWeight: 0, clickable: false })));
    const b = new google.maps.LatLngBounds(); px.forEach(p => b.extend({ lat: p.lat, lng: p.lng })); mapRef.current.fitBounds(b);
  }
  function loadPixels(f) {
    const u = window.firebase && firebase.auth().currentUser; if (!u) return;
    setInfo({ name: f.name, count: '…' });
    u.getIdToken().then(tok => fetch(GMAP_API + '/get_farm_pixels?farm=' + encodeURIComponent(f.id), { headers: { Authorization: 'Bearer ' + tok } }))
      .then(r => r.json()).then(d => { mapRef.current._pix = (d && d.pixels) || []; setInfo({ name: f.name, count: mapRef.current._pix.length }); paint(); })
      .catch(() => setInfo({ name: f.name, count: 0 }));
  }
  function drawMarkers() {
    mk.current.forEach(m => m.setMap(null)); mk.current = [];
    const COL = { red: '#ED6A5E', amber: '#F4BE4F', green: '#61C554' };
    ll.forEach(f => {
      const m = new google.maps.Marker({ position: { lat: f.lat, lng: f.lng }, map: mapRef.current, title: f.name,
        icon: { path: google.maps.SymbolPath.CIRCLE, scale: 7, fillColor: COL[f.status] || '#61C554', fillOpacity: 1, strokeColor: '#fff', strokeWeight: 2 } });
      m.addListener('click', () => { if (onPick) onPick(f.id); loadPixels(f); });
      mk.current.push(m);
    });
  }
  useEffect(() => {
    let n = 0;
    const init = () => {
      if (!window.google || !window.google.maps) { if (n++ < 80) setTimeout(init, 150); return; }
      if (mapRef.current || !ref.current) return;
      mapRef.current = new google.maps.Map(ref.current, { center: ll[0] ? { lat: ll[0].lat, lng: ll[0].lng } : { lat: 0.52, lng: 35.27 }, zoom: 8, mapTypeId: 'hybrid', disableDefaultUI: true, zoomControl: true, gestureHandling: 'greedy' });
      drawMarkers();
      if (ll.length > 1) { const b = new google.maps.LatLngBounds(); ll.forEach(f => b.extend({ lat: f.lat, lng: f.lng })); mapRef.current.fitBounds(b); }
    };
    init();
  }, []);
  useEffect(() => { if (mapRef.current && mapRef.current._pix) paint(); }, [idx]);
  const pill = { padding: '6px 11px', fontSize: 11.5, fontWeight: 600, border: 0, borderRadius: 7, cursor: 'pointer', fontFamily: 'inherit' };
  const chip = { position: 'absolute', background: 'rgba(11,13,17,.88)', borderRadius: 9, color: '#fff' };
  return e('div', { style: { position: 'relative' } },
    e('div', { ref, style: { height, borderRadius: 12, overflow: 'hidden', background: '#16232a', border: '1px solid #000' } }),
    e('div', { style: Object.assign({}, chip, { top: 10, right: 10, padding: 6, display: 'flex', gap: 4 }) },
      GIDX.map(([k, lab]) => e('button', { key: k, onClick: () => setIdx(k), style: Object.assign({}, pill, { background: idx === k ? '#DE994C' : 'transparent', color: idx === k ? '#3a2408' : '#d8cdbb' }) }, lab))),
    e('div', { style: Object.assign({}, chip, { top: 10, left: 10, padding: '7px 11px', fontSize: 12 }) },
      info ? (info.name + ' · ' + info.count + ' px') : (ll.length + ' farms · click one for its pixel grid')),
    e('div', { style: Object.assign({}, chip, { bottom: 10, left: 10, padding: '8px 11px', fontSize: 11, color: '#d8cdbb', display: 'flex', alignItems: 'center', gap: 6 }) },
      GIDX.find(s => s[0] === idx)[1], 'low',
      e('span', { style: { display: 'inline-block', width: 78, height: 8, borderRadius: 9, background: 'linear-gradient(90deg,rgb(230,80,70),rgb(230,220,70),rgb(60,220,70))' } }), 'high'));
}

function RegionMap({ regions, onPick, height = 540 }) {
  const [hover, setHover] = useState(null);
  const max = Math.max(...regions.map(r => r.farms));
  const h = regions.find(r => r.name === hover);
  return React.createElement('div', { style: { position: 'relative' } },
    React.createElement('div', { className: 'map-overlay' },
      React.createElement('div', { className: 'map-legend' },
        React.createElement('div', { className: 'eyebrow', style: { marginBottom: 6 } }, 'Coverage'),
        React.createElement('div', { className: 'row' }, React.createElement('span', { style: { fontSize: 11 } }, 'Circle size = farms')),
        React.createElement('div', { className: 'row' }, React.createElement('span', { style: { fontSize: 11 } }, 'Color = health mix')))),
    React.createElement('div', { className: 'map-title' }, regions.length + ' wards'),
    React.createElement(MapBase, { height },
      regions.map(r => {
        const cx = r.x * 10, cy = r.y * 10, R = 26 + (r.farms / max) * 44;
        const total = r.green + r.amber + r.red;
        // dominant tone for the disc
        const redPct = r.red / total;
        const tone = redPct > 0.14 ? 'var(--red)' : (r.amber / total) > 0.28 ? 'var(--amber)' : 'var(--green)';
        return React.createElement('g', { key: r.name, style: { cursor: 'pointer' }, onMouseEnter: () => setHover(r.name), onMouseLeave: () => setHover(null), onClick: () => onPick && onPick(r.name) },
          React.createElement('circle', { cx, cy, r: R + 6, fill: tone, opacity: 0.12 }),
          React.createElement('circle', { cx, cy, r: R, fill: tone, opacity: 0.26, stroke: tone, strokeWidth: 2 }),
          React.createElement('text', { x: cx, y: cy - 2, textAnchor: 'middle', fontSize: 22, fontWeight: 700, fontFamily: 'Familjen Grotesk, sans-serif', fill: '#3a2c12' }, r.farms),
          React.createElement('text', { x: cx, y: cy + 18, textAnchor: 'middle', fontSize: 12, fontFamily: 'JetBrains Mono, monospace', fill: '#6E6347' }, r.name));
      })),
    h && React.createElement('div', { className: 'maptip', style: { left: h.x + '%', top: (h.y / 100 * height) + 'px' } },
      React.createElement('div', { className: 'mt-name' }, h.name),
      React.createElement('div', { className: 'mt-meta' }, h.farms + ' farms · ' + h.green + ' good · ' + h.amber + ' watch · ' + h.red + ' urgent')));
}

Object.assign(window, { PortfolioMap, RegionMap });
