// Animated water tank SVG with sine-wave fill
const TankVisual = ({ level = 50, width = 110, height = 140, online = true, motor = false, valveOpen = false, big = false }) => {
  const id = React.useId();
  const w = width, h = height;
  const pad = 6;
  const tankInner = { x: pad, y: pad, w: w - pad*2, h: h - pad*2, r: big ? 18 : 14 };
  const fillH = (tankInner.h) * (level / 100);
  const fillTop = tankInner.y + (tankInner.h - fillH);

  // Wave SVG path — two waves of double-width for seamless loop translate
  const waveAmp = big ? 4 : 3;
  const waveCount = 4;
  const waveW = tankInner.w;

  const buildWavePath = (phase = 0) => {
    const steps = 40;
    let d = `M 0 ${waveAmp} `;
    for (let i = 0; i <= steps; i++) {
      const x = (i / steps) * waveW * 2; // double width for loop
      const y = waveAmp + Math.sin((i/steps) * Math.PI * waveCount + phase) * waveAmp;
      d += `L ${x.toFixed(2)} ${y.toFixed(2)} `;
    }
    d += `L ${waveW*2} ${tankInner.h} L 0 ${tankInner.h} Z`;
    return d;
  };

  const dim = !online;

  return (
    <svg width={w} height={h} viewBox={`0 0 ${w} ${h}`} style={{ display: 'block', filter: dim ? 'grayscale(0.6) opacity(0.55)' : undefined }}>
      <defs>
        <linearGradient id={`grad-${id}`} x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="#7fe9ff" stopOpacity="0.95"/>
          <stop offset="60%" stopColor="#00d4ff" stopOpacity="0.95"/>
          <stop offset="100%" stopColor="#0066a3" stopOpacity="1"/>
        </linearGradient>
        <linearGradient id={`grad2-${id}`} x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="#7fe9ff" stopOpacity="0.55"/>
          <stop offset="100%" stopColor="#00d4ff" stopOpacity="0.55"/>
        </linearGradient>
        <clipPath id={`clip-${id}`}>
          <rect x={tankInner.x} y={tankInner.y} width={tankInner.w} height={tankInner.h} rx={tankInner.r} ry={tankInner.r}/>
        </clipPath>
        <filter id={`glow-${id}`} x="-50%" y="-50%" width="200%" height="200%">
          <feGaussianBlur stdDeviation="2.5" result="b"/>
          <feMerge><feMergeNode in="b"/><feMergeNode in="SourceGraphic"/></feMerge>
        </filter>
      </defs>

      {/* Tank outline (background) */}
      <rect x={tankInner.x} y={tankInner.y} width={tankInner.w} height={tankInner.h} rx={tankInner.r} ry={tankInner.r}
            fill="rgba(255,255,255,0.03)" stroke="rgba(255,255,255,0.18)" strokeWidth="1.2"/>

      {/* Tick marks */}
      {[25, 50, 75].map(p => {
        const y = tankInner.y + tankInner.h - (tankInner.h * p / 100);
        return (
          <g key={p}>
            <line x1={tankInner.x} y1={y} x2={tankInner.x + 4} y2={y} stroke="rgba(255,255,255,0.25)" strokeWidth="1"/>
            <line x1={tankInner.x + tankInner.w - 4} y1={y} x2={tankInner.x + tankInner.w} y2={y} stroke="rgba(255,255,255,0.25)" strokeWidth="1"/>
          </g>
        );
      })}

      {/* Water fill — clipped */}
      <g clipPath={`url(#clip-${id})`}>
        <rect x={tankInner.x} y={fillTop + waveAmp} width={tankInner.w} height={fillH} fill={`url(#grad-${id})`}/>
        {/* Back wave */}
        <g transform={`translate(${tankInner.x}, ${fillTop})`}>
          <g style={{ animation: 'wave-2 6s linear infinite' }}>
            <path d={buildWavePath(0)} fill={`url(#grad2-${id})`}/>
          </g>
        </g>
        {/* Front wave */}
        <g transform={`translate(${tankInner.x}, ${fillTop})`}>
          <g style={{ animation: 'wave-1 4s linear infinite' }}>
            <path d={buildWavePath(Math.PI/2)} fill={`url(#grad-${id})`} opacity="0.85"/>
          </g>
        </g>

        {/* Bubbles when motor running */}
        {motor && [0,1,2].map(i => (
          <circle key={i}
            cx={tankInner.x + (tankInner.w/4) + (i * tankInner.w/4)}
            cy={tankInner.y + tankInner.h - 8}
            r={1.6 + (i%2)}
            fill="rgba(255,255,255,0.6)"
            style={{
              animation: `bounce-y ${1.2 + i*0.2}s ease-in-out ${i*0.2}s infinite`
            }}
          />
        ))}
      </g>

      {/* Top inlet pipe */}
      <line x1={tankInner.x + tankInner.w * 0.78} y1={tankInner.y - pad} x2={tankInner.x + tankInner.w * 0.78} y2={tankInner.y + 2}
            stroke={valveOpen ? 'var(--cyan)' : 'rgba(255,255,255,0.25)'} strokeWidth="2.5"
            strokeDasharray={valveOpen ? '4 3' : '0'}
            style={{ animation: valveOpen ? 'flow-dash 0.8s linear infinite' : undefined }}/>

      {/* Tank outline (foreground) */}
      <rect x={tankInner.x} y={tankInner.y} width={tankInner.w} height={tankInner.h} rx={tankInner.r} ry={tankInner.r}
            fill="none" stroke="rgba(255,255,255,0.35)" strokeWidth="1.2"/>

      {/* Offline badge overlay */}
      {!online && (
        <g>
          <rect x={tankInner.x} y={tankInner.y + tankInner.h/2 - 10} width={tankInner.w} height={20} fill="rgba(10,14,39,0.7)"/>
          <text x={tankInner.x + tankInner.w/2} y={tankInner.y + tankInner.h/2 + 4} textAnchor="middle" fill="#ff5252" fontSize="10" fontWeight="600" fontFamily="Outfit, sans-serif">OFFLINE</text>
        </g>
      )}
    </svg>
  );
};

// Circular progress ring — used in detail view
const CircularRing = ({ level, size = 220, strokeWidth = 8 }) => {
  const r = size / 2 - strokeWidth;
  const c = 2 * Math.PI * r;
  const off = c - (level / 100) * c;
  const id = React.useId();
  return (
    <svg width={size} height={size} style={{position: 'absolute', inset: 0, transform: 'rotate(-90deg)'}}>
      <defs>
        <linearGradient id={`ring-${id}`} x1="0" y1="0" x2="1" y2="1">
          <stop offset="0%" stopColor="#7fe9ff"/>
          <stop offset="100%" stopColor="#00b894"/>
        </linearGradient>
      </defs>
      <circle cx={size/2} cy={size/2} r={r} fill="none" stroke="rgba(255,255,255,0.06)" strokeWidth={strokeWidth}/>
      <circle cx={size/2} cy={size/2} r={r} fill="none"
              stroke={`url(#ring-${id})`} strokeWidth={strokeWidth}
              strokeDasharray={c} strokeDashoffset={off}
              strokeLinecap="round"
              style={{transition: 'stroke-dashoffset 600ms ease'}}/>
    </svg>
  );
};

// Underground tank — buried cistern with ground cross-section above
const UndergroundTankVisual = ({ level = 50, width = 110, height = 140, online = true, motor = false, valveOpen = false, big = false }) => {
  const id = React.useId();
  const w = width, h = height;
  const groundH = Math.round(h * 0.22);   // top ground band
  const pad = 6;
  const tank = { x: pad, y: groundH + 2, w: w - pad*2, h: h - groundH - pad - 2, r: big ? 14 : 10 };
  const fillH = tank.h * (level / 100);
  const fillTop = tank.y + (tank.h - fillH);
  const waveAmp = big ? 4 : 3;
  const waveCount = 4;

  const buildWavePath = (phase = 0) => {
    const steps = 40;
    let d = `M 0 ${waveAmp} `;
    for (let i = 0; i <= steps; i++) {
      const x = (i / steps) * tank.w * 2;
      const y = waveAmp + Math.sin((i/steps) * Math.PI * waveCount + phase) * waveAmp;
      d += `L ${x.toFixed(2)} ${y.toFixed(2)} `;
    }
    d += `L ${tank.w*2} ${tank.h} L 0 ${tank.h} Z`;
    return d;
  };

  const dim = !online;
  const pipeX = tank.x + tank.w * 0.72;

  return (
    <svg width={w} height={h} viewBox={`0 0 ${w} ${h}`} style={{ display: 'block', filter: dim ? 'grayscale(0.6) opacity(0.55)' : undefined }}>
      <defs>
        <linearGradient id={`ugrad-${id}`} x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="#7fe9ff" stopOpacity="0.95"/>
          <stop offset="60%" stopColor="#00d4ff" stopOpacity="0.95"/>
          <stop offset="100%" stopColor="#0066a3" stopOpacity="1"/>
        </linearGradient>
        <linearGradient id={`ugrad2-${id}`} x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="#7fe9ff" stopOpacity="0.55"/>
          <stop offset="100%" stopColor="#00d4ff" stopOpacity="0.55"/>
        </linearGradient>
        <linearGradient id={`earth-${id}`} x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="#3d2b1f" stopOpacity="0.9"/>
          <stop offset="100%" stopColor="#5c3d2e" stopOpacity="0.85"/>
        </linearGradient>
        <clipPath id={`uclip-${id}`}>
          <rect x={tank.x} y={tank.y} width={tank.w} height={tank.h} rx={tank.r} ry={tank.r}/>
        </clipPath>
      </defs>

      {/* Ground surface band */}
      <rect x={0} y={0} width={w} height={groundH} rx={4} ry={4} fill={`url(#earth-${id})`}/>
      {/* Ground texture lines */}
      {[0.28, 0.52, 0.74].map((t, i) => (
        <line key={i}
          x1={pad} y1={Math.round(groundH * t)}
          x2={w - pad} y2={Math.round(groundH * t)}
          stroke="rgba(255,255,255,0.10)" strokeWidth="1" strokeDasharray="3 4"/>
      ))}
      {/* Ground surface grass line */}
      <line x1={0} y1={groundH} x2={w} y2={groundH} stroke="rgba(0,230,118,0.45)" strokeWidth="1.5"/>

      {/* Pipe going from surface down into tank */}
      <line x1={pipeX} y1={0} x2={pipeX} y2={tank.y + 4}
            stroke={valveOpen ? 'var(--cyan)' : 'rgba(255,255,255,0.35)'} strokeWidth="2.5"
            strokeDasharray={valveOpen ? '4 3' : '0'}
            style={{ animation: valveOpen ? 'flow-dash 0.8s linear infinite' : undefined }}/>

      {/* Tank body background */}
      <rect x={tank.x} y={tank.y} width={tank.w} height={tank.h} rx={tank.r} ry={tank.r}
            fill="rgba(255,255,255,0.03)" stroke="rgba(255,255,255,0.18)" strokeWidth="1.2"/>

      {/* Tick marks */}
      {[25, 50, 75].map(p => {
        const y = tank.y + tank.h - (tank.h * p / 100);
        return (
          <g key={p}>
            <line x1={tank.x} y1={y} x2={tank.x + 4} y2={y} stroke="rgba(255,255,255,0.25)" strokeWidth="1"/>
            <line x1={tank.x + tank.w - 4} y1={y} x2={tank.x + tank.w} y2={y} stroke="rgba(255,255,255,0.25)" strokeWidth="1"/>
          </g>
        );
      })}

      {/* Water fill */}
      <g clipPath={`url(#uclip-${id})`}>
        <rect x={tank.x} y={fillTop + waveAmp} width={tank.w} height={fillH} fill={`url(#ugrad-${id})`}/>
        <g transform={`translate(${tank.x}, ${fillTop})`}>
          <g style={{ animation: 'wave-2 6s linear infinite' }}>
            <path d={buildWavePath(0)} fill={`url(#ugrad2-${id})`}/>
          </g>
        </g>
        <g transform={`translate(${tank.x}, ${fillTop})`}>
          <g style={{ animation: 'wave-1 4s linear infinite' }}>
            <path d={buildWavePath(Math.PI/2)} fill={`url(#ugrad-${id})`} opacity="0.85"/>
          </g>
        </g>
        {motor && [0,1,2].map(i => (
          <circle key={i}
            cx={tank.x + (tank.w/4) + (i * tank.w/4)}
            cy={tank.y + tank.h - 8}
            r={1.6 + (i%2)}
            fill="rgba(255,255,255,0.6)"
            style={{ animation: `bounce-y ${1.2 + i*0.2}s ease-in-out ${i*0.2}s infinite` }}
          />
        ))}
      </g>

      {/* Tank body foreground */}
      <rect x={tank.x} y={tank.y} width={tank.w} height={tank.h} rx={tank.r} ry={tank.r}
            fill="none" stroke="rgba(255,255,255,0.35)" strokeWidth="1.2"/>

      {/* Offline badge */}
      {!online && (
        <g>
          <rect x={tank.x} y={tank.y + tank.h/2 - 10} width={tank.w} height={20} fill="rgba(10,14,39,0.7)"/>
          <text x={tank.x + tank.w/2} y={tank.y + tank.h/2 + 4} textAnchor="middle" fill="#ff5252" fontSize="10" fontWeight="600" fontFamily="Outfit, sans-serif">OFFLINE</text>
        </g>
      )}
    </svg>
  );
};

window.TankVisual = TankVisual;
window.UndergroundTankVisual = UndergroundTankVisual;
window.CircularRing = CircularRing;
