/* Interactive stylized sector map — pan via plots, zoom, layers, hover, select. */
(function () {
  const { useState, useMemo } = React;
  const Icon = window.Icon;

  // Generate a plausible plot layout: blocks of plots separated by roads.
  function buildPlots(seed) {
    const rng = (() => { let s = seed; return () => { s = (s * 9301 + 49297) % 233280; return s / 233280; }; })();
    const blocks = [
      { code: 'A', x: 40, y: 40, cols: 6, rows: 3 },
      { code: 'B', x: 40, y: 230, cols: 6, rows: 3 },
      { code: 'C', x: 470, y: 40, cols: 5, rows: 3 },
      { code: 'D', x: 470, y: 230, cols: 5, rows: 4 },
    ];
    const pw = 58, ph = 50, gap = 6;
    const plots = [];
    blocks.forEach(b => {
      for (let r = 0; r < b.rows; r++) for (let c = 0; c < b.cols; c++) {
        const n = r * b.cols + c + 1;
        const types = ['res', 'res', 'res', 'comm', 'inst', 'park'];
        const t = rng() < 0.08 ? 'park' : rng() < 0.12 ? 'comm' : rng() < 0.08 ? 'inst' : 'res';
        plots.push({
          id: b.code + '-' + n, block: b.code,
          x: b.x + c * (pw + gap), y: b.y + r * (ph + gap), w: pw, h: ph, type: t,
        });
      }
    });
    return plots;
  }

  const TYPE = {
    res: { fill: '#ffffff', label: 'Residential', sw: '#cbd8e8' },
    comm: { fill: '#fff2dc', label: 'Commercial', sw: '#f0d49a' },
    inst: { fill: '#e7eeff', label: 'Institutional', sw: '#bcd0f5' },
    park: { fill: '#e3f6ec', label: 'Green / Park', sw: '#b6e6cd' },
  };

  function SectorMap({ sectorName = 'Sector 18', myPlot = 'B-47', height = 460, compact }) {
    const plots = useMemo(() => buildPlots(sectorName.length * 137 + 7), [sectorName]);
    const [zoom, setZoom] = useState(1);
    const [sel, setSel] = useState(null);
    const [hover, setHover] = useState(null);
    const [layers, setLayers] = useState({ satellite: false, master: false, infra: true });
    const [search, setSearch] = useState('');
    // map myPlot to an existing plot id; fall back to one in the same block, then a default
    const mine = plots.find(p => p.id === myPlot)
      || (myPlot && plots.find(p => p.block === myPlot.split('-')[0]))
      || plots[14];
    const matched = search ? plots.find(p => p.id.toLowerCase() === search.toLowerCase()) : null;

    const W = 760, H = 480;
    return (
      <div className="card" style={{ overflow: 'hidden', position: 'relative' }}>
        {/* toolbar */}
        <div className="row spread" style={{ padding: '12px 16px', borderBottom: '1px solid var(--line)', flexWrap: 'wrap', gap: 10 }}>
          <div className="row gap-3">
            <span className="badge badge-navy"><Icon name="map" size={13} />{sectorName}</span>
            <div className="input-icon" style={{ width: 200 }}>
              <Icon name="search" />
              <input className="input" style={{ height: 36, fontSize: 13 }} placeholder="Find plot e.g. B-47" value={search} onChange={e => { setSearch(e.target.value); const m = plots.find(p => p.id.toLowerCase() === e.target.value.toLowerCase()); if (m) setSel(m.id); }} />
            </div>
          </div>
          <div className="row gap-2">
            {[['satellite', 'layers', 'Satellite'], ['master', 'grid', 'Master Plan'], ['infra', 'building', 'Infrastructure']].map(([k, ic, l]) => (
              <button key={k} onClick={() => setLayers(s => ({ ...s, [k]: !s[k] }))}
                className="chip" style={{ padding: '7px 11px', fontSize: 12.5, background: layers[k] ? 'var(--navy-800)' : '#fff', color: layers[k] ? '#fff' : 'var(--ink-2)', borderColor: layers[k] ? 'var(--navy-800)' : 'var(--line)' }}>
                <Icon name={ic} size={14} />{l}
              </button>
            ))}
          </div>
        </div>

        {/* map canvas */}
        <div style={{ position: 'relative', height, overflow: 'hidden', background: layers.satellite ? '#1f3247' : 'linear-gradient(135deg,#eef4fb,#e9f2ec)' }}>
          <div style={{ position: 'absolute', inset: 0, transform: `scale(${zoom})`, transformOrigin: 'center', transition: 'transform .35s cubic-bezier(.3,.7,.3,1)' }}>
            <svg viewBox={`0 0 ${W} ${H}`} width="100%" height="100%" style={{ display: 'block' }}>
              {/* land base */}
              <rect width={W} height={H} fill={layers.satellite ? '#2a4258' : '#e6eef7'} />
              {/* greens / blocks bg when satellite */}
              {layers.satellite && plots.filter(p => p.type === 'park').map(p => <rect key={p.id} x={p.x} y={p.y} width={p.w} height={p.h} fill="#2f5e44" rx={3} />)}
              {/* roads */}
              <g>
                <rect x={0} y={188} width={W} height={34} fill={layers.satellite ? '#3a4a5c' : '#d7e0ec'} />
                <rect x={420} y={0} width={34} height={H} fill={layers.satellite ? '#3a4a5c' : '#d7e0ec'} />
                <line x1={0} y1={205} x2={W} y2={205} stroke={layers.satellite ? '#6f7f93' : '#fff'} strokeWidth={2.5} strokeDasharray="14 11" />
                <line x1={437} y1={0} x2={437} y2={H} stroke={layers.satellite ? '#6f7f93' : '#fff'} strokeWidth={2.5} strokeDasharray="14 11" />
              </g>
              {/* master plan grid overlay */}
              {layers.master && Array.from({ length: 20 }).map((_, i) => (
                <g key={i}>
                  <line x1={i * 40} y1={0} x2={i * 40} y2={H} stroke="rgba(38,112,230,.18)" strokeWidth={1} />
                  <line x1={0} y1={i * 40} x2={W} y2={i * 40} stroke="rgba(38,112,230,.18)" strokeWidth={1} />
                </g>
              ))}
              {/* plots */}
              {plots.map(p => {
                const t = TYPE[p.type];
                const isMine = p.id === mine.id;
                const isSel = sel === p.id;
                const isHover = hover === p.id;
                const isMatch = matched && matched.id === p.id;
                let fill = layers.satellite ? (p.type === 'park' ? '#356b4e' : '#cdd9e6') : t.fill;
                if (isMine) fill = 'var(--emerald-500)';
                if (isSel || isMatch) fill = 'var(--blue-500)';
                return (
                  <g key={p.id} style={{ cursor: 'pointer' }}
                    onMouseEnter={() => setHover(p.id)} onMouseLeave={() => setHover(null)}
                    onClick={() => setSel(p.id)}>
                    <rect x={p.x} y={p.y} width={p.w} height={p.h} rx={4} fill={fill}
                      stroke={isMine ? '#fff' : isSel || isMatch ? '#fff' : (layers.satellite ? '#56697d' : t.sw)}
                      strokeWidth={isMine || isSel || isMatch ? 2.5 : 1}
                      style={{ filter: isHover ? 'brightness(.95)' : 'none', transition: 'filter .1s' }} />
                    <text x={p.x + p.w / 2} y={p.y + p.h / 2 + 4} textAnchor="middle" fontSize="11" fontWeight="700"
                      fill={isMine || isSel || isMatch ? '#fff' : (layers.satellite ? '#dce6f1' : '#7b8aa0')} style={{ pointerEvents: 'none' }}>{p.id}</text>
                  </g>
                );
              })}
              {/* my plot pulse */}
              <circle cx={mine.x + mine.w / 2} cy={mine.y + mine.h / 2} r={36} fill="none" stroke="var(--emerald-500)" strokeWidth={2} opacity={.4} style={{ animation: 'ping 2.4s infinite' }} />
            </svg>
          </div>

          {/* legend */}
          {!compact && (
            <div style={{ position: 'absolute', left: 14, bottom: 14, background: 'rgba(255,255,255,.94)', backdropFilter: 'blur(6px)', borderRadius: 11, padding: '11px 13px', boxShadow: 'var(--sh-md)', display: 'flex', flexDirection: 'column', gap: 7 }}>
              <div style={{ fontWeight: 700, fontSize: 11.5, color: 'var(--ink-2)' }}>Legend</div>
              {[['Your Plot', 'var(--emerald-500)'], ['Selected', 'var(--blue-500)'], ['Residential', '#fff'], ['Commercial', '#fff2dc'], ['Green / Park', '#e3f6ec']].map(([l, c]) => (
                <div key={l} className="row gap-2" style={{ fontSize: 11.5, color: 'var(--muted)' }}>
                  <span style={{ width: 13, height: 13, borderRadius: 3, background: c, border: '1px solid var(--line)' }} />{l}
                </div>
              ))}
            </div>
          )}

          {/* zoom controls */}
          <div style={{ position: 'absolute', right: 14, top: 14, display: 'flex', flexDirection: 'column', gap: 6 }}>
            <button className="icon-btn" style={{ background: '#fff', boxShadow: 'var(--sh-sm)' }} onClick={() => setZoom(z => Math.min(2.2, z + 0.25))}><Icon name="zoomIn" /></button>
            <button className="icon-btn" style={{ background: '#fff', boxShadow: 'var(--sh-sm)' }} onClick={() => setZoom(z => Math.max(0.7, z - 0.25))}><Icon name="zoomOut" /></button>
            <button className="icon-btn" style={{ background: '#fff', boxShadow: 'var(--sh-sm)' }} onClick={() => { setZoom(1); setSel(null); }}><Icon name="refresh" /></button>
          </div>

          {/* selected plot tooltip */}
          {sel && (() => { const p = plots.find(x => x.id === sel); const isMine = p.id === mine.id; return (
            <div className="anim-pop" style={{ position: 'absolute', right: 14, bottom: 14, width: 210, background: '#fff', borderRadius: 12, padding: '13px 15px', boxShadow: 'var(--sh-lg)', border: '1px solid var(--line)' }}>
              <div className="row spread"><span style={{ fontWeight: 800, fontFamily: 'var(--font-display)', fontSize: 16 }}>Plot {p.id}</span><button onClick={() => setSel(null)} style={{ border: 'none', background: 'none', color: 'var(--faint)', cursor: 'pointer' }}><Icon name="x" size={16} /></button></div>
              <div className="muted" style={{ fontSize: 12.5, marginTop: 2 }}>{TYPE[p.type].label} · Block {p.block}</div>
              <div style={{ height: 1, background: 'var(--line)', margin: '10px 0' }} />
              <div className="col gap-2" style={{ fontSize: 12.5 }}>
                <div className="row spread"><span className="muted">Area</span><b>{p.type === 'comm' ? '450' : '300'} sq.m</b></div>
                <div className="row spread"><span className="muted">Status</span>{isMine ? <span className="badge badge-green" style={{ fontSize: 10.5 }}>Yours</span> : <span className="badge badge-gray" style={{ fontSize: 10.5 }}>Allotted</span>}</div>
              </div>
            </div>
          ); })()}
        </div>
      </div>
    );
  }

  window.SectorMap = SectorMap;
})();
