// diagram.jsx — Animated P2P link diagram, topo map, photo placeholder

const StarLogo = ({ size = 28, color = 'currentColor' }) => (
  <svg viewBox="0 0 28 28" width={size} height={size} aria-hidden="true">
    {/* radio tower abstracted into 4-point star + signal arcs */}
    <g stroke={color} strokeWidth="1.4" fill="none" strokeLinecap="round">
      <path d="M14 4 L14 24" />
      <path d="M4 14 L24 14" />
      <circle cx="14" cy="14" r="2.4" fill={color} stroke="none" />
      <path d="M8 14 a6 6 0 0 1 6 -6" opacity="0.55" />
      <path d="M20 14 a6 6 0 0 1 -6 6" opacity="0.55" />
    </g>
  </svg>
);

// ── Animated P2P link diagram ───────────────────────────────────────
// Two ridge silhouettes, towers on each, a beam between them, packets
// moving along the link. Scales to its container.
function P2PDiagram({ compact = false }) {
  // SVG viewBox 800x500
  const ridgeA = "M 0 380 L 60 320 L 110 290 L 170 310 L 230 250 L 290 230 L 340 260 L 400 220 L 400 500 L 0 500 Z";
  const ridgeB = "M 400 220 L 460 240 L 510 200 L 580 215 L 650 175 L 720 195 L 780 165 L 800 175 L 800 500 L 400 500 Z";

  // far ridges (for depth)
  const farRidge = "M 0 320 L 80 280 L 140 295 L 220 250 L 320 270 L 410 230 L 500 250 L 600 215 L 700 240 L 800 220 L 800 500 L 0 500 Z";

  // Tower coords (top of antenna)
  const towerA = { x: 230, y: 250, top: 175 };
  const towerB = { x: 650, y: 175, top: 100 };

  // Customer house — sits in the valley below Hill B
  const house = { x: 730, y: 300, dish: { x: 738, y: 286 } };

  // Link line: A radio → B radio
  const linkPath = `M ${towerA.x} ${towerA.top} L ${towerB.x} ${towerB.top}`;
  // Last-mile: B radio → customer dish
  const lastMilePath = `M ${towerB.x} ${towerB.top} L ${house.dish.x} ${house.dish.y}`;

  return (
    <svg viewBox="0 0 800 500" width="100%" height="100%" preserveAspectRatio="xMidYMid slice"
         style={{ display: 'block' }}>
      <defs>
        <linearGradient id="sky" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="var(--bg)" />
          <stop offset="100%" stopColor="var(--bg-2)" />
        </linearGradient>
        <linearGradient id="ridgeFar" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="color-mix(in oklab, var(--ink) 14%, var(--bg))" />
          <stop offset="100%" stopColor="color-mix(in oklab, var(--ink) 6%, var(--bg))" />
        </linearGradient>
        <linearGradient id="ridgeMid" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="color-mix(in oklab, var(--ink) 28%, var(--bg))" />
          <stop offset="100%" stopColor="color-mix(in oklab, var(--ink) 16%, var(--bg))" />
        </linearGradient>
        <linearGradient id="ridgeNear" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="color-mix(in oklab, var(--ink) 50%, var(--bg))" />
          <stop offset="100%" stopColor="color-mix(in oklab, var(--ink) 30%, var(--bg))" />
        </linearGradient>
      </defs>

      {/* Sky */}
      <rect x="0" y="0" width="800" height="500" fill="url(#sky)" />

      {/* Subtle stars/grid in sky */}
      <g opacity="0.35">
        {[[120,60],[260,40],[420,80],[560,55],[700,90],[180,110],[340,120],[480,140],[620,135]].map(([x,y],i)=>(
          <circle key={i} cx={x} cy={y} r="1" fill="var(--ink-3)" />
        ))}
      </g>

      {/* Far ridge */}
      <path d={farRidge} fill="url(#ridgeFar)" />

      {/* Mid ridges (the two stations sit on these) */}
      <path d={ridgeA} fill="url(#ridgeMid)" />
      <path d={ridgeB} fill="url(#ridgeMid)" />

      {/* Tower A */}
      <Tower x={towerA.x} y={towerA.y} top={towerA.top} label="HILL A" labelOffset={-1} />
      {/* Tower B */}
      <Tower x={towerB.x} y={towerB.y} top={towerB.top} label="HILL B" labelOffset={1} />

      {/* Distance annotation */}
      <g fontFamily="var(--font-mono)" fontSize="11" fill="var(--ink-3)">
        <line x1={towerA.x + 12} y1={towerA.top - 18} x2={towerB.x - 12} y2={towerB.top - 18}
              stroke="var(--ink-3)" strokeWidth="0.5" strokeDasharray="2 3" />
        <rect x="395" y="105" width="80" height="22" rx="11"
              fill="var(--bg)" stroke="var(--line)" />
        <text x="435" y="120" textAnchor="middle">14.3 km</text>
      </g>

      {/* Active link line — A → B */}
      <path d={linkPath}
            stroke="var(--accent)" strokeWidth="1.5"
            fill="none" className="signal-line" />
      <path d={linkPath}
            stroke="var(--accent)" strokeWidth="0.5"
            fill="none" opacity="0.4" />

      {/* Last-mile link — B → house */}
      <path d={lastMilePath}
            stroke="var(--accent)" strokeWidth="1.5"
            fill="none" className="signal-line" />
      <path d={lastMilePath}
            stroke="var(--accent)" strokeWidth="0.5"
            fill="none" opacity="0.4" />

      {/* Pulse rings on each radio endpoint */}
      <circle cx={towerA.x} cy={towerA.top} r="6"
              fill="none" stroke="var(--accent)" strokeWidth="1.2" className="pulse-ring" />
      <circle cx={towerB.x} cy={towerB.top} r="6"
              fill="none" stroke="var(--accent)" strokeWidth="1.2" className="pulse-ring delay" />
      <circle cx={house.dish.x} cy={house.dish.y} r="5"
              fill="none" stroke="var(--accent)" strokeWidth="1" className="pulse-ring" />

      {/* Moving packets — A → B */}
      <g style={{ offsetPath: `path('${linkPath}')`, animation: 'packetMove 3.2s linear infinite' }}>
        <rect x="-6" y="-3" width="12" height="6" rx="1" fill="var(--accent)" />
      </g>
      <g style={{ offsetPath: `path('${linkPath}')`, animation: 'packetMove 3.2s linear infinite', animationDelay: '1.4s' }}>
        <rect x="-6" y="-3" width="12" height="6" rx="1" fill="var(--accent)" />
      </g>

      {/* Moving packet — B → house (last mile) */}
      <g style={{ offsetPath: `path('${lastMilePath}')`, animation: 'packetMove 2s linear infinite', animationDelay: '0.6s' }}>
        <rect x="-5" y="-2.5" width="10" height="5" rx="1" fill="var(--accent)" />
      </g>

      {/* Last-mile distance label */}
      <g fontFamily="var(--font-mono)" fontSize="10" fill="var(--ink-3)">
        <rect x={(towerB.x + house.dish.x) / 2 - 24} y={(towerB.top + house.dish.y) / 2 - 24}
              width="48" height="18" rx="9"
              fill="var(--bg)" stroke="var(--line)" />
        <text x={(towerB.x + house.dish.x) / 2} y={(towerB.top + house.dish.y) / 2 - 12}
              textAnchor="middle">2.1 km</text>
      </g>

      {/* Customer house at base of Hill B — with roof dish aimed back at tower B */}
      <House x={house.x} y={house.y} aimX={towerB.x} aimY={towerB.top} />

      {/* Subtle measurement: signal strength */}
      <g fontFamily="var(--font-mono)" fontSize="10" fill="var(--ink-3)">
        <text x={28} y={460}>LAT  −44.6912° S</text>
        <text x={28} y={478}>LNG  170.1018° E</text>
        <text x={680} y={460} textAnchor="end">RSSI  −58 dBm</text>
        <text x={680} y={478} textAnchor="end">LINK  ESTABLISHED</text>
        <circle cx={690} cy={475} r="3" fill="var(--accent)" className="blink" />
      </g>
    </svg>
  );
}

function Tower({ x, y, top, label, labelOffset = -1 }) {
  // simple lattice tower: triangle silhouette + dish
  return (
    <g>
      {/* Tower legs */}
      <path d={`M ${x-7} ${y} L ${x} ${top} L ${x+7} ${y}`}
            stroke="var(--ink)" strokeWidth="1" fill="none" />
      <path d={`M ${x-4} ${y-15} L ${x+4} ${y-15} M ${x-3} ${y-30} L ${x+3} ${y-30} M ${x-2} ${y-45} L ${x+2} ${y-45}`}
            stroke="var(--ink)" strokeWidth="0.7" />
      {/* Dish */}
      <ellipse cx={x + (labelOffset > 0 ? -8 : 8)} cy={top + 6} rx="6" ry="3.5"
               transform={`rotate(${labelOffset > 0 ? 20 : -20} ${x} ${top+6})`}
               fill="var(--ink)" />
      {/* Antenna spike */}
      <line x1={x} y1={top} x2={x} y2={top - 8}
            stroke="var(--ink)" strokeWidth="1" />

      {/* Label */}
      <g fontFamily="var(--font-mono)" fontSize="10" fill="var(--ink-2)">
        <text x={x} y={y + 22} textAnchor="middle">{label}</text>
      </g>
    </g>
  );
}

function House({ x, y, aimX, aimY }) {
  // Dish sits on roof corner closest to the tower; rotated to point at it.
  const dishX = x + 8;
  const dishMountY = y - 16;
  const dishY = y - 20;
  // Angle from dish to aim point (degrees). 0deg = pointing right.
  const angle = (aimX != null && aimY != null)
    ? Math.atan2(aimY - dishY, aimX - dishX) * 180 / Math.PI
    : -90;
  return (
    <g>
      {/* House body */}
      <g stroke="var(--ink)" strokeWidth="1" fill="var(--bg)">
        <path d={`M ${x-14} ${y} L ${x-14} ${y-12} L ${x} ${y-24} L ${x+14} ${y-12} L ${x+14} ${y} Z`} />
        <rect x={x-3} y={y-10} width="6" height="10" fill="var(--ink)" stroke="none" />
        <rect x={x-11} y={y-9} width="5" height="5" fill="none" />
        <rect x={x+6} y={y-9} width="5" height="5" fill="none" />
      </g>
      {/* Dish mast */}
      <line x1={dishX} y1={dishMountY} x2={dishX} y2={dishY}
            stroke="var(--ink)" strokeWidth="1" />
      {/* Dish — rotated to face the tower */}
      <g transform={`translate(${dishX} ${dishY}) rotate(${angle})`}>
        {/* dish bowl, opening faces +x (toward tower) */}
        <path d="M 0 -3 A 3 3 0 0 1 0 3 L -1 3 A 3 3 0 0 0 -1 -3 Z"
              fill="var(--ink)" stroke="var(--ink)" strokeWidth="0.4" />
        {/* feed */}
        <line x1="-1" y1="0" x2="2.5" y2="0" stroke="var(--ink)" strokeWidth="0.6" />
        <circle cx="2.5" cy="0" r="0.7" fill="var(--ink)" />
      </g>
    </g>
  );
}

// ── Topographic map (hero variant + coverage map) ───────────────────
function TopoMap({ withPins = true, dense = false }) {
  // Generate concentric topo lines mimicking ridges. Procedural.
  const layers = [];
  const seed = 1.7;
  for (let i = 0; i < 14; i++) {
    const y = 40 + i * 32;
    const amp = 18 + (i % 4) * 8;
    const path = makeWave(800, y, amp, 4 + (i % 3), i * seed);
    layers.push(<path key={`a-${i}`} d={path}
                      stroke="var(--ink)" strokeOpacity={0.18}
                      fill="none" strokeWidth="0.6" />);
  }
  // Diagonal contour cluster (a hill)
  const hills = [
    { cx: 220, cy: 240, n: 6, r: 30 },
    { cx: 580, cy: 180, n: 7, r: 36 },
    { cx: 460, cy: 360, n: 5, r: 26 },
  ];

  return (
    <svg viewBox="0 0 800 500" width="100%" height="100%" preserveAspectRatio="xMidYMid slice"
         style={{ display: 'block' }}>
      {/* Background */}
      <rect x="0" y="0" width="800" height="500" fill="var(--bg-2)" />

      {/* Contour bands */}
      <g>{layers}</g>

      {/* Hills (closed loops) */}
      {hills.map((h, idx) => (
        <g key={idx}>
          {Array.from({ length: h.n }).map((_, j) => (
            <ellipse key={j} cx={h.cx} cy={h.cy}
                     rx={h.r + j * 12}
                     ry={(h.r + j * 12) * 0.62}
                     fill="none" stroke="var(--ink)" strokeOpacity={0.22 - j * 0.025}
                     strokeWidth="0.6" />
          ))}
          <circle cx={h.cx} cy={h.cy} r="2" fill="var(--ink)" />
        </g>
      ))}

      {/* Grid ticks at edges */}
      <g fontFamily="var(--font-mono)" fontSize="9" fill="var(--ink-3)">
        {[170.05, 170.10, 170.15, 170.20, 170.25].map((v, i) => (
          <text key={`x-${i}`} x={20 + i * 180} y="490">{v.toFixed(2)}°E</text>
        ))}
        <text x="14" y="60" transform="rotate(-90 14 60)">−44.65°S</text>
        <text x="14" y="240" transform="rotate(-90 14 240)">−44.70°S</text>
        <text x="14" y="420" transform="rotate(-90 14 420)">−44.75°S</text>
      </g>

      {withPins && <CoveragePins />}

      {/* Compass */}
      <g transform="translate(740 60)" fontFamily="var(--font-mono)" fontSize="9" fill="var(--ink-2)">
        <circle r="22" fill="none" stroke="var(--ink-3)" strokeWidth="0.5" />
        <path d="M 0 -18 L 4 0 L 0 18 L -4 0 Z" fill="var(--ink)" opacity="0.6" />
        <text x="0" y="-26" textAnchor="middle">N</text>
      </g>
    </svg>
  );
}

function CoveragePins() {
  // Repeater stations + customer endpoints
  const sites = [
    { x: 220, y: 240, type: 'tower', label: 'WEDDERBURN' },
    { x: 580, y: 180, type: 'tower', label: 'OBELISK' },
    { x: 460, y: 360, type: 'tower', label: 'ROCK & PILLAR' },
  ];
  const customers = [
    { x: 320, y: 290 }, { x: 280, y: 200 }, { x: 380, y: 220 },
    { x: 510, y: 260 }, { x: 620, y: 280 }, { x: 540, y: 130 },
    { x: 410, y: 300 }, { x: 360, y: 400 }, { x: 600, y: 380 },
    { x: 680, y: 230 }, { x: 200, y: 320 }, { x: 720, y: 320 },
  ];
  return (
    <g>
      {/* Backbone links */}
      <g stroke="var(--accent)" strokeWidth="1" fill="none" opacity="0.7">
        <line x1={sites[0].x} y1={sites[0].y} x2={sites[1].x} y2={sites[1].y}
              className="signal-line" />
        <line x1={sites[1].x} y1={sites[1].y} x2={sites[2].x} y2={sites[2].y}
              className="signal-line" />
        <line x1={sites[0].x} y1={sites[0].y} x2={sites[2].x} y2={sites[2].y}
              strokeOpacity="0.4" strokeDasharray="2 4" />
      </g>

      {/* Customer fans */}
      <g stroke="var(--ink)" strokeWidth="0.4" opacity="0.25">
        {customers.map((c, i) => {
          // pick nearest tower
          const nearest = sites.reduce((a, b) =>
            Math.hypot(b.x - c.x, b.y - c.y) < Math.hypot(a.x - c.x, a.y - c.y) ? b : a
          );
          return <line key={i} x1={c.x} y1={c.y} x2={nearest.x} y2={nearest.y} />;
        })}
      </g>

      {/* Customers */}
      {customers.map((c, i) => (
        <circle key={i} cx={c.x} cy={c.y} r="2.5" fill="var(--ink-2)" />
      ))}

      {/* Towers */}
      {sites.map((s, i) => (
        <g key={i}>
          <circle cx={s.x} cy={s.y} r="14" fill="none" stroke="var(--accent)" strokeWidth="0.6" opacity="0.4" />
          <circle cx={s.x} cy={s.y} r="22" fill="none" stroke="var(--accent)" strokeWidth="0.4" opacity="0.2" />
          <rect x={s.x - 5} y={s.y - 5} width="10" height="10"
                fill="var(--bg)" stroke="var(--accent)" strokeWidth="1.2"
                transform={`rotate(45 ${s.x} ${s.y})`} />
          <circle cx={s.x} cy={s.y} r="1.5" fill="var(--accent)" />
          <text x={s.x + 18} y={s.y + 4}
                fontFamily="var(--font-mono)" fontSize="9"
                fill="var(--ink-2)">{s.label}</text>
        </g>
      ))}
    </g>
  );
}

// helper
function makeWave(width, baseY, amp, freq, phase) {
  let d = `M 0 ${baseY}`;
  const steps = 40;
  for (let i = 1; i <= steps; i++) {
    const x = (i / steps) * width;
    const y = baseY + Math.sin(i / steps * freq * Math.PI * 2 + phase) * amp;
    d += ` L ${x.toFixed(1)} ${y.toFixed(1)}`;
  }
  return d;
}

// ── Photo placeholder (striped, with mono caption) ──────────────────
function PhotoPlaceholder({ caption = 'PHOTO PLACEHOLDER', aspect }) {
  const styleObj = aspect ? { aspectRatio: aspect } : { height: '100%' };
  return (
    <div style={{
      ...styleObj,
      width: '100%',
      position: 'relative',
      background: `repeating-linear-gradient(135deg,
        color-mix(in oklab, var(--ink) 8%, var(--bg-2)) 0 10px,
        color-mix(in oklab, var(--ink) 4%, var(--bg-2)) 10px 20px)`,
      borderRadius: 'inherit',
      overflow: 'hidden',
    }}>
      <div style={{
        position:'absolute', inset:0,
        display:'flex', alignItems:'center', justifyContent:'center',
        flexDirection:'column', gap: 8,
      }}>
        <div style={{
          fontFamily:'var(--font-mono)', fontSize: 11,
          letterSpacing: '0.1em', color: 'var(--ink-3)',
        }}>{caption}</div>
        <div style={{
          width: 32, height: 1, background: 'var(--ink-3)', opacity: 0.5,
        }} />
        <div style={{
          fontFamily:'var(--font-mono)', fontSize: 10,
          color: 'var(--ink-3)', opacity: 0.6,
        }}>4000 × 3000 · ƒ/4 · ISO 200</div>
      </div>
    </div>
  );
}

Object.assign(window, { StarLogo, P2PDiagram, TopoMap, PhotoPlaceholder });
