/* MANARA — UAE Map fallback (SVG)
   Stylized geographic outline + emirate labels + incident dots + patrol chevrons + heatmap blobs.
   Used when no Mapbox token is set. */

const { useState, useEffect, useRef, useMemo } = React;

// Approximate UAE outline path (simplified; lng/lat space mapped via project()):
// We render in viewBox 0 0 1000 600 and project lng [50.5, 57] x lat [21.5, 26.8].
const UAE_BOUNDS = { lngMin: 50.5, lngMax: 57.0, latMin: 21.5, latMax: 26.8 };
function project(lng, lat) {
  const x = ((lng - UAE_BOUNDS.lngMin) / (UAE_BOUNDS.lngMax - UAE_BOUNDS.lngMin)) * 1000;
  // invert lat (y grows downward)
  const y = 600 - ((lat - UAE_BOUNDS.latMin) / (UAE_BOUNDS.latMax - UAE_BOUNDS.latMin)) * 600;
  return [x, y];
}

// Highly simplified UAE coastline + interior outline (hand-built).
const UAE_PATH = `
M 540 470 L 555 480 L 575 488 L 605 480 L 640 472
L 670 466 L 700 458 L 730 446 L 758 432
L 786 418 L 810 405 L 838 388 L 858 372 L 870 356 L 880 336
L 884 312 L 880 290 L 868 268 L 854 248 L 838 232 L 818 220
L 798 212 L 776 210 L 754 214 L 732 222 L 712 232 L 696 240
L 680 246 L 660 252 L 638 256 L 615 258
L 600 256 L 588 252 L 580 244 L 575 232 L 572 218
L 568 200 L 562 184 L 550 170 L 532 158 L 510 148 L 488 142
L 462 138 L 432 138 L 398 142 L 362 150 L 322 162 L 282 174
L 246 188 L 214 204 L 188 222 L 168 240 L 152 258
L 142 278 L 138 298 L 142 316 L 152 332 L 168 346
L 188 358 L 212 368 L 240 376 L 270 382 L 304 388
L 340 392 L 378 396 L 416 400 L 450 406 L 478 414
L 502 422 L 522 432 L 536 446 L 540 460 Z`;

// Inner Al-Ain bulge / Oman border indent (decorative)
const UAE_INNER = `
M 630 360 L 660 364 L 686 374 L 698 392 L 700 412 L 692 432 L 670 444 L 644 446 L 624 438 L 612 422 L 610 402 L 614 384 L 622 370 Z`;

// Heat blobs — approximate density centers
const HEAT_BLOBS = [
  { lng: 55.27, lat: 25.20, r: 90, intensity: 0.9 },  // Dubai
  { lng: 54.37, lat: 24.48, r: 100, intensity: 0.85 }, // Abu Dhabi
  { lng: 55.40, lat: 25.34, r: 60, intensity: 0.7 },  // Sharjah
  { lng: 55.94, lat: 25.79, r: 50, intensity: 0.5 },  // RAK
  { lng: 55.76, lat: 24.21, r: 55, intensity: 0.55 }, // Al Ain
  { lng: 56.34, lat: 25.13, r: 45, intensity: 0.45 }  // Fujairah
];

const EMIRATE_LABELS = [
  { en: 'ABU DHABI', ar: 'أبوظبي', lng: 53.85, lat: 23.5 },
  { en: 'DUBAI', ar: 'دبي', lng: 55.27, lat: 25.05 },
  { en: 'SHARJAH', ar: 'الشارقة', lng: 55.55, lat: 25.45 },
  { en: 'AJMAN', ar: 'عجمان', lng: 55.60, lat: 25.55 },
  { en: 'UMM AL QUWAIN', ar: 'أم القيوين', lng: 55.75, lat: 25.65 },
  { en: 'RAS AL KHAIMAH', ar: 'رأس الخيمة', lng: 55.95, lat: 25.85 },
  { en: 'FUJAIRAH', ar: 'الفجيرة', lng: 56.30, lat: 25.30 },
  { en: 'AL AIN', ar: 'العين', lng: 55.76, lat: 24.21, sub: true }
];

function FallbackMap({ locale, focus, incidents, patrols, scenario, opCenters }) {
  const isAr = locale === 'ar';

  // Auto-cycle camera focal point label
  const focalCenter = useMemo(() => {
    if (scenario && scenario.mapCoords) return scenario.mapCoords;
    return null;
  }, [scenario]);

  return (
    <div style={{ position: 'absolute', inset: 0, overflow: 'hidden' }}>
      <svg
        viewBox="0 0 1000 600"
        preserveAspectRatio="xMidYMid slice"
        style={{ width: '100%', height: '100%', display: 'block' }}
      >
        <defs>
          {/* Subtle starfield gradient */}
          <radialGradient id="bgGlow" cx="50%" cy="50%" r="60%">
            <stop offset="0%" stopColor="#0F1A2E" />
            <stop offset="60%" stopColor="#070D1A" />
            <stop offset="100%" stopColor="#03060D" />
          </radialGradient>
          <radialGradient id="heatRed" cx="50%" cy="50%" r="50%">
            <stop offset="0%" stopColor="rgba(255,71,87,0.55)" />
            <stop offset="50%" stopColor="rgba(255,184,0,0.28)" />
            <stop offset="100%" stopColor="rgba(0,229,204,0)" />
          </radialGradient>
          <radialGradient id="heatTeal" cx="50%" cy="50%" r="50%">
            <stop offset="0%" stopColor="rgba(0,229,204,0.5)" />
            <stop offset="60%" stopColor="rgba(0,229,204,0.15)" />
            <stop offset="100%" stopColor="rgba(0,229,204,0)" />
          </radialGradient>
          <linearGradient id="landFill" x1="0%" y1="0%" x2="100%" y2="100%">
            <stop offset="0%" stopColor="#0E1830" stopOpacity="0.95" />
            <stop offset="100%" stopColor="#0A1224" stopOpacity="0.95" />
          </linearGradient>
          <pattern id="landGrid" x="0" y="0" width="20" height="20" patternUnits="userSpaceOnUse">
            <path d="M 20 0 L 0 0 0 20" fill="none" stroke="rgba(0,229,204,0.06)" strokeWidth="0.5" />
          </pattern>
          <filter id="softGlow">
            <feGaussianBlur stdDeviation="2.5" result="coloredBlur" />
            <feMerge>
              <feMergeNode in="coloredBlur" />
              <feMergeNode in="SourceGraphic" />
            </feMerge>
          </filter>
          <filter id="heatBlur">
            <feGaussianBlur stdDeviation="14" />
          </filter>
        </defs>

        {/* Backdrop */}
        <rect width="1000" height="600" fill="url(#bgGlow)" />

        {/* Subtle latitude/longitude grid */}
        <g opacity="0.18">
          {Array.from({ length: 12 }, (_, i) => (
            <line key={`vl-${i}`} x1={i * 90} y1="0" x2={i * 90} y2="600" stroke="rgba(0,229,204,0.18)" strokeWidth="0.4" strokeDasharray="2 6" />
          ))}
          {Array.from({ length: 8 }, (_, i) => (
            <line key={`hl-${i}`} x1="0" y1={i * 80} x2="1000" y2={i * 80} stroke="rgba(0,229,204,0.18)" strokeWidth="0.4" strokeDasharray="2 6" />
          ))}
        </g>

        {/* Heat blobs (under land) */}
        <g filter="url(#heatBlur)" opacity="0.85">
          {HEAT_BLOBS.map((b, i) => {
            const [x, y] = project(b.lng, b.lat);
            return (
              <circle
                key={`heat-${i}`}
                cx={x} cy={y}
                r={b.r}
                fill={b.intensity > 0.7 ? 'url(#heatRed)' : 'url(#heatTeal)'}
                opacity={b.intensity}
              />
            );
          })}
        </g>

        {/* UAE land mass */}
        <g>
          <path d={UAE_PATH} fill="url(#landFill)" stroke="rgba(0,229,204,0.4)" strokeWidth="1" />
          <path d={UAE_PATH} fill="url(#landGrid)" />
          <path d={UAE_INNER} fill="none" stroke="rgba(0,229,204,0.2)" strokeWidth="0.6" strokeDasharray="4 4" />
        </g>

        {/* Emirate labels */}
        <g style={{ fontFamily: isAr ? 'Tajawal, sans-serif' : 'JetBrains Mono, monospace', fontWeight: 600 }}>
          {EMIRATE_LABELS.map((e) => {
            const [x, y] = project(e.lng, e.lat);
            const text = isAr ? e.ar : e.en;
            return (
              <text
                key={e.en}
                x={x} y={y}
                fontSize={e.sub ? 10 : 12}
                fill={e.sub ? 'rgba(148,163,184,0.55)' : 'rgba(241,245,249,0.7)'}
                textAnchor="middle"
                letterSpacing="2"
              >
                {text}
              </text>
            );
          })}
        </g>

        {/* Op center markers (radar) */}
        <g>
          {opCenters.map((c) => {
            const [x, y] = project(c.lng, c.lat);
            const isFocus = scenario?.mapFocus === c.id;
            return (
              <g key={c.id} transform={`translate(${x},${y})`}>
                <circle r="4" fill="#00E5CC" opacity="0.9" />
                <circle r="8" fill="none" stroke="#00E5CC" strokeWidth="0.8" opacity="0.5" />
                {isFocus && (
                  <>
                    <circle r="14" fill="none" stroke="#00E5CC" strokeWidth="1.2">
                      <animate attributeName="r" from="14" to="48" dur="2.4s" repeatCount="indefinite" />
                      <animate attributeName="opacity" from="0.9" to="0" dur="2.4s" repeatCount="indefinite" />
                    </circle>
                    <circle r="14" fill="none" stroke="#00E5CC" strokeWidth="1.2">
                      <animate attributeName="r" from="14" to="48" dur="2.4s" begin="1.2s" repeatCount="indefinite" />
                      <animate attributeName="opacity" from="0.9" to="0" dur="2.4s" begin="1.2s" repeatCount="indefinite" />
                    </circle>
                  </>
                )}
              </g>
            );
          })}
        </g>

        {/* Patrol units (chevrons) */}
        <g>
          {patrols.map((p, i) => {
            const [x, y] = project(p.lng, p.lat);
            return (
              <g key={`p-${i}`} transform={`translate(${x},${y}) rotate(${p.heading})`} filter="url(#softGlow)">
                <path d="M 0 -4 L 4 4 L 0 2 L -4 4 Z" fill="#00E5CC" opacity="0.9" />
              </g>
            );
          })}
        </g>

        {/* Incidents */}
        <g>
          {incidents.map((inc, i) => {
            const [x, y] = project(inc.lng, inc.lat);
            const color = inc.severity === 'critical' ? '#FF4757' : inc.severity === 'warning' ? '#FFB800' : '#38BDF8';
            return (
              <g key={`i-${i}`} transform={`translate(${x},${y})`}>
                {inc.severity === 'critical' && (
                  <>
                    <circle r="6" fill="none" stroke="#FF4757" strokeWidth="1.5">
                      <animate attributeName="r" from="6" to="32" dur="2s" repeatCount="indefinite" />
                      <animate attributeName="opacity" from="0.9" to="0" dur="2s" repeatCount="indefinite" />
                    </circle>
                    <circle r="6" fill="none" stroke="#FF4757" strokeWidth="1.5">
                      <animate attributeName="r" from="6" to="32" dur="2s" begin="1s" repeatCount="indefinite" />
                      <animate attributeName="opacity" from="0.9" to="0" dur="2s" begin="1s" repeatCount="indefinite" />
                    </circle>
                  </>
                )}
                <circle r="5" fill={color} stroke="#0A1120" strokeWidth="1" />
                {inc.severity === 'critical' && <circle r="2.5" fill="#fff" opacity="0.9" />}
              </g>
            );
          })}
        </g>

        {/* Focus crosshair if scenario has coords */}
        {focalCenter && (() => {
          const [x, y] = project(focalCenter.lng, focalCenter.lat);
          return (
            <g opacity="0.85">
              <circle cx={x} cy={y} r="40" fill="none" stroke="rgba(255,71,87,0.4)" strokeWidth="1" strokeDasharray="3 4" />
              <line x1={x - 60} y1={y} x2={x - 12} y2={y} stroke="rgba(255,71,87,0.6)" strokeWidth="1" />
              <line x1={x + 12} y1={y} x2={x + 60} y2={y} stroke="rgba(255,71,87,0.6)" strokeWidth="1" />
              <line x1={x} y1={y - 60} x2={x} y2={y - 12} stroke="rgba(255,71,87,0.6)" strokeWidth="1" />
              <line x1={x} y1={y + 12} x2={x} y2={y + 60} stroke="rgba(255,71,87,0.6)" strokeWidth="1" />
            </g>
          );
        })()}

        {/* Compass */}
        <g transform="translate(940, 60)" opacity="0.5">
          <circle r="22" fill="none" stroke="rgba(0,229,204,0.4)" strokeWidth="0.6" />
          <text y="-26" textAnchor="middle" fill="#00E5CC" fontSize="10" fontFamily="JetBrains Mono">N</text>
          <path d="M 0 -16 L 4 0 L 0 -4 L -4 0 Z" fill="#00E5CC" />
        </g>

        {/* Scale bar */}
        <g transform="translate(60, 540)" fontFamily="JetBrains Mono" fontSize="9" fill="rgba(148,163,184,0.6)">
          <line x1="0" y1="0" x2="120" y2="0" stroke="rgba(148,163,184,0.5)" strokeWidth="1" />
          <line x1="0" y1="-3" x2="0" y2="3" stroke="rgba(148,163,184,0.5)" strokeWidth="1" />
          <line x1="60" y1="-2" x2="60" y2="2" stroke="rgba(148,163,184,0.5)" strokeWidth="1" />
          <line x1="120" y1="-3" x2="120" y2="3" stroke="rgba(148,163,184,0.5)" strokeWidth="1" />
          <text x="0" y="14">0</text>
          <text x="60" y="14" textAnchor="middle">50</text>
          <text x="120" y="14" textAnchor="middle">100 km</text>
        </g>
      </svg>
    </div>
  );
}

window.FallbackMap = FallbackMap;
