/* global React */
const { useState: useStateP, useMemo: useMemoP } = React;

/* ============================================================
   <Prospectivity> — interactive hex map of pilot regions.
   Two tabs: Kaduna (Nigeria) and South Africa.
   Hexes use deterministic hotspots so the heat pattern reads
   like a real prospectivity surface. Click hexes for inspection.
============================================================ */

const REGIONS = {
  kaduna: {
    label: "Kaduna",
    country: "Nigeria",
    coords: "10.52°N · 7.44°E",
    eyebrow: "Pilot · Nigeria",
    area: "46,053 km²",
    holes: "1,284",
    discoveries: "11",
    aucScore: "0.86",
    nameLong: "Kaduna State,\nNigeria",
    minerals: ["Gold", "Tantalum", "Lithium", "Tin", "Columbite", "Lead-Zinc"],
    hotspots: [
      { x: 4,  y: 3, r: 3.2, w: 1.0 },
      { x: 9,  y: 5, r: 2.8, w: 0.85 },
      { x: 11, y: 8, r: 2.2, w: 0.55 },
      { x: 2,  y: 7, r: 2.4, w: 0.6 },
    ],
    targets: [
      { id: "KAD-001", mineral: "Lithium pegmatite",  conf: 92, c: 4,  r: 3 },
      { id: "KAD-007", mineral: "Gold (orogenic)",    conf: 84, c: 9,  r: 5 },
      { id: "KAD-012", mineral: "Tantalum-Nb",        conf: 78, c: 2,  r: 7 },
      { id: "KAD-019", mineral: "Tin (cassiterite)",  conf: 71, c: 11, r: 8 },
    ],
  },
  southafrica: {
    label: "South Africa",
    country: "South Africa",
    coords: "26.20°S · 28.05°E",
    eyebrow: "Pilot · South Africa",
    area: "1,221,037 km²",
    holes: "2,041",
    discoveries: "18",
    aucScore: "0.81",
    nameLong: "South Africa",
    minerals: ["PGM", "Chromite", "Copper", "Magnetite", "Diamond", "Vanadium"],
    hotspots: [
      { x: 6,  y: 4, r: 3.6, w: 0.95 },
      { x: 10, y: 6, r: 2.8, w: 0.9 },
      { x: 3,  y: 6, r: 2.2, w: 0.55 },
      { x: 12, y: 3, r: 2.0, w: 0.5 },
    ],
    targets: [
      { id: "SA-003", mineral: "PGM (Bushveld)",    conf: 94, c: 6,  r: 4 },
      { id: "SA-008", mineral: "Chromite seam",     conf: 88, c: 10, r: 6 },
      { id: "SA-014", mineral: "Copper porphyry",   conf: 76, c: 3,  r: 6 },
      { id: "SA-021", mineral: "Magnetite (Fe-Ti)", conf: 72, c: 12, r: 3 },
    ],
  },
};

function makeHexes(hotspots, cols = 14, rows = 10) {
  const out = [];
  for (let r = 0; r < rows; r++) {
    for (let c = 0; c < cols; c++) {
      let v = 0;
      for (const h of hotspots) {
        const dx = c - h.x, dy = r - h.y;
        const d  = Math.sqrt(dx * dx + dy * dy);
        v += h.w * Math.max(0, 1 - d / h.r);
      }
      v = Math.max(0, Math.min(1, v + Math.sin(c * 1.3 + r * 0.7) * 0.04));
      out.push({ c, r, v });
    }
  }
  return out;
}

function hexPath(cx, cy, s) {
  const pts = [];
  for (let i = 0; i < 6; i++) {
    const a = (Math.PI / 3) * i + Math.PI / 6;
    pts.push([cx + s * Math.cos(a), cy + s * Math.sin(a)]);
  }
  return "M" + pts.map(p => p.join(",")).join("L") + "Z";
}

function colorFor(v) {
  if (v < 0.10) return "rgba(125,144,128,0.04)";
  if (v < 0.28) return "rgba(125,144,128,0.14)";
  if (v < 0.46) return "rgba(125,144,128,0.28)";
  if (v < 0.64) return "rgba(154,147,122,0.45)";
  if (v < 0.82) return "rgba(200,164,90,0.60)";
  return "rgba(184,92,74,0.78)";
}

function Prospectivity() {
  const [regionId, setRegionId] = useStateP("kaduna");
  const [focusId, setFocusId] = useStateP(null);
  const [hoverHex, setHoverHex] = useStateP(null);
  const region = REGIONS[regionId];
  const hexes = useMemoP(() => makeHexes(region.hotspots), [regionId]);

  const W = 720, H = 560;
  const cols = 14, rows = 10;
  const size = 26;
  const dx = size * Math.sqrt(3);
  const dy = size * 1.5;
  const pad = 32;

  return (
    <section className="section" id="prospect" data-screen-label="05 Prospectivity">
      <SectionHead
        num="§ 03 · PROSPECT"
        eyebrow="Headline product"
        h2={<>Prospectivity, scored.<br/>Every square kilometre.</>}
        lead="We train on every historical discovery in your jurisdiction and project a probability surface across an H3 hex grid. Targets are ranked, not just mapped, so you know where to put the next hole."
      />

      <div className="prospect-wrap reveal">
        <div className="prospect-map">
          <div className="prospect-tabs">
            {Object.entries(REGIONS).map(([id, r]) => (
              <button
                key={id}
                className={"prospect-tab" + (regionId === id ? " on" : "")}
                onClick={() => { setRegionId(id); setFocusId(null); }}
                type="button"
              >
                {r.label}
              </button>
            ))}
          </div>

          <svg width="100%" viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="xMidYMid meet">
            <defs>
              <radialGradient id="map-glow" cx="35%" cy="35%" r="70%">
                <stop offset="0%"   stopColor="#1a2a36" stopOpacity="0.65" />
                <stop offset="100%" stopColor="#07090c" stopOpacity="0" />
              </radialGradient>
              <pattern id="map-fine-grid" width="40" height="40" patternUnits="userSpaceOnUse">
                <path d="M 40 0 L 0 0 0 40" fill="none" stroke="rgba(255,255,255,0.025)" strokeWidth="0.5"/>
              </pattern>
            </defs>
            <rect width={W} height={H} fill="#07090c" />
            <rect width={W} height={H} fill="url(#map-fine-grid)" />
            <rect width={W} height={H} fill="url(#map-glow)" />

            {/* hex grid */}
            <g onMouseLeave={() => setHoverHex(null)}>
              {hexes.map((h, i) => {
                const cx = ox(h, pad, dx);
                const cy = pad + h.r * dy;
                const isHover = hoverHex && hoverHex.c === h.c && hoverHex.r === h.r;
                return (
                  <path
                    key={i}
                    d={hexPath(cx, cy, size * 0.88)}
                    fill={colorFor(h.v)}
                    stroke={isHover ? "rgba(255,255,255,0.85)" : "rgba(255,255,255,0.05)"}
                    strokeWidth={isHover ? "1.6" : "0.8"}
                    className="hex"
                    onMouseEnter={() => setHoverHex(h)}
                  />
                );
              })}
            </g>

            {/* target pins */}
            <g>
              {region.targets.map((t) => {
                const cx = ox(t, pad, dx);
                const cy = pad + t.r * dy;
                const isFocus = focusId === t.id;
                return (
                  <g key={t.id} onClick={() => setFocusId(isFocus ? null : t.id)} style={{ cursor: "pointer" }}>
                    {isFocus && (
                      <circle cx={cx} cy={cy} r="22" fill="none" stroke="rgba(255,255,255,0.45)" strokeWidth="1" strokeDasharray="2 3">
                        <animate attributeName="r" from="14" to="22" dur="1.6s" repeatCount="indefinite"/>
                        <animate attributeName="opacity" from="0.7" to="0" dur="1.6s" repeatCount="indefinite"/>
                      </circle>
                    )}
                    <circle cx={cx} cy={cy} r="15" fill="rgba(7,9,12,0.6)" stroke="rgba(255,255,255,0.18)" strokeWidth="1" />
                    <circle cx={cx} cy={cy} r="5"  fill={isFocus ? "#c8a45a" : "#fff"} stroke="#07090c" strokeWidth="1.5" />
                    <text x={cx + 14} y={cy + 4} fontFamily="Geist Mono, monospace" fontSize="10" fill="rgba(255,255,255,0.85)">
                      {t.id}
                    </text>
                  </g>
                );
              })}
            </g>

            {/* compass + scale */}
            <g transform={`translate(${W - 92}, ${H - 40})`}>
              <text fontFamily="Geist Mono, monospace" fontSize="10" fill="rgba(255,255,255,0.4)" letterSpacing="0.16em">
                N ↑
              </text>
            </g>
            <g transform={`translate(${pad}, ${H - 22})`}>
              <line x1="0" y1="0" x2="60" y2="0" stroke="rgba(255,255,255,0.35)" />
              <line x1="0" y1="-3" x2="0" y2="3" stroke="rgba(255,255,255,0.35)" />
              <line x1="60" y1="-3" x2="60" y2="3" stroke="rgba(255,255,255,0.35)" />
              <text x="68" y="4" fontFamily="Geist Mono, monospace" fontSize="10" fill="rgba(255,255,255,0.4)">100 km</text>
            </g>
          </svg>

          <HexPanel hex={hoverHex} region={region} />

          <div className="prospect-legend">
            <span className="prospect-legend-l">Prospectivity</span>
            <div className="prospect-legend-ramp">
              <span style={{ background: "rgba(125,144,128,0.04)" }} />
              <span style={{ background: "rgba(125,144,128,0.14)" }} />
              <span style={{ background: "rgba(125,144,128,0.28)" }} />
              <span style={{ background: "rgba(154,147,122,0.45)" }} />
              <span style={{ background: "rgba(200,164,90,0.60)" }} />
              <span style={{ background: "rgba(184,92,74,0.78)" }} />
            </div>
            <span className="prospect-legend-r">0.0 → 1.0</span>
          </div>
        </div>

        <div className="prospect-detail">
          <div className="prospect-detail-eyebrow">{region.eyebrow}</div>
          <div className="prospect-detail-region" style={{ whiteSpace: "pre-line" }}>{region.nameLong}</div>
          <div className="prospect-detail-coords">{region.coords}</div>

          <div className="prospect-stats">
            <div className="prospect-stat">
              <span className="prospect-stat-l">Coverage area</span>
              <span className="prospect-stat-v">{region.area}</span>
            </div>
            <div className="prospect-stat">
              <span className="prospect-stat-l">Historical drillholes</span>
              <span className="prospect-stat-v">{region.holes}</span>
            </div>
            <div className="prospect-stat">
              <span className="prospect-stat-l">Confirmed discoveries</span>
              <span className="prospect-stat-v">{region.discoveries}</span>
            </div>
            <div className="prospect-stat">
              <span className="prospect-stat-l">Model AUC</span>
              <span className="prospect-stat-v" style={{ color: "var(--brand-amber)" }}>{region.aucScore}</span>
            </div>
          </div>

          <div className="prospect-minerals">
            {region.minerals.map(m => (
              <span className="mineral-pill" key={m}>{m}</span>
            ))}
          </div>

          <div className="prospect-targets-head">Top-ranked targets</div>
          <div className="prospect-targets">
            {region.targets.map(t => (
              <div className="prospect-target" key={t.id} onClick={() => setFocusId(focusId === t.id ? null : t.id)} style={{ cursor: "pointer", background: focusId === t.id ? "rgba(255,255,255,0.02)" : "transparent" }}>
                <span className="prospect-target-id">{t.id}</span>
                <span className="prospect-target-mineral">{t.mineral}</span>
                <span className="prospect-target-conf">{t.conf}%</span>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

function ox(h, pad, dx) {
  return pad + h.c * dx + ((h.r % 2) ? dx / 2 : 0);
}

/* ============================================================
   <HexPanel> — futuristic inspection panel for hovered hex.
   Anchors top-right of the map; updates on hover.
============================================================ */
function HexPanel({ hex, region }) {
  if (!hex) {
    return (
      <div className="hex-panel hex-panel--empty" aria-hidden="true">
        <div className="hex-panel-bracket hex-panel-bracket--tl" />
        <div className="hex-panel-bracket hex-panel-bracket--tr" />
        <div className="hex-panel-bracket hex-panel-bracket--bl" />
        <div className="hex-panel-bracket hex-panel-bracket--br" />
        <div className="hex-panel-empty-icon">⬡</div>
        <div className="hex-panel-empty-text">
          Hover a hex<br/>to inspect.
        </div>
      </div>
    );
  }

  // Stable synthetic metadata derived from c/r
  const seed = hex.c * 17 + hex.r * 31 + 1;
  const hexId = "8a" + ((seed * 9301 + 49297) % 0x1000000).toString(16).padStart(6, "0") + "f" + ((seed * 233 + 7) % 0x10000).toString(16).padStart(4, "0") + "fff";

  // Band classification
  const v = hex.v;
  let band, bandClass;
  if      (v >= 0.82) { band = "Very High"; bandClass = "vhigh"; }
  else if (v >= 0.64) { band = "High";      bandClass = "high"; }
  else if (v >= 0.46) { band = "Moderate";  bandClass = "med"; }
  else if (v >= 0.28) { band = "Low";       bandClass = "low"; }
  else if (v >= 0.10) { band = "Trace";     bandClass = "trace"; }
  else                { band = "Background"; bandClass = "bg"; }

  // Region center → hex coordinate offset
  const m = region.coords.match(/([\d.]+)°([NS])\s*·\s*([\d.]+)°([EW])/) || ["", "0", "N", "0", "E"];
  const baseLat = parseFloat(m[1]) * (m[2] === "S" ? -1 : 1);
  const baseLng = parseFloat(m[3]) * (m[4] === "W" ? -1 : 1);
  const lat = baseLat + (hex.r - 5) * 0.062;
  const lng = baseLng + (hex.c - 7) * 0.084;
  const latStr = `${Math.abs(lat).toFixed(3)}°${lat >= 0 ? "N" : "S"}`;
  const lngStr = `${Math.abs(lng).toFixed(3)}°${lng >= 0 ? "E" : "W"}`;

  // Dominant mineral signature
  const minIdx = seed % region.minerals.length;
  const dominant = region.minerals[minIdx];
  const secondary = region.minerals[(minIdx + 2) % region.minerals.length];

  // Confidence + last update from v
  const conf = Math.round(48 + v * 48);
  const updateMins = Math.max(1, Math.round(60 - v * 55));

  return (
    <div className="hex-panel" key={hex.c + "-" + hex.r}>
      <div className="hex-panel-bracket hex-panel-bracket--tl" />
      <div className="hex-panel-bracket hex-panel-bracket--tr" />
      <div className="hex-panel-bracket hex-panel-bracket--bl" />
      <div className="hex-panel-bracket hex-panel-bracket--br" />

      <div className="hex-panel-head">
        <span className="hex-panel-lbl">H3 · CELL</span>
        <span className="hex-panel-id">{hexId}</span>
      </div>

      <div className="hex-panel-prospect">
        <div className="hex-panel-prospect-num">{v.toFixed(3)}</div>
        <div className="hex-panel-prospect-l">
          <span className="hex-panel-lbl">PROSPECTIVITY</span>
          <span className={`hex-panel-band hex-panel-band--${bandClass}`}>{band}</span>
        </div>
      </div>

      <div className="hex-panel-bar">
        <div className={`hex-panel-bar-fill hex-panel-bar-fill--${bandClass}`} style={{ width: (v * 100).toFixed(1) + "%" }} />
      </div>

      <div className="hex-panel-grid">
        <div className="hex-panel-row">
          <span className="hex-panel-lbl">LAT</span>
          <span className="hex-panel-val">{latStr}</span>
        </div>
        <div className="hex-panel-row">
          <span className="hex-panel-lbl">LNG</span>
          <span className="hex-panel-val">{lngStr}</span>
        </div>
        <div className="hex-panel-row">
          <span className="hex-panel-lbl">DOMINANT</span>
          <span className="hex-panel-val">{dominant}</span>
        </div>
        <div className="hex-panel-row">
          <span className="hex-panel-lbl">SECONDARY</span>
          <span className="hex-panel-val">{secondary}</span>
        </div>
        <div className="hex-panel-row">
          <span className="hex-panel-lbl">CONFIDENCE</span>
          <span className="hex-panel-val">{conf}%</span>
        </div>
        <div className="hex-panel-row">
          <span className="hex-panel-lbl">SYNC</span>
          <span className="hex-panel-val">{updateMins} min ago</span>
        </div>
      </div>
    </div>
  );
}

window.Prospectivity = Prospectivity;
