// primitives.jsx — Reusable visual elements for X3EDGE data flow animation

// ── Color tokens (from device) ─────────────────────────────────────
const X3 = {
  bg: '#0a0a0a',
  bg2: '#141414',
  panel: '#1a1a1a',
  border: 'rgba(255,255,255,0.08)',
  borderHi: 'rgba(255,255,255,0.18)',
  text: '#f5f5f0',
  textDim: 'rgba(245,245,240,0.55)',
  textMute: 'rgba(245,245,240,0.35)',
  orange: '#ff4d1a',     // top of device frame
  amber: '#ff9d2a',      // bottom of device frame
  teal: '#2dd4d4',       // xeeed.io dot color
  status: '#22c55e',     // green status LED
  blue: '#3b82f6',       // wifi
  violet: '#a855f7',     // 4g
};
const monoFont = "'JetBrains Mono', ui-monospace, SFMono-Regular, monospace";
const sansFont = "'Inter', -apple-system, system-ui, sans-serif";

// ── Glow ring around device frame ──────────────────────────────────
function FrameGlow({ x, y, w, h, intensity = 1 }) {
  return (
    <div style={{
      position: 'absolute', left: x, top: y, width: w, height: h,
      borderRadius: 28,
      background: `linear-gradient(180deg, ${X3.orange}, ${X3.amber})`,
      filter: 'blur(40px)',
      opacity: 0.35 * intensity,
      pointerEvents: 'none',
    }}/>
  );
}

// ── Solar panel (CSS grid of cells) ────────────────────────────────
function SolarPanel({ x, y, w = 220, h = 130, tilt = -8, sunlight = 1 }) {
  const cols = 6, rows = 4;
  const cells = [];
  for (let r = 0; r < rows; r++) {
    for (let c = 0; c < cols; c++) {
      cells.push(
        <div key={`${r}-${c}`} style={{
          background: `linear-gradient(135deg, oklch(${28 + sunlight * 8}% 0.04 240) 0%, oklch(${42 + sunlight * 12}% 0.06 235) 50%, oklch(${22 + sunlight * 6}% 0.03 240) 100%)`,
          borderRadius: 2,
          boxShadow: 'inset 0 0 0 1px rgba(80,140,200,0.18)',
        }}/>
      );
    }
  }
  return (
    <div style={{
      position: 'absolute', left: x, top: y, width: w, height: h,
      transform: `perspective(800px) rotateX(${tilt}deg)`,
      transformOrigin: 'center bottom',
    }}>
      <div style={{
        width: '100%', height: '100%',
        background: '#0a1628',
        padding: 6,
        display: 'grid',
        gridTemplateColumns: `repeat(${cols}, 1fr)`,
        gridTemplateRows: `repeat(${rows}, 1fr)`,
        gap: 3,
        border: '2px solid #1a2942',
        borderRadius: 3,
      }}>
        {cells}
      </div>
      {/* support */}
      <div style={{
        position: 'absolute',
        left: '50%', bottom: -30,
        width: 4, height: 30,
        background: '#3a3a3a',
        transform: 'translateX(-50%)',
      }}/>
    </div>
  );
}

// ── Inverter box ───────────────────────────────────────────────────
function Inverter({ x, y, w = 170, h = 200, label = 'INVERTER', pulse = 0 }) {
  return (
    <div style={{
      position: 'absolute', left: x, top: y, width: w, height: h,
      background: 'linear-gradient(180deg, #2a2a2a 0%, #1a1a1a 100%)',
      borderRadius: 8,
      border: '1px solid #383838',
      boxShadow: '0 8px 24px rgba(0,0,0,0.5), inset 0 1px 0 rgba(255,255,255,0.06)',
      padding: 14,
      display: 'flex', flexDirection: 'column',
      gap: 10,
      fontFamily: monoFont,
    }}>
      <div style={{
        fontSize: 10,
        letterSpacing: '0.15em',
        color: X3.textDim,
        fontWeight: 600,
      }}>{label}</div>

      {/* Display screen */}
      <div style={{
        background: '#000',
        border: '1px solid #2a2a2a',
        borderRadius: 4,
        padding: '8px 10px',
        flex: 1,
        display: 'flex', flexDirection: 'column',
        gap: 4,
        fontSize: 9,
        color: '#7fff7f',
        textShadow: '0 0 4px rgba(127,255,127,0.5)',
      }}>
        <div>P: 8.42 kW</div>
        <div>V: 480.2 V</div>
        <div>I: 17.5 A</div>
        <div>η: 98.4%</div>
      </div>

      {/* LEDs */}
      <div style={{ display: 'flex', gap: 8 }}>
        {[X3.status, '#fbbf24', '#3b82f6'].map((c, i) => (
          <div key={i} style={{
            width: 8, height: 8, borderRadius: 4,
            background: c,
            boxShadow: `0 0 ${6 + pulse * 6}px ${c}`,
            opacity: 0.6 + pulse * 0.4,
          }}/>
        ))}
      </div>

      {/* Modbus port */}
      <div style={{
        position: 'absolute',
        right: -8, top: '50%',
        width: 10, height: 24,
        background: '#1a1a1a',
        border: '1px solid #2a2a2a',
        borderRadius: '0 3px 3px 0',
        transform: 'translateY(-50%)',
      }}/>
    </div>
  );
}

// ── Data packet (small floating chip) ──────────────────────────────
function DataPacket({ x, y, label, value, color = X3.teal, scale = 1, opacity = 1 }) {
  return (
    <div style={{
      position: 'absolute',
      left: x, top: y,
      transform: `translate(-50%, -50%) scale(${scale})`,
      opacity,
      background: 'rgba(20,20,20,0.95)',
      border: `1px solid ${color}`,
      borderRadius: 6,
      padding: '5px 9px',
      fontFamily: monoFont,
      fontSize: 11,
      color: X3.text,
      whiteSpace: 'nowrap',
      boxShadow: `0 0 18px ${color}55, 0 4px 12px rgba(0,0,0,0.4)`,
      display: 'flex',
      gap: 6,
      alignItems: 'center',
      pointerEvents: 'none',
    }}>
      <span style={{ color: color, fontWeight: 600 }}>{label}</span>
      <span style={{ color: X3.textDim }}>{value}</span>
    </div>
  );
}

// ── Connection wire (SVG path) ─────────────────────────────────────
function Wire({ x1, y1, x2, y2, color = X3.borderHi, dashed = false, dashOffset = 0, glow = false }) {
  const dx = x2 - x1;
  const dy = y2 - y1;
  const cx1 = x1 + dx * 0.5;
  const cy1 = y1;
  const cx2 = x1 + dx * 0.5;
  const cy2 = y2;
  const path = `M ${x1} ${y1} C ${cx1} ${cy1}, ${cx2} ${cy2}, ${x2} ${y2}`;
  return (
    <svg style={{
      position: 'absolute', inset: 0,
      width: '100%', height: '100%',
      pointerEvents: 'none',
      overflow: 'visible',
    }}>
      {glow && (
        <path d={path} stroke={color} strokeWidth="6" fill="none" opacity="0.25" filter="blur(4px)"/>
      )}
      <path
        d={path}
        stroke={color}
        strokeWidth="1.5"
        fill="none"
        strokeDasharray={dashed ? '4 6' : 'none'}
        strokeDashoffset={dashOffset}
        strokeLinecap="round"
      />
    </svg>
  );
}

// ── Tiny label (annotation) ────────────────────────────────────────
function Annotation({ x, y, text, color = X3.textDim, size = 11, opacity = 1, align = 'left' }) {
  return (
    <div style={{
      position: 'absolute', left: x, top: y,
      transform: align === 'center' ? 'translateX(-50%)' : align === 'right' ? 'translateX(-100%)' : 'none',
      fontFamily: monoFont,
      fontSize: size,
      color,
      opacity,
      letterSpacing: '0.08em',
      textTransform: 'uppercase',
      whiteSpace: 'nowrap',
      pointerEvents: 'none',
    }}>{text}</div>
  );
}

// ── Heading text ───────────────────────────────────────────────────
function Heading({ x, y, text, size = 32, color = X3.text, opacity = 1, weight = 700, align = 'left', tracking = '-0.02em' }) {
  return (
    <div style={{
      position: 'absolute', left: x, top: y,
      transform: align === 'center' ? 'translateX(-50%)' : align === 'right' ? 'translateX(-100%)' : 'none',
      fontFamily: sansFont,
      fontSize: size,
      fontWeight: weight,
      color,
      opacity,
      letterSpacing: tracking,
      whiteSpace: 'pre',
      lineHeight: 1.1,
      pointerEvents: 'none',
    }}>{text}</div>
  );
}

// ── Pill badge ─────────────────────────────────────────────────────
function Pill({ x, y, text, color = X3.teal, opacity = 1, dot = true }) {
  return (
    <div style={{
      position: 'absolute', left: x, top: y, opacity,
      display: 'inline-flex', alignItems: 'center', gap: 7,
      padding: '5px 11px',
      background: 'rgba(20,20,20,0.85)',
      border: `1px solid ${color}55`,
      borderRadius: 999,
      fontFamily: monoFont,
      fontSize: 10,
      letterSpacing: '0.12em',
      textTransform: 'uppercase',
      color: color,
      fontWeight: 600,
    }}>
      {dot && <div style={{
        width: 6, height: 6, borderRadius: 3,
        background: color, boxShadow: `0 0 6px ${color}`,
      }}/>}
      {text}
    </div>
  );
}

// ── Signal wave (concentric arcs) ──────────────────────────────────
function SignalWave({ x, y, t, color = X3.blue, count = 3, maxR = 80, period = 1.5 }) {
  return (
    <svg style={{
      position: 'absolute', left: x - maxR, top: y - maxR,
      width: maxR * 2, height: maxR * 2,
      pointerEvents: 'none', overflow: 'visible',
    }}>
      {Array.from({ length: count }).map((_, i) => {
        const phase = ((t / period) + i / count) % 1;
        const r = 8 + phase * (maxR - 8);
        const op = (1 - phase) * 0.7;
        return (
          <circle
            key={i}
            cx={maxR} cy={maxR}
            r={r}
            fill="none"
            stroke={color}
            strokeWidth={1.5}
            opacity={op}
          />
        );
      })}
    </svg>
  );
}

// ── Terminal-style code block ──────────────────────────────────────
function CodeBlock({ x, y, w, h, lines, opacity = 1, scrollT = 0 }) {
  return (
    <div style={{
      position: 'absolute', left: x, top: y, width: w, height: h, opacity,
      background: 'rgba(8,8,8,0.95)',
      border: `1px solid ${X3.border}`,
      borderRadius: 8,
      fontFamily: monoFont,
      fontSize: 11,
      color: X3.text,
      overflow: 'hidden',
      boxShadow: '0 8px 32px rgba(0,0,0,0.5)',
    }}>
      {/* Header */}
      <div style={{
        padding: '6px 12px',
        borderBottom: `1px solid ${X3.border}`,
        display: 'flex', alignItems: 'center', gap: 6,
        fontSize: 9,
        letterSpacing: '0.1em',
        color: X3.textMute,
        textTransform: 'uppercase',
      }}>
        <div style={{ width: 8, height: 8, borderRadius: 4, background: X3.status, boxShadow: `0 0 4px ${X3.status}` }}/>
        MQTT.PAYLOAD
      </div>
      <div style={{ padding: '8px 12px', lineHeight: 1.55 }}>
        {lines.map((line, i) => {
          const reveal = scrollT > i * 0.08;
          return (
            <div key={i} style={{
              opacity: reveal ? 1 : 0,
              transform: reveal ? 'translateY(0)' : 'translateY(4px)',
              transition: 'opacity 200ms, transform 200ms',
              color: line.color || X3.text,
            }}>{line.text}</div>
          );
        })}
      </div>
    </div>
  );
}

// ── Cloud / server stack ───────────────────────────────────────────
function CloudPlatform({ x, y, w = 360, h = 260, t = 0, dataPulse = 0 }) {
  return (
    <div style={{
      position: 'absolute', left: x, top: y, width: w, height: h,
      background: 'linear-gradient(180deg, #181818 0%, #101010 100%)',
      border: `1px solid ${X3.border}`,
      borderRadius: 14,
      boxShadow: '0 16px 60px rgba(0,0,0,0.6)',
      padding: 16,
      display: 'flex', flexDirection: 'column',
      gap: 10,
      fontFamily: sansFont,
      overflow: 'hidden',
    }}>
      {/* Header */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <div style={{
            width: 18, height: 18, borderRadius: 4,
            background: `linear-gradient(135deg, ${X3.teal}, #1ba8a8)`,
            boxShadow: `0 0 12px ${X3.teal}66`,
          }}/>
          <div style={{ fontSize: 13, fontWeight: 700, color: X3.text, letterSpacing: '-0.01em' }}>
            SynergyOT
          </div>
        </div>
        <div style={{
          fontFamily: monoFont, fontSize: 9,
          color: X3.status, letterSpacing: '0.1em',
          display: 'flex', alignItems: 'center', gap: 5,
        }}>
          <div style={{
            width: 6, height: 6, borderRadius: 3, background: X3.status,
            boxShadow: `0 0 6px ${X3.status}`,
            opacity: 0.6 + dataPulse * 0.4,
          }}/>
          LIVE
        </div>
      </div>

      {/* KPI tiles */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
        <Tile label="Total Power" value="8.42" unit="kW" t={t}/>
        <Tile label="Today" value="42.7" unit="kWh" t={t + 0.4}/>
      </div>

      {/* Mini chart */}
      <MiniChart t={t}/>

      {/* Status row */}
      <div style={{
        display: 'flex', gap: 6, fontFamily: monoFont, fontSize: 9,
        color: X3.textMute, letterSpacing: '0.06em',
      }}>
        <span style={{ color: X3.teal }}>● MQTT/CONNECTED</span>
        <span>·</span>
        <span>QoS 1</span>
        <span>·</span>
        <span>BROKER OK</span>
      </div>
    </div>
  );
}

function Tile({ label, value, unit, t }) {
  // Tiny flicker on the last digit
  const flick = Math.floor(t * 8) % 10;
  const display = `${value}`;
  return (
    <div style={{
      background: 'rgba(255,255,255,0.02)',
      border: `1px solid ${X3.border}`,
      borderRadius: 6,
      padding: '8px 10px',
    }}>
      <div style={{
        fontFamily: monoFont, fontSize: 8.5,
        color: X3.textMute, letterSpacing: '0.12em',
        textTransform: 'uppercase', marginBottom: 4,
      }}>{label}</div>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 4 }}>
        <div style={{
          fontFamily: monoFont, fontSize: 20, fontWeight: 600,
          color: X3.text, fontVariantNumeric: 'tabular-nums',
        }}>{display}</div>
        <div style={{ fontSize: 10, color: X3.textDim }}>{unit}</div>
      </div>
    </div>
  );
}

function MiniChart({ t }) {
  // Build a smooth bumping line + bars
  const W = 320, H = 70;
  const N = 32;
  const pts = [];
  for (let i = 0; i < N; i++) {
    const phase = i / N;
    const drift = Math.min(1, t / 2);
    const y =
      0.55 +
      0.18 * Math.sin(phase * 6 + t * 0.6) +
      0.08 * Math.sin(phase * 13 + t * 1.2);
    const x = phase * W;
    const yy = (1 - y) * H * drift + (1 - drift) * H * 0.5;
    pts.push([x, yy]);
  }
  const path = pts.map((p, i) => (i === 0 ? `M ${p[0]} ${p[1]}` : `L ${p[0]} ${p[1]}`)).join(' ');
  const areaPath = path + ` L ${W} ${H} L 0 ${H} Z`;

  return (
    <div style={{ position: 'relative', flex: 1, minHeight: 70 }}>
      <svg width={W} height={H} style={{ display: 'block', width: '100%', height: '100%' }} viewBox={`0 0 ${W} ${H}`}>
        <defs>
          <linearGradient id="chartFill" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor={X3.teal} stopOpacity="0.4"/>
            <stop offset="100%" stopColor={X3.teal} stopOpacity="0"/>
          </linearGradient>
        </defs>
        <path d={areaPath} fill="url(#chartFill)"/>
        <path d={path} stroke={X3.teal} strokeWidth="1.5" fill="none" strokeLinecap="round"/>
        {/* moving dot at end */}
        <circle cx={pts[pts.length - 1][0]} cy={pts[pts.length - 1][1]} r="3" fill={X3.teal}/>
        <circle cx={pts[pts.length - 1][0]} cy={pts[pts.length - 1][1]} r="6" fill="none" stroke={X3.teal} strokeOpacity="0.4"/>
      </svg>
    </div>
  );
}

// Export all globally
Object.assign(window, {
  X3, monoFont, sansFont,
  FrameGlow, SolarPanel, Inverter,
  DataPacket, Wire, Annotation, Heading, Pill,
  SignalWave, CodeBlock, CloudPlatform,
});
