// ============================================================
// GEO HEATMAP — UK-focused geographic intelligence
// Used by Analytics Intelligence Center + Analytics Breakdown.
// Brass + cyan over matte black. Always-visible regions.
// ============================================================

// Simplified UK + Ireland outline (abstracted, not cartographically precise).
// Coordinates picked so cities land where they belong roughly.
const UK_OUTLINE = "M 260 60 L 280 50 L 305 60 L 320 50 L 332 65 L 340 80 L 350 95 L 360 115 L 365 135 L 358 152 L 340 160 L 332 175 L 325 195 L 320 218 L 318 240 L 312 262 L 304 280 L 296 296 L 282 310 L 268 322 L 252 335 L 240 348 L 230 362 L 224 380 L 220 400 L 218 422 L 224 442 L 232 458 L 218 462 L 200 460 L 188 450 L 178 432 L 170 414 L 162 392 L 158 372 L 150 354 L 146 332 L 142 312 L 138 290 L 138 268 L 142 248 L 152 228 L 162 210 L 174 196 L 184 178 L 196 162 L 208 144 L 218 126 L 228 108 L 240 92 L 252 78 L 260 60 Z";

const IE_OUTLINE = "M 100 240 L 112 232 L 126 230 L 138 240 L 144 256 L 142 272 L 134 286 L 122 296 L 108 298 L 96 292 L 88 280 L 86 264 L 92 250 L 100 240 Z";

// UK & Ireland cities with mock business data
const UK_CITIES = [
  { id: 'london',     name: 'London',     x: 308, y: 390, leads: 1284, revenue: 184200, conv: 24.2, bookings: 412, color: '#5dffb0' },
  { id: 'manchester', name: 'Manchester', x: 252, y: 268, leads: 612,  revenue: 84200,  conv: 21.4, bookings: 184, color: '#4be8ff' },
  { id: 'birmingham', name: 'Birmingham', x: 268, y: 332, leads: 442,  revenue: 64100,  conv: 18.8, bookings: 124, color: '#4be8ff' },
  { id: 'leeds',      name: 'Leeds',      x: 280, y: 252, leads: 312,  revenue: 48400,  conv: 19.2, bookings: 92,  color: '#8b6bff' },
  { id: 'bristol',    name: 'Bristol',    x: 232, y: 388, leads: 248,  revenue: 38400,  conv: 17.4, bookings: 68,  color: '#8b6bff' },
  { id: 'liverpool',  name: 'Liverpool',  x: 236, y: 270, leads: 184,  revenue: 24800,  conv: 14.2, bookings: 42,  color: '#ff7ad9' },
  { id: 'glasgow',    name: 'Glasgow',    x: 196, y: 134, leads: 168,  revenue: 28400,  conv: 22.4, bookings: 48,  color: '#ff7ad9' },
  { id: 'edinburgh',  name: 'Edinburgh',  x: 232, y: 138, leads: 142,  revenue: 24200,  conv: 23.1, bookings: 38,  color: '#ff7ad9' },
  { id: 'cardiff',    name: 'Cardiff',    x: 208, y: 408, leads: 88,   revenue: 12400,  conv: 11.8, bookings: 24,  color: '#ffb14b' }
];

const METRICS = {
  leads:    { label: 'Leads',         key: 'leads',    fmt: v => v.toLocaleString(),         unit: '',  hue: '#4be8ff' },
  revenue:  { label: 'Revenue',       key: 'revenue',  fmt: v => `£${(v/1000).toFixed(1)}k`, unit: '',  hue: '#5dffb0' },
  conv:     { label: 'Conversion',    key: 'conv',     fmt: v => `${v.toFixed(1)}%`,         unit: '',  hue: '#8b6bff' },
  bookings: { label: 'Bookings',      key: 'bookings', fmt: v => v.toLocaleString(),         unit: '',  hue: '#e8c98a' }
};

function GeoHeatmap({ data = UK_CITIES, defaultMetric = 'revenue', defaultPeriod = '30d', onPushToast }) {
  const [metric, setMetric] = React.useState(defaultMetric);
  const [period, setPeriod] = React.useState(defaultPeriod);
  const [hover, setHover] = React.useState(null);
  const [selected, setSelected] = React.useState(null);
  const [zoom, setZoom] = React.useState(1);
  const [pan, setPan] = React.useState({ x: 0, y: 0 });

  const m = METRICS[metric];
  const vals = data.map(d => d[m.key]);
  const max = Math.max(...vals);
  const min = Math.min(...vals);

  // Stats
  const top = [...data].sort((a, b) => b[m.key] - a[m.key])[0];
  const bottom = [...data].sort((a, b) => a[m.key] - b[m.key])[0];
  const total = vals.reduce((s, v) => s + v, 0);

  // Radius mapping for bubbles
  const radius = (val) => 8 + ((val - min) / (max - min || 1)) * 22;
  // Opacity / glow intensity mapping
  const intensity = (val) => 0.3 + ((val - min) / (max - min || 1)) * 0.7;

  const isEmpty = data.length === 0 || max === 0;

  if (isEmpty) {
    return (
      <div className="geo-empty">
        <div className="geo-empty-icon">
          <svg viewBox="0 0 80 80" width="64" height="64">
            <circle cx="40" cy="40" r="32" fill="none" stroke="rgba(232,201,138,0.3)" strokeWidth="1" strokeDasharray="2 4"/>
            <circle cx="40" cy="40" r="20" fill="none" stroke="rgba(232,201,138,0.2)" strokeWidth="1"/>
            <circle cx="40" cy="40" r="4" fill="rgba(232,201,138,0.5)"/>
          </svg>
        </div>
        <div className="geo-empty-title">No map data yet</div>
        <div className="geo-empty-sub">Connect channels or leads to unlock geographic intelligence.</div>
        <button className="btn primary sm" onClick={() => onPushToast && onPushToast('Channel picker opened')}>Connect channels</button>
      </div>
    );
  }

  return (
    <div className="geo-shell">
      {/* Top control bar */}
      <div className="geo-controls">
        <div className="segmented">
          {Object.entries(METRICS).map(([k, def]) => (
            <button key={k} className={metric === k ? 'active' : ''} onClick={() => setMetric(k)}>
              {def.label}
            </button>
          ))}
        </div>
        <span style={{flex: 1}}/>
        <div className="segmented">
          {['24h','7d','30d','90d','ytd'].map(p => (
            <button key={p} className={period === p ? 'active' : ''} onClick={() => setPeriod(p)}>{p}</button>
          ))}
        </div>
      </div>

      <div className="geo-main">
        {/* Map canvas */}
        <div className="geo-canvas">
          <span className="br-bl"></span>
          <span className="br-br"></span>
          <span className="coord">UK · GEO · {METRICS[metric].label.toUpperCase()} · {period.toUpperCase()}</span>
          <span className="coord-br">9 REGIONS · LIVE</span>

          {/* Zoom controls */}
          <div className="geo-zoom-ctrl">
            <button onClick={() => setZoom(z => Math.min(2.5, z + 0.2))} title="Zoom in">+</button>
            <button onClick={() => setZoom(z => Math.max(0.6, z - 0.2))} title="Zoom out">−</button>
            <button onClick={() => { setZoom(1); setPan({x:0,y:0}); }} title="Reset view">⌂</button>
            <span className="geo-zoom-label">{Math.round(zoom * 100)}%</span>
          </div>

          <svg
            viewBox="0 0 500 500"
            xmlns="http://www.w3.org/2000/svg"
            style={{width: '100%', height: '100%', display: 'block'}}
          >
            <defs>
              {/* Subtle grid background */}
              <pattern id="geo-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.04)" strokeWidth="0.5"/>
              </pattern>
              {/* Country fill — bronze-tinted dark */}
              <radialGradient id="geo-country-fill" cx="50%" cy="40%">
                <stop offset="0%" stopColor="rgba(232,201,138,0.08)"/>
                <stop offset="60%" stopColor="rgba(75,232,255,0.04)"/>
                <stop offset="100%" stopColor="rgba(255,255,255,0.02)"/>
              </radialGradient>
              {/* Glow for hot regions */}
              <filter id="geo-glow" x="-50%" y="-50%" width="200%" height="200%">
                <feGaussianBlur stdDeviation="6"/>
              </filter>
              {/* Halo for selected */}
              <filter id="geo-halo" x="-100%" y="-100%" width="300%" height="300%">
                <feGaussianBlur stdDeviation="12"/>
              </filter>
              <radialGradient id="geo-hotspot">
                <stop offset="0%" stopColor="#ffffff" stopOpacity="0.4"/>
                <stop offset="40%" stopColor="#e8c98a" stopOpacity="0.18"/>
                <stop offset="100%" stopColor="#e8c98a" stopOpacity="0"/>
              </radialGradient>
            </defs>

            {/* Grid */}
            <rect width="500" height="500" fill="url(#geo-grid)"/>

            <g transform={`translate(${pan.x} ${pan.y}) scale(${zoom}) translate(${(1 - zoom) * 250} ${(1 - zoom) * 250})`}>
              {/* UK & Ireland outlines */}
              <path d={UK_OUTLINE} fill="url(#geo-country-fill)" stroke="rgba(232,201,138,0.35)" strokeWidth="1.2" strokeLinejoin="round"/>
              <path d={IE_OUTLINE} fill="url(#geo-country-fill)" stroke="rgba(232,201,138,0.22)" strokeWidth="1" strokeLinejoin="round"/>

              {/* Sea labels (decorative) */}
              <text x="80" y="380" fill="rgba(75,232,255,0.25)" fontSize="9" fontFamily="Geist Mono" letterSpacing="3" style={{textTransform: 'uppercase'}}>ATLANTIC</text>
              <text x="380" y="280" fill="rgba(75,232,255,0.25)" fontSize="9" fontFamily="Geist Mono" letterSpacing="3" style={{textTransform: 'uppercase'}}>NORTH · SEA</text>

              {/* Compass rose */}
              <g transform="translate(440 70)" opacity="0.55">
                <circle r="20" fill="none" stroke="rgba(232,201,138,0.4)" strokeWidth="0.6"/>
                <line x1="0" y1="-22" x2="0" y2="-12" stroke="#e8c98a" strokeWidth="1"/>
                <line x1="0" y1="22" x2="0" y2="12" stroke="rgba(232,201,138,0.35)" strokeWidth="0.6"/>
                <line x1="-22" y1="0" x2="-12" y2="0" stroke="rgba(232,201,138,0.35)" strokeWidth="0.6"/>
                <line x1="22" y1="0" x2="12" y2="0" stroke="rgba(232,201,138,0.35)" strokeWidth="0.6"/>
                <text y="-26" fill="#e8c98a" fontSize="8" fontFamily="Geist Mono" textAnchor="middle">N</text>
              </g>

              {/* Heat glow under high-intensity cities */}
              {data.map(c => {
                const i = intensity(c[m.key]);
                if (i < 0.5) return null;
                return (
                  <circle key={`glow-${c.id}`} cx={c.x} cy={c.y} r={radius(c[m.key]) * 2.4}
                    fill="url(#geo-hotspot)" opacity={i}/>
                );
              })}

              {/* Connection lines from #1 city to top 3 (revenue paths) */}
              {metric === 'revenue' && top && data.slice(0, 4).filter(c => c.id !== top.id).map(c => (
                <line key={`path-${c.id}`} x1={top.x} y1={top.y} x2={c.x} y2={c.y}
                  stroke="rgba(232,201,138,0.2)" strokeWidth="0.8" strokeDasharray="2 4"/>
              ))}

              {/* City bubbles */}
              {data.map(c => {
                const r = radius(c[m.key]);
                const i = intensity(c[m.key]);
                const isHover = hover === c.id;
                const isSel = selected === c.id;
                const isTop = c.id === top.id;
                return (
                  <g key={c.id}
                    onMouseEnter={() => setHover(c.id)}
                    onMouseLeave={() => setHover(null)}
                    onClick={() => setSelected(s => s === c.id ? null : c.id)}
                    style={{cursor: 'pointer'}}
                  >
                    {/* Outer ring on hover/select */}
                    {(isHover || isSel) && (
                      <circle cx={c.x} cy={c.y} r={r + 8}
                        fill="none" stroke="#4be8ff" strokeWidth="1.4" opacity="0.85"
                        strokeDasharray="3 2">
                        <animateTransform attributeName="transform" type="rotate" from={`0 ${c.x} ${c.y}`} to={`360 ${c.x} ${c.y}`} dur="6s" repeatCount="indefinite"/>
                      </circle>
                    )}
                    {/* Outer ring always for top */}
                    {isTop && (
                      <>
                        <circle cx={c.x} cy={c.y} r={r + 6} fill="none" stroke="#e8c98a" strokeWidth="1" opacity="0.5">
                          <animate attributeName="r" values={`${r + 4};${r + 12};${r + 4}`} dur="2.6s" repeatCount="indefinite"/>
                          <animate attributeName="opacity" values="0.6;0.1;0.6" dur="2.6s" repeatCount="indefinite"/>
                        </circle>
                        <circle cx={c.x} cy={c.y} r={r + 4} fill="none" stroke="#e8c98a" strokeWidth="0.6" opacity="0.6"/>
                      </>
                    )}
                    {/* Main bubble */}
                    <circle cx={c.x} cy={c.y} r={r}
                      fill={c.color}
                      opacity={0.18 + i * 0.4}
                      stroke={c.color}
                      strokeWidth="1.4"
                      style={{transition: 'all 0.2s'}}/>
                    {/* Bullseye dot */}
                    <circle cx={c.x} cy={c.y} r="2.5" fill={c.color}
                      style={{filter: i > 0.6 ? `drop-shadow(0 0 4px ${c.color})` : 'none'}}/>
                    {/* Label */}
                    <text x={c.x} y={c.y - r - 6}
                      fill={isTop || isHover || isSel ? '#f5f1e6' : 'rgba(245,241,230,0.8)'}
                      fontSize={isTop ? 12 : 11}
                      fontFamily="Instrument Serif"
                      fontStyle="italic"
                      textAnchor="middle"
                      style={{letterSpacing: '-0.01em', transition: 'all 0.2s'}}>
                      {c.name}
                    </text>
                    {/* Metric value below label */}
                    <text x={c.x} y={c.y + r + 14}
                      fill={isTop ? '#e8c98a' : 'rgba(184,188,207,0.85)'}
                      fontSize="10"
                      fontFamily="Geist Mono"
                      textAnchor="middle"
                      style={{letterSpacing: '0.04em'}}>
                      {m.fmt(c[m.key])}
                    </text>
                  </g>
                );
              })}
            </g>
          </svg>

          {/* Legend */}
          <div className="geo-legend">
            <span className="geo-legend-label">Low</span>
            <div className="geo-legend-track">
              {[0.2, 0.4, 0.6, 0.8, 1].map((a, i) => (
                <div key={i} className="geo-legend-step" style={{background: `${m.hue}${Math.floor(a * 99).toString(16).padStart(2, '0')}`}}/>
              ))}
            </div>
            <span className="geo-legend-label">High</span>
            <span className="geo-legend-metric">· {m.label}</span>
          </div>

          {/* Hover tooltip */}
          {hover && (() => {
            const c = data.find(x => x.id === hover);
            if (!c) return null;
            return (
              <div className="geo-tooltip" style={{
                left: `${(c.x / 500) * 100}%`,
                top: `${(c.y / 500) * 100}%`
              }}>
                <div className="geo-tooltip-name">{c.name}</div>
                <div className="geo-tooltip-row"><span>Leads</span><span>{c.leads.toLocaleString()}</span></div>
                <div className="geo-tooltip-row"><span>Revenue</span><span style={{color: '#5dffb0'}}>£{c.revenue.toLocaleString()}</span></div>
                <div className="geo-tooltip-row"><span>Conversion</span><span style={{color: '#4be8ff'}}>{c.conv}%</span></div>
                <div className="geo-tooltip-row"><span>Bookings</span><span style={{color: '#8b6bff'}}>{c.bookings}</span></div>
              </div>
            );
          })()}
        </div>

        {/* Right rail */}
        <div className="geo-rail">
          {/* Summary */}
          <div className="geo-summary">
            <div className="geo-sum-card">
              <div className="lbl">Top region</div>
              <div className="val" style={{color: '#e8c98a'}}>{top.name}</div>
              <div className="sub">{m.fmt(top[m.key])} {m.label.toLowerCase()}</div>
            </div>
            <div className="geo-sum-card">
              <div className="lbl">Underperforming</div>
              <div className="val" style={{color: '#ffb14b'}}>{bottom.name}</div>
              <div className="sub">{m.fmt(bottom[m.key])} {m.label.toLowerCase()}</div>
            </div>
            <div className="geo-sum-card">
              <div className="lbl">Total {m.label.toLowerCase()}</div>
              <div className="val" style={{color: m.hue}}>{m.fmt(total)}</div>
              <div className="sub">across {data.length} regions</div>
            </div>
          </div>

          {/* Region list */}
          <div className="geo-rail-list">
            <div className="geo-rail-list-hd">REGIONS · BY {m.label.toUpperCase()}</div>
            {[...data].sort((a, b) => b[m.key] - a[m.key]).map((c, i) => (
              <div key={c.id}
                className={`geo-rail-row ${selected === c.id ? 'on' : ''}`}
                onMouseEnter={() => setHover(c.id)}
                onMouseLeave={() => setHover(null)}
                onClick={() => setSelected(s => s === c.id ? null : c.id)}
              >
                <span className="geo-rail-rank">#{i + 1}</span>
                <span className="geo-rail-name">{c.name}</span>
                <div className="geo-rail-bar">
                  <div className="geo-rail-bar-fill" style={{
                    width: `${(c[m.key] / max) * 100}%`,
                    background: c.color,
                    boxShadow: `0 0 6px ${c.color}80`
                  }}/>
                </div>
                <span className="geo-rail-val">{m.fmt(c[m.key])}</span>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

window.GeoHeatmap = GeoHeatmap;
window.UK_CITIES = UK_CITIES;
