/* global React */
// ============================================================
// Inframind product mockup — enterprise dashboard
// Renders a realistic-looking inspection UI with point cloud,
// defect list, risk panel, and export bar.
// ============================================================

const { useMemo } = React;

// --- Point cloud SVG (tunnel cross-section, falling into perspective) ---
function PointCloud({ defectMode = "all" }) {
  // Pre-generate point cloud points deterministically so they don't reshuffle on render
  const points = useMemo(() => generateTunnelPoints(), []);

  return (
    <svg
      viewBox="0 0 720 380"
      preserveAspectRatio="xMidYMid slice"
      style={{ position: "absolute", inset: 0, width: "100%", height: "100%" }}
    >
      <defs>
        <linearGradient id="depthFade" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0" stopColor="#22D3EE" stopOpacity="0.9" />
          <stop offset="0.6" stopColor="#3B82F6" stopOpacity="0.55" />
          <stop offset="1" stopColor="#1D4FD7" stopOpacity="0.15" />
        </linearGradient>
        <radialGradient id="vignette" cx="50%" cy="55%" r="60%">
          <stop offset="0" stopColor="#0A1422" stopOpacity="0" />
          <stop offset="1" stopColor="#050C18" stopOpacity="0.9" />
        </radialGradient>
      </defs>

      {/* Tunnel arch ribs at increasing depth */}
      {[0.05, 0.18, 0.32, 0.46, 0.6, 0.74, 0.86].map((t, i) => {
        const scale = 1 - t * 0.78;
        const cx = 360;
        const cy = 220 - t * 90;
        const rx = 300 * scale;
        const ry = 160 * scale;
        return (
          <ellipse
            key={i}
            cx={cx} cy={cy}
            rx={rx} ry={ry}
            fill="none"
            stroke={`rgba(34,211,238,${0.35 - t * 0.32})`}
            strokeWidth="0.6"
          />
        );
      })}

      {/* Cloud points */}
      {points.map((p, i) => (
        <circle
          key={i}
          cx={p.x} cy={p.y}
          r={p.r}
          fill="url(#depthFade)"
          opacity={p.o}
        />
      ))}

      {/* Centreline / measurement axis */}
      <line x1="360" y1="60" x2="360" y2="360" stroke="rgba(34,211,238,0.18)" strokeDasharray="3 4" />

      {/* Defect markers */}
      {DEFECTS.filter(d => defectMode === "all" || d.sev === defectMode).map((d, i) => (
        <g key={i}>
          {/* halo */}
          <circle cx={d.x} cy={d.y} r="14" fill={d.color} opacity="0.12" />
          <circle cx={d.x} cy={d.y} r="7" fill={d.color} opacity="0.32" />
          <circle cx={d.x} cy={d.y} r="3" fill={d.color} />
          {/* leader line + label */}
          <line x1={d.x} y1={d.y} x2={d.lx} y2={d.ly} stroke={d.color} strokeWidth="0.6" opacity="0.65" />
          <g transform={`translate(${d.lx}, ${d.ly})`}>
            <rect x="-1" y="-9" width={d.lw} height="14" fill="rgba(8,17,31,0.85)" stroke={d.color} strokeOpacity="0.5" />
            <text x="4" y="1" fontFamily="IBM Plex Mono, monospace" fontSize="9" fill={d.color} dominantBaseline="middle">
              {d.label}
            </text>
          </g>
        </g>
      ))}

      <rect x="0" y="0" width="720" height="380" fill="url(#vignette)" />
    </svg>
  );
}

function generateTunnelPoints() {
  const pts = [];
  // seeded pseudo-random
  let seed = 1;
  const rand = () => {
    seed = (seed * 9301 + 49297) % 233280;
    return seed / 233280;
  };

  // Generate tunnel surface (arch projected backwards)
  for (let depth = 0; depth < 1; depth += 0.012) {
    const scale = 1 - depth * 0.78;
    const cy = 220 - depth * 90;
    const ringPoints = Math.floor(80 + (1 - depth) * 80);
    for (let j = 0; j < ringPoints; j++) {
      const angle = (j / ringPoints) * Math.PI;
      const jitter = (rand() - 0.5) * 8 * scale;
      const x = 360 + Math.cos(Math.PI - angle) * (300 * scale) + jitter;
      const y = cy + Math.sin(Math.PI - angle) * (-160 * scale) + (rand() - 0.5) * 3;
      // Skip points outside view
      if (x < -10 || x > 730 || y < -10 || y > 390) continue;
      pts.push({
        x, y,
        r: 0.4 + rand() * 0.8,
        o: 0.18 + (1 - depth) * 0.5
      });
    }
  }
  // Floor plane points
  for (let i = 0; i < 600; i++) {
    const depth = rand();
    const scale = 1 - depth * 0.78;
    const x = 360 + (rand() - 0.5) * 600 * scale;
    const y = 220 - depth * 90 + 160 * scale + (rand() - 0.5) * 6;
    pts.push({
      x, y,
      r: 0.3 + rand() * 0.6,
      o: 0.1 + (1 - depth) * 0.35
    });
  }
  return pts;
}

const DEFECTS = [
  { x: 220, y: 180, color: "#EF4444", lx: 60,  ly: 120, lw: 96, label: "CR-04 12.8mm" },
  { x: 460, y: 150, color: "#F59E0B", lx: 540, ly: 100, lw: 100, label: "SP-12 4.2mm" },
  { x: 380, y: 280, color: "#22D3EE", lx: 480, ly: 320, lw: 96, label: "DF-02 1.6mm" },
  { x: 280, y: 240, color: "#F59E0B", lx: 120, ly: 280, lw: 96, label: "CR-07 5.2mm" },
  { x: 420, y: 210, color: "#EF4444", lx: 580, ly: 200, lw: 100, label: "ML-03 32mm" },
].map(d => ({ ...d, sev:
  d.color === "#EF4444" ? "high" :
  d.color === "#F59E0B" ? "med" : "low"
}));

// --- Sparkline / asset health trend ---
function Sparkline({ color = "#22D3EE", trend = "down" }) {
  // 24 values, generally trending down (deterioration)
  const data = trend === "down"
    ? [78, 76, 77, 75, 73, 74, 72, 70, 71, 68, 67, 68, 65, 64, 63, 64, 61, 60, 58, 59, 57, 55, 54, 52]
    : [42, 44, 43, 46, 48, 47, 49, 52, 51, 54, 56, 55, 58, 60, 59, 62, 64, 63, 66, 68, 67, 70, 72, 74];
  const max = Math.max(...data), min = Math.min(...data);
  const w = 220, h = 36, pad = 2;
  const xStep = (w - pad * 2) / (data.length - 1);
  const path = data.map((v, i) => {
    const x = pad + i * xStep;
    const y = pad + (1 - (v - min) / (max - min)) * (h - pad * 2);
    return `${i === 0 ? "M" : "L"}${x.toFixed(1)},${y.toFixed(1)}`;
  }).join(" ");
  const area = `${path} L${w - pad},${h} L${pad},${h} Z`;
  return (
    <svg viewBox={`0 0 ${w} ${h}`} preserveAspectRatio="none" className="sparkline">
      <defs>
        <linearGradient id="sparkfill" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0" stopColor={color} stopOpacity="0.3" />
          <stop offset="1" stopColor={color} stopOpacity="0" />
        </linearGradient>
      </defs>
      <path d={area} fill="url(#sparkfill)" />
      <path d={path} fill="none" stroke={color} strokeWidth="1.2" />
    </svg>
  );
}

// --- The dashboard itself ---
function Dashboard({ mode = "tunnel" }) {
  const filterMode = mode === "high" ? "high" : "all";
  return (
    <div className="dashboard" role="img" aria-label="Inframind inspection dashboard">
      {/* Title bar */}
      <div className="dash-titlebar">
        <div className="dots"><span></span><span></span><span></span></div>
        <div className="path">inframind / projects / a13-northbound / tunnel-segment-04</div>
        <div className="right">
          <span className="pill">live</span>
          <span style={{color: "#6A7B97"}}>↻ updated 2m ago</span>
        </div>
      </div>

      {/* Main canvas + sidebars */}
      <div className="dash-main">
        <aside className="dash-aside">
          <div>
            <div className="dash-section-label">Project</div>
            <div style={{marginTop: 8, fontSize: 13, color: "#C8D2E4", fontWeight: 500}}>A13 Northbound</div>
            <div style={{fontFamily: "IBM Plex Mono, monospace", fontSize: 10, color: "#6A7B97", marginTop: 2}}>PRJ-2026-014</div>
          </div>

          <div>
            <div className="dash-section-label">Assets</div>
            <div className="dash-asset-tree" style={{marginTop: 8}}>
              <div className="dash-asset"><span className="icon"></span>Tunnels (3)</div>
              <div className="dash-asset child active"><span className="icon"></span>Segment 04</div>
              <div className="dash-asset child"><span className="icon"></span>Segment 05</div>
              <div className="dash-asset child"><span className="icon"></span>Segment 06</div>
              <div className="dash-asset"><span className="icon"></span>Bridges (7)</div>
              <div className="dash-asset"><span className="icon"></span>Drainage (12)</div>
            </div>
          </div>

          <div>
            <div className="dash-section-label">Data layers</div>
            <div style={{display: "flex", flexDirection: "column", gap: 4, marginTop: 8, fontSize: 11, fontFamily: "IBM Plex Mono, monospace", color: "#C8D2E4"}}>
              <label style={{display: "flex", gap: 6, alignItems: "center"}}><span style={{width: 8, height: 8, background: "#22D3EE"}} /> LiDAR · ON</label>
              <label style={{display: "flex", gap: 6, alignItems: "center"}}><span style={{width: 8, height: 8, background: "#6A7B97"}} /> Imagery · OFF</label>
              <label style={{display: "flex", gap: 6, alignItems: "center"}}><span style={{width: 8, height: 8, background: "#EF4444"}} /> Defects · ON</label>
            </div>
          </div>
        </aside>

        {/* Center: point cloud canvas */}
        <div className="dash-canvas">
          <div className="canvas-grid" />
          <PointCloud defectMode={filterMode} />

          <div className="canvas-tools">
            <div className="tool active">⊞</div>
            <div className="tool">◎</div>
            <div className="tool">↔</div>
            <div className="tool">⊕</div>
          </div>

          <div className="canvas-readout">
            <div>chainage <span className="v">412.6 m</span></div>
            <div>x,y,z <span className="v">−0.82, 2.14, 4.06</span></div>
            <div>density <span className="v">1.4M pts / m³</span></div>
          </div>

          <div className="legend">
            <span><span className="sw" style={{background: "#EF4444"}}></span> high</span>
            <span><span className="sw" style={{background: "#F59E0B"}}></span> medium</span>
            <span><span className="sw" style={{background: "#22D3EE"}}></span> low</span>
          </div>
        </div>

        {/* Right side panel */}
        <aside className="dash-side">
          <div>
            <div className="dash-section-label">Asset health</div>
            <div className="risk-score" style={{marginTop: 8}}>
              <span className="num">72</span>
              <span className="delta">▼ 4 pts · 30d</span>
            </div>
            <div className="risk-bar" style={{marginTop: 8}}>
              <span></span><span></span><span></span>
            </div>
            <div className="risk-meta" style={{marginTop: 6}}>
              <span>good · 60</span>
              <span>watch · 20</span>
              <span>act · 20</span>
            </div>
            <Sparkline color="#22D3EE" />
          </div>

          <div>
            <div className="dash-section-label" style={{display: "flex", justifyContent: "space-between"}}>
              <span>Priority defects</span>
              <span style={{color: "#C8D2E4"}}>23</span>
            </div>
            <div className="defect-list" style={{marginTop: 8}}>
              <div className="defect-row">
                <span className="sev high"></span>
                <span className="label">
                  <span className="ttl">Longitudinal crack</span>
                  <span className="meta">CR-04 · ch 412.6</span>
                </span>
                <span className="val">12.8 mm</span>
              </div>
              <div className="defect-row">
                <span className="sev high"></span>
                <span className="label">
                  <span className="ttl">Mortar loss</span>
                  <span className="meta">ML-03 · ch 418.2</span>
                </span>
                <span className="val">32 mm</span>
              </div>
              <div className="defect-row">
                <span className="sev med"></span>
                <span className="label">
                  <span className="ttl">Concrete spalling</span>
                  <span className="meta">SP-12 · ch 414.0</span>
                </span>
                <span className="val">4.2 mm</span>
              </div>
              <div className="defect-row">
                <span className="sev med"></span>
                <span className="label">
                  <span className="ttl">Transverse crack</span>
                  <span className="meta">CR-07 · ch 419.5</span>
                </span>
                <span className="val">5.2 mm</span>
              </div>
            </div>
          </div>
        </aside>
      </div>

      {/* Bottom stat strip */}
      <div className="dash-bottom">
        <div className="stat">
          <div className="lbl">Defects detected</div>
          <div className="val">147 <span className="accent">+ 12</span></div>
        </div>
        <div className="stat">
          <div className="lbl">Reviewed</div>
          <div className="val">92<span style={{fontSize: 11, color: "#6A7B97"}}> / 147</span></div>
        </div>
        <div className="stat">
          <div className="lbl">Maintenance priority</div>
          <div className="val">8 <span style={{color: "#F59E0B"}}>urgent</span></div>
        </div>
        <button className="export">↓ Export evidence pack</button>
      </div>
    </div>
  );
}

Object.assign(window, { Dashboard, PointCloud, Sparkline });
