/* The real, interactive Madison Fields site plan.
   Uses lot polygons parsed from the DXF. */

const M = window.MAF;
const { useState, useMemo, useRef, useCallback, useEffect } = React;

const BBOX = window.MAF_DATA.bbox;
const W = BBOX.xmax - BBOX.xmin;
const H = BBOX.ymax - BBOX.ymin;

// Transform SVG point → viewBox-local point. SVG export is already top-left
// origin / Y-down, so no flip — just translate to (xmin, ymin) = (0, 0).
function xform([x, y]) {
  return [x - BBOX.xmin, y - BBOX.ymin];
}
function pointsAttr(verts) {
  return verts.map(xform).map(p => p[0].toFixed(1) + ',' + p[1].toFixed(1)).join(' ');
}

/* Aerial-style backdrop — soft photo-feel texture without an actual photo. */
function AerialBackdrop({ aerial }) {
  return (
    <defs>
      <radialGradient id="aerialBg" cx="50%" cy="50%" r="70%">
        <stop offset="0%"   stopColor="#dad0b8"/>
        <stop offset="60%"  stopColor="#cdc0a3"/>
        <stop offset="100%" stopColor="#b8a986"/>
      </radialGradient>
      <pattern id="treeNoise" patternUnits="userSpaceOnUse" width="15000" height="15000">
        <rect width="15000" height="15000" fill="transparent"/>
        {Array.from({ length: 28 }).map((_, i) => {
          const x = (i * 2800) % 15000;
          const y = (i * 4900) % 15000;
          const r = 250 + ((i * 19) % 7) * 80;
          return <circle key={i} cx={x} cy={y} r={r} fill="#7d8e6c" opacity="0.42"/>;
        })}
      </pattern>
      <linearGradient id="schematicBg" x1="0" y1="0" x2="0" y2="1">
        <stop offset="0%"   stopColor="#f5f2eb"/>
        <stop offset="100%" stopColor="#ece8de"/>
      </linearGradient>
      <pattern id="schematicGrid" patternUnits="userSpaceOnUse" width="50000" height="50000">
        <path d="M 50000 0 L 0 0 0 50000" fill="none" stroke="#d6d3d1" strokeWidth="150" opacity="0.5"/>
      </pattern>
    </defs>
  );
}

/* Roads — derived from non-lot space; for now drawn as a soft "field" rectangle.
   In production we'd export roads as a named SVG group from SketchUp. */
function GreenWedge() {
  // East-edge greenspace wedge — visually warmer than the rest, hints at hardwoods
  return (
    <path
      d={`M ${W * 0.78} 0 Q ${W * 0.95} ${H * 0.35} ${W * 0.92} ${H * 0.65} Q ${W * 0.84} ${H * 0.95} ${W * 0.7} ${H} L ${W} ${H} L ${W} 0 Z`}
      fill="rgba(125,142,108,0.22)"
      stroke="none"
    />
  );
}

/* The site plan svg itself */
function SitePlanMap({
  filters,
  highlight,
  onHover,
  onSelect,
  showAerial = true,
  showLabels = false,
  width = '100%',
  height = 640,
}) {
  const data = M.useData();
  const lots = data.lots;
  const matchesFilter = useCallback((lot) => {
    if (!filters.type[lot.type]) return false;
    if (!filters.status[lot.status]) return false;
    const p = lot.price;
    if (filters.price === '<750'  && !(p < 750000)) return false;
    if (filters.price === '750-1' && !(p >= 750000 && p < 1000000)) return false;
    if (filters.price === '1-1.5' && !(p >= 1000000 && p < 1500000)) return false;
    if (filters.price === '1.5+'  && !(p >= 1500000)) return false;
    if (filters.builder !== 'all' && lot.builderId !== filters.builder) return false;
    return true;
  }, [filters]);

  return (
    <svg viewBox={`0 0 ${W} ${H}`}
         preserveAspectRatio="xMidYMid meet"
         width={width} height={height}
         style={{ display: 'block', background: 'var(--bg-secondary)' }}>
      <AerialBackdrop aerial={showAerial}/>
      {/* Background */}
      {showAerial ? (
        <>
          <rect width={W} height={H} fill="url(#aerialBg)"/>
          <rect width={W} height={H} fill="url(#treeNoise)" opacity="0.55"/>
          <GreenWedge/>
        </>
      ) : (
        <>
          <rect width={W} height={H} fill="url(#schematicBg)"/>
          <rect width={W} height={H} fill="url(#schematicGrid)"/>
        </>
      )}

      {/* Lots */}
      <g>
        {lots.map(lot => {
          const matches = matchesFilter(lot);
          const isHi = highlight === lot.n;
          const fill = isHi ? 'rgba(194,90,58,0.55)' : M.STATUS_FILL[lot.status];
          const stroke = isHi ? '#c25a3a' : M.STATUS_STROKE[lot.status];
          return (
            <polygon
              key={lot.n}
              points={pointsAttr(lot.verts)}
              fill={fill}
              stroke={stroke}
              strokeWidth={isHi ? 2200 : 1100}
              opacity={matches ? 1 : 0.12}
              style={{
                cursor: matches ? 'pointer' : 'default',
                transition: 'fill 0.15s ease, opacity 0.15s ease',
              }}
              onMouseEnter={() => matches && onHover && onHover(lot)}
              onMouseLeave={() => onHover && onHover(null)}
              onClick={() => matches && onSelect && onSelect(lot)}
            />
          );
        })}
      </g>

      {/* Lot number labels — same SVG so they share the viewBox & transform */}
      {showLabels && (
        <g style={{ pointerEvents: 'none' }}>
          {lots.filter(matchesFilter).map(lot => {
            const [cx, cy] = xform(lot.c);
            return (
              <text key={`l-${lot.n}`} x={cx} y={cy + 12000}
                    textAnchor="middle"
                    fontFamily="Inter, sans-serif"
                    fontSize="36000"
                    fontWeight="500"
                    fill="#1c1917" opacity="0.9">
                {lot.n}
              </text>
            );
          })}
        </g>
      )}

      {/* Compass + scale ref — sized for the mm-scale viewBox */}
      <g transform={`translate(${W - 35000} 35000)`}>
        <circle r="11000" fill="none" stroke="#57534e" strokeWidth="1100" opacity="0.6"/>
        <text y="-15500" textAnchor="middle"
              fontFamily="Inter, sans-serif" fontSize="9000" fill="#57534e" opacity="0.7">N</text>
        <line x1="0" y1="-10500" x2="0" y2="0" stroke="#1c1917" strokeWidth="1500" opacity="0.7"/>
      </g>
    </svg>
  );
}

/* Floating peek card — appears when hovering a lot */
function LotPeekCard({ lot, x = null, y = null }) {
  const { navigate } = M.useRoute();
  if (!lot) return null;
  const builder = window.MAF_DATA.builders.find(b => b.id === lot.builderId);
  const fixedPos = (x == null);
  const cardStyle = fixedPos
    ? { position: 'absolute', top: 24, right: 24, width: 280, zIndex: 5 }
    : { position: 'absolute', left: x + 16, top: y + 16, width: 280, zIndex: 5, pointerEvents: 'none' };
  return (
    <div className="wf-card" style={{ ...cardStyle, background: 'var(--surface)', overflow: 'hidden' }}>
      <M.Img label={`Lot ${lot.n}`} style={{ height: 140, borderRadius: 0, border: 'none' }}/>
      <div className="col gap-2" style={{ padding: 16 }}>
        <div className="row between center">
          <M.Eyebrow>{lot.type === 'cottage' ? 'Cottage' : 'Estate'} · Lot {lot.n}</M.Eyebrow>
          <span className={`wf-dot wf-dot-${M.STATUS_DOT[lot.status]}`}/>
        </div>
        <div className="t-h4">{M.fmtPrice(lot.price)}</div>
        <M.Note style={{ fontSize: 12 }}>
          {lot.acres} ac · {lot.area_sqft.toLocaleString()} sf · {builder?.name}
        </M.Note>
        <div className="row between center" style={{ marginTop: 6 }}>
          <M.Eyebrow>{M.STATUS_LABEL[lot.status]}</M.Eyebrow>
          <button className="wf-btn" style={{ padding: '6px 12px', fontSize: 10 }}
                  onClick={() => navigate('lot', { n: lot.n })}>Open →</button>
        </div>
      </div>
    </div>
  );
}

window.MAF.SitePlanMap = SitePlanMap;
window.MAF.LotPeekCard = LotPeekCard;
window.MAF.SitePlanBBox = { W, H };
