// Aviation / data-inspired visual motifs. All monochromatic, low-opacity.
// Each component is a pure SVG decoration — safe to drop behind content.

const { useEffect, useRef, useState } = React;

// --------- Plotting grid w/ coordinate ticks on edges ---------
function PlottingGrid({ density = 10, opacity = 0.6 }) {
  const ticks = Array.from({ length: density });
  return (
    <svg className="motif-grid" width="100%" height="100%" preserveAspectRatio="none"
         style={{ position: 'absolute', inset: 0, opacity }}>
      <defs>
        <pattern id="plot-grid" width="40" height="40" patternUnits="userSpaceOnUse">
          <path d="M 40 0 L 0 0 0 40" fill="none" stroke="rgba(232,230,225,0.045)" strokeWidth="0.5"/>
        </pattern>
        <pattern id="plot-grid-major" width="160" height="160" patternUnits="userSpaceOnUse">
          <path d="M 160 0 L 0 0 0 160" fill="none" stroke="rgba(232,230,225,0.08)" strokeWidth="0.5"/>
        </pattern>
      </defs>
      <rect width="100%" height="100%" fill="url(#plot-grid)"/>
      <rect width="100%" height="100%" fill="url(#plot-grid-major)"/>
    </svg>
  );
}

// --------- Great-circle arc (route trace) ---------
function RouteArc({ d, strokeDasharray, animated = false, stroke = "rgba(232,230,225,0.18)", strokeWidth = 1 }) {
  return (
    <path d={d} fill="none" stroke={stroke} strokeWidth={strokeWidth}
          strokeLinecap="round" strokeDasharray={strokeDasharray}
          className={animated ? "route-animate" : ""} />
  );
}

// --------- Waypoint glyph (triangle) ---------
function Waypoint({ x, y, label, accent = false }) {
  const color = accent ? "var(--accent)" : "rgba(232,230,225,0.5)";
  return (
    <g transform={`translate(${x} ${y})`}>
      <path d="M 0 -5 L 4.3 2.5 L -4.3 2.5 Z" fill="none" stroke={color} strokeWidth="1"/>
      {label && (
        <text x="9" y="3" fontFamily="JetBrains Mono" fontSize="8.5"
              fill={color} letterSpacing="0.12em">{label}</text>
      )}
    </g>
  );
}

// --------- VOR / DME rose ---------
function VorRose({ x, y, r = 60 }) {
  const ticks = Array.from({ length: 36 }, (_, i) => i * 10);
  return (
    <g transform={`translate(${x} ${y})`} opacity="0.7">
      <circle r={r} fill="none" stroke="rgba(232,230,225,0.1)" strokeWidth="0.6"/>
      <circle r={r * 0.72} fill="none" stroke="rgba(232,230,225,0.06)" strokeWidth="0.4"/>
      {ticks.map((t, i) => {
        const rad = (t - 90) * Math.PI / 180;
        const inner = i % 3 === 0 ? r - 6 : r - 3;
        return (
          <line key={i}
                x1={Math.cos(rad) * inner} y1={Math.sin(rad) * inner}
                x2={Math.cos(rad) * r}     y2={Math.sin(rad) * r}
                stroke="rgba(232,230,225,0.25)" strokeWidth="0.6"/>
        );
      })}
      {["N","E","S","W"].map((d, i) => {
        const rad = (i * 90 - 90) * Math.PI / 180;
        const rx = Math.cos(rad) * (r + 12);
        const ry = Math.sin(rad) * (r + 12);
        return (
          <text key={d} x={rx} y={ry + 3} textAnchor="middle"
                fontFamily="JetBrains Mono" fontSize="9"
                fill="rgba(232,230,225,0.55)" letterSpacing="0.1em">{d}</text>
        );
      })}
      <circle r="1.6" fill="var(--accent)"/>
    </g>
  );
}

// --------- Hero background: route reconstruction scene ---------
function HeroCanvas() {
  // static, composed scene — flight path over a subtle graticule
  return (
    <svg className="hero-canvas" viewBox="0 0 1600 900" preserveAspectRatio="xMidYMid slice"
         style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', opacity: 1 }}>
      <defs>
        <pattern id="hero-graticule" width="80" height="80" patternUnits="userSpaceOnUse">
          <path d="M 80 0 L 0 0 0 80" fill="none" stroke="rgba(232,230,225,0.045)" strokeWidth="0.5"/>
        </pattern>
        <pattern id="hero-graticule-major" width="400" height="400" patternUnits="userSpaceOnUse">
          <path d="M 400 0 L 0 0 0 400" fill="none" stroke="rgba(232,230,225,0.08)" strokeWidth="0.6"/>
        </pattern>
        <radialGradient id="hero-mask" cx="50%" cy="55%" r="60%">
          <stop offset="0%" stopColor="white" stopOpacity="1"/>
          <stop offset="100%" stopColor="white" stopOpacity="0"/>
        </radialGradient>
        <mask id="hero-mask-apply">
          <rect width="1600" height="900" fill="url(#hero-mask)"/>
        </mask>
        <linearGradient id="accent-fade" x1="0%" y1="0%" x2="100%" y2="0%">
          <stop offset="0%" stopColor="oklch(0.78 0.09 75)" stopOpacity="0"/>
          <stop offset="60%" stopColor="oklch(0.78 0.09 75)" stopOpacity="0.8"/>
          <stop offset="100%" stopColor="oklch(0.78 0.09 75)" stopOpacity="1"/>
        </linearGradient>
      </defs>

      <g mask="url(#hero-mask-apply)">
        <rect width="1600" height="900" fill="url(#hero-graticule)"/>
        <rect width="1600" height="900" fill="url(#hero-graticule-major)"/>

        {/* graticule coordinate labels */}
        {[200, 600, 1000, 1400].map((x, i) => (
          <text key={x} x={x} y="24" fontFamily="JetBrains Mono" fontSize="9"
                fill="rgba(232,230,225,0.3)" letterSpacing="0.1em">
            {`${45 + i * 2}°00′N`}
          </text>
        ))}
        {[150, 450, 750].map((y, i) => (
          <text key={y} x="16" y={y} fontFamily="JetBrains Mono" fontSize="9"
                fill="rgba(232,230,225,0.3)" letterSpacing="0.1em">
            {`${8 + i * 3}°00′W`}
          </text>
        ))}

        {/* primary route — curved great-circle-ish */}
        <path d="M 120 680 Q 500 180, 1050 420 T 1520 280"
              fill="none" stroke="rgba(232,230,225,0.22)" strokeWidth="1.1"/>
        {/* echo / secondary trace - dashed projection */}
        <path d="M 120 680 Q 500 220, 1050 460 T 1520 320"
              fill="none" stroke="rgba(232,230,225,0.1)" strokeWidth="0.7"
              strokeDasharray="2 6"/>
        {/* highlighted segment */}
        <path d="M 820 460 Q 920 400, 1050 420"
              fill="none" stroke="url(#accent-fade)" strokeWidth="1.4"/>

        {/* waypoints */}
        <Waypoint x={120} y={680} label="ORIG"/>
        <Waypoint x={400} y={340} label="KENLI"/>
        <Waypoint x={720} y={300} label="BRAVO 04"/>
        <Waypoint x={1050} y={420} label="EVENT 14:32:08" accent/>
        <Waypoint x={1320} y={310} label="RECON END"/>
        <Waypoint x={1520} y={280} label="DEST"/>

        {/* DME rose */}
        <VorRose x={280} y={520} r={46}/>

        {/* altitude ladder — right side */}
        <g transform="translate(1540 420)">
          {[0, 1, 2, 3, 4, 5].map(i => (
            <g key={i}>
              <line x1="0" y1={i * 24} x2="10" y2={i * 24} stroke="rgba(232,230,225,0.25)" strokeWidth="0.6"/>
              <text x="16" y={i * 24 + 3} fontFamily="JetBrains Mono" fontSize="8"
                    fill="rgba(232,230,225,0.35)">
                {`FL${380 - i * 20}`}
              </text>
            </g>
          ))}
        </g>

        {/* time ticks across bottom */}
        <g transform="translate(0 840)">
          {Array.from({ length: 16 }).map((_, i) => (
            <g key={i} transform={`translate(${60 + i * 96} 0)`}>
              <line y1="0" y2={i % 4 === 0 ? 8 : 4} stroke="rgba(232,230,225,0.25)" strokeWidth="0.6"/>
              {i % 4 === 0 && (
                <text y="22" fontFamily="JetBrains Mono" fontSize="8"
                      fill="rgba(232,230,225,0.35)" textAnchor="middle">
                  {`14:${String(28 + i).padStart(2, '0')}:00`}
                </text>
              )}
            </g>
          ))}
        </g>
      </g>
    </svg>
  );
}

// --------- Scan line / crosshair for media placeholders ---------
function MediaCrosshair() {
  return (
    <svg width="100%" height="100%" preserveAspectRatio="none"
         style={{ position: 'absolute', inset: 0 }}>
      <line x1="0" y1="50%" x2="100%" y2="50%" stroke="rgba(232,230,225,0.06)" strokeWidth="0.6"/>
      <line x1="50%" y1="0" x2="50%" y2="100%" stroke="rgba(232,230,225,0.06)" strokeWidth="0.6"/>
    </svg>
  );
}

// --------- Media placeholder: labeled replacement slot ---------
function MediaSlot({ kind = "VIDEO", id = "MED-001", title, ratio, note, duration, frameRef, children, visual, image, images }) {
  if (images && images.length) {
    return (
      <div className={"media-slot media-slot-filled media-slot-stack"}>
        {images.map((src, i) => (
          <img key={i} src={src} alt={`${title || id} ${i+1}`}
               style={{ display: 'block', width: '100%', height: 'auto' }}/>
        ))}
        {children}
      </div>
    );
  }
  if (image) {
    return (
      <div className={"media-slot media-slot-filled"}>
        <img src={image} alt={title || id}
             style={{ display: 'block', width: '100%', height: 'auto' }}/>
        {children}
      </div>
    );
  }
  return (
    <div className={"media-slot"} style={ratio ? { aspectRatio: ratio } : undefined}>
      <div className="media-slot-grid"/>
      <MediaCrosshair/>
      {visual}
      <div className="media-slot-label">
        <span className="media-slot-label-dot"/>
        <span className="mono">{kind} · {id}</span>
      </div>
      <div className="media-slot-spec">
        {duration && <span className="mono">{duration}</span>}
        {frameRef && <span className="mono">{frameRef}</span>}
      </div>
      <div className="media-slot-center">
        {title && <span className="mono paper">{title}</span>}
        {note && <span className="mono" style={{opacity: 0.6}}>{note}</span>}
      </div>
      <div className="media-slot-dims">
        <span className="mono">REPLACE · /media/{id.toLowerCase()}</span>
      </div>
      {children}
    </div>
  );
}

// --------- Parameter plot (for work thumbnails & services) ---------
function ParamPlot({ seed = 1, traces = 2, grid = true }) {
  const W = 600, H = 360;
  const rng = (n) => {
    // simple deterministic noise
    let t = seed * 9301 + n * 49297;
    return ((t % 233280) / 233280);
  };
  const series = [];
  for (let s = 0; s < traces; s++) {
    const pts = [];
    let y = H * 0.5 + (rng(s) - 0.5) * 60;
    for (let i = 0; i <= 60; i++) {
      y += (rng(s * 100 + i) - 0.5) * 18;
      y = Math.max(40, Math.min(H - 40, y));
      pts.push(`${(i / 60) * W},${y}`);
    }
    series.push(pts.join(" "));
  }
  return (
    <svg viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="none"
         style={{ position: 'absolute', inset: 0, width: '100%', height: '100%' }}>
      {grid && (
        <>
          {[0.25, 0.5, 0.75].map(p => (
            <line key={p} x1="0" y1={H * p} x2={W} y2={H * p}
                  stroke="rgba(232,230,225,0.06)" strokeWidth="0.5"/>
          ))}
          {[0.2, 0.4, 0.6, 0.8].map(p => (
            <line key={p} x1={W * p} y1="0" x2={W * p} y2={H}
                  stroke="rgba(232,230,225,0.04)" strokeWidth="0.5"/>
          ))}
        </>
      )}
      {series.map((s, i) => (
        <polyline key={i} points={s}
                  stroke={i === 0 ? "rgba(232,230,225,0.55)" : "rgba(232,230,225,0.18)"}
                  strokeWidth={i === 0 ? "1" : "0.7"}
                  fill="none"/>
      ))}
    </svg>
  );
}

// --------- Mini route card visual (for work thumbnails) ---------
function MiniRoute({ seed = 1 }) {
  const W = 600, H = 360;
  const paths = [
    "M 40 280 Q 180 100, 380 200 T 560 100",
    "M 40 300 Q 200 220, 380 240 T 560 180",
    "M 60 60 Q 260 240, 420 140 T 560 260",
    "M 40 200 Q 240 80, 340 300 T 560 200"
  ];
  const d = paths[seed % paths.length];
  return (
    <svg viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="xMidYMid slice"
         style={{ position: 'absolute', inset: 0, width: '100%', height: '100%' }}>
      <defs>
        <pattern id={`mr-${seed}`} width="32" height="32" patternUnits="userSpaceOnUse">
          <path d="M 32 0 L 0 0 0 32" fill="none" stroke="rgba(232,230,225,0.04)" strokeWidth="0.5"/>
        </pattern>
      </defs>
      <rect width={W} height={H} fill={`url(#mr-${seed})`}/>
      <path d={d} fill="none" stroke="rgba(232,230,225,0.18)" strokeWidth="0.8"/>
      <path d={d} fill="none" stroke="rgba(232,230,225,0.45)" strokeWidth="0.8"
            strokeDasharray="3 200" strokeDashoffset="100"/>
      <Waypoint x="40" y={paths[seed % paths.length].includes("M 40 280") ? 280 : paths[seed % paths.length].includes("M 40 300") ? 300 : paths[seed % paths.length].includes("M 60 60") ? 60 : 200}/>
      <Waypoint x="560" y={paths[seed % paths.length].includes("560 100") ? 100 : paths[seed % paths.length].includes("560 180") ? 180 : paths[seed % paths.length].includes("560 260") ? 260 : 200} accent/>
    </svg>
  );
}

// --------- Brand mark ---------
// Image-based logo (Flight Reconstruction Group). The PNG includes the
// wordmark, so callers usually pass a height (e.g. 40-72px) and skip
// any adjacent text label.
function BrandMark({ size = 24, height }) {
  const h = height || size;
  return (
    <img
      src="media/logo.svg"
      alt="Flight Reconstruction Group"
      style={{ height: h, width: 'auto', display: 'block', flexShrink: 0, alignSelf: 'flex-start', maxWidth: '100%' }}
    />
  );
}

// Expose to other Babel scripts
Object.assign(window, {
  PlottingGrid, RouteArc, Waypoint, VorRose, HeroCanvas,
  MediaSlot, MediaCrosshair, ParamPlot, MiniRoute, BrandMark
});
