// map.jsx — Leaflet map components for picking + displaying report locations

// Bodindecha School (Singh Singhaseni) — main campus, Wang Thonglang
const BODIN_CENTER = [13.7705, 100.6248];
const BODIN_ZOOM = 18;

function statusColor(status) {
  if (status === 'resolved') return '#3aa057';
  if (status === 'in-progress') return '#d68a2c';
  return '#d64545';
}

function pinIconHtml(color) {
  return `<div style="
    width: 26px; height: 26px; border-radius: 50% 50% 50% 0;
    background: ${color}; transform: rotate(-45deg);
    border: 2px solid #fff; box-shadow: 0 3px 6px rgba(0,0,0,0.3);
    display:flex; align-items:center; justify-content:center;
  "><div style="
    width: 8px; height: 8px; border-radius: 50%; background:#fff; transform: rotate(45deg);
  "></div></div>`;
}

// ─── Location picker (student form) ────────────────────────
function LocationPicker({ value, onChange, height = 220 }) {
  const ref = React.useRef(null);
  const mapRef = React.useRef(null);
  const markerRef = React.useRef(null);

  React.useEffect(() => {
    if (!ref.current || mapRef.current) return;
    if (typeof L === 'undefined') return;
    const start = value && value.lat ? [value.lat, value.lng] : BODIN_CENTER;
    const map = L.map(ref.current, { zoomControl: true, attributionControl: false })
      .setView(start, BODIN_ZOOM);
    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
      maxZoom: 20,
    }).addTo(map);
    mapRef.current = map;

    function setPin(lat, lng) {
      if (markerRef.current) markerRef.current.remove();
      const icon = L.divIcon({
        html: pinIconHtml('#5048d6'),
        className: 'bp-leaflet-pin',
        iconSize: [26, 26],
        iconAnchor: [13, 26],
      });
      markerRef.current = L.marker([lat, lng], { icon }).addTo(map);
      onChange && onChange({ lat, lng });
    }

    if (value && value.lat) setPin(value.lat, value.lng);
    map.on('click', e => setPin(e.latlng.lat, e.latlng.lng));

    return () => { map.remove(); mapRef.current = null; markerRef.current = null; };
  }, []);

  return (
    <div style={{ position:'relative' }}>
      <div ref={ref} style={{
        height, width:'100%', borderRadius: 12,
        border:'1px solid var(--bp-line)', overflow:'hidden',
        background:'var(--bp-soft)',
      }}/>
      <div style={{
        position:'absolute', bottom: 8, left: 8, right: 8,
        background:'rgba(255,255,255,0.94)', backdropFilter:'blur(10px)',
        borderRadius: 8, padding:'6px 10px',
        fontSize: 11, color:'var(--bp-ink-2)',
        pointerEvents:'none',
      }}>
        {value && value.lat
          ? `📍 ${value.lat.toFixed(5)}, ${value.lng.toFixed(5)}`
          : 'แตะบนแผนที่เพื่อปักหมุดจุดที่พบปัญหา'}
      </div>
    </div>
  );
}

// ─── Reports map view (teacher) ────────────────────────────
function ReportsMap({ reports, lang, onPick, height = 'calc(100vh - 160px)' }) {
  const ref = React.useRef(null);
  const mapRef = React.useRef(null);
  const layerRef = React.useRef(null);

  React.useEffect(() => {
    if (!ref.current || mapRef.current) return;
    if (typeof L === 'undefined') return;
    const map = L.map(ref.current, { zoomControl: true, attributionControl: false })
      .setView(BODIN_CENTER, BODIN_ZOOM);
    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { maxZoom: 20 }).addTo(map);
    layerRef.current = L.layerGroup().addTo(map);
    mapRef.current = map;
    return () => { map.remove(); mapRef.current = null; layerRef.current = null; };
  }, []);

  React.useEffect(() => {
    if (!layerRef.current || !mapRef.current) return;
    layerRef.current.clearLayers();
    const pinned = (reports || []).filter(r => r.lat && r.lng);
    pinned.forEach(r => {
      const icon = L.divIcon({
        html: pinIconHtml(statusColor(r.status)),
        className: 'bp-leaflet-pin',
        iconSize: [26, 26],
        iconAnchor: [13, 26],
      });
      const marker = L.marker([r.lat, r.lng], { icon })
        .addTo(layerRef.current)
        .bindPopup(`<div style="font-family:inherit;min-width:160px">
          <div style="font-weight:600;font-size:12px;color:#111">${lang === 'th' ? r.title : (r.titleEn || r.title)}</div>
          <div style="font-size:10.5px;color:#666;margin-top:4px">${r.id} · ${r.reporter || ''}</div>
          <div style="font-size:10.5px;color:#666;margin-top:2px">${lang === 'th' ? r.location : (r.locationEn || r.location)}</div>
        </div>`);
      if (onPick) marker.on('click', () => onPick(r.id));
    });
  }, [reports, lang, onPick]);

  return (
    <div style={{ position:'relative' }}>
      <div ref={ref} style={{
        height, width:'100%', borderRadius: 12,
        border:'1px solid var(--bp-line)', overflow:'hidden',
      }}/>
      <div style={{
        position:'absolute', top: 8, right: 8,
        background:'rgba(255,255,255,0.96)', backdropFilter:'blur(10px)',
        borderRadius: 10, padding:'8px 12px',
        fontSize: 11, color:'var(--bp-ink-2)', lineHeight: 1.6,
        boxShadow:'var(--bp-shadow-sm)',
        border:'1px solid var(--bp-line)',
      }}>
        <div style={{ fontWeight: 600, marginBottom: 4 }}>
          {lang === 'th' ? 'สถานะ' : 'Status'}
        </div>
        <div style={{ display:'flex', alignItems:'center', gap: 6 }}><Dot c="#d64545"/> {lang === 'th' ? 'รอแก้' : 'Pending'}</div>
        <div style={{ display:'flex', alignItems:'center', gap: 6 }}><Dot c="#d68a2c"/> {lang === 'th' ? 'กำลังแก้' : 'In progress'}</div>
        <div style={{ display:'flex', alignItems:'center', gap: 6 }}><Dot c="#3aa057"/> {lang === 'th' ? 'แก้แล้ว' : 'Resolved'}</div>
      </div>
    </div>
  );
}

function Dot({ c }) {
  return <span style={{ width: 10, height: 10, borderRadius:'50%', background: c, display:'inline-block' }}/>;
}

Object.assign(window, { LocationPicker, ReportsMap, BODIN_CENTER, BODIN_ZOOM });
