// Module: Monitoreo en tiempo real

function Channel({ label, unit, value, min, max, warn, color = '#EB6B1E', history }) {
  const pct = Math.min(100, Math.max(0, ((value - min) / (max - min)) * 100));
  const isWarn = warn && value > warn;
  return (
    <Card className="relative overflow-hidden">
      <div className="px-5 py-4">
        <div className="flex items-center justify-between">
          <div className="text-[11px] font-semibold text-muted uppercase tracking-wider">
            {label}
          </div>
          <div className="flex items-center gap-1.5 text-[10px] text-muted">
            <span className="relative flex h-1.5 w-1.5">
              <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-emerald opacity-75" />
              <span className="relative inline-flex rounded-full h-1.5 w-1.5 bg-emerald" />
            </span>
            LIVE
          </div>
        </div>
        <div className="flex items-end gap-2 mt-3">
          <div
            className={cn(
              'text-[34px] font-bold tracking-tight leading-none tnum',
              isWarn ? 'text-red' : 'text-ink',
            )}
          >
            {typeof value === 'number' ? value.toFixed(1) : value}
          </div>
          <div className="text-[14px] text-muted font-medium mb-1">{unit}</div>
        </div>
        <div className="mt-3 h-1.5 rounded-full bg-slate-100 overflow-hidden">
          <div
            className={cn('h-full rounded-full transition-all')}
            style={{ width: `${pct}%`, background: isWarn ? '#B91C1C' : color }}
          />
        </div>
        <div className="flex justify-between text-[10px] text-muted tnum mt-1">
          <span>{min}</span>
          {warn && <span className="text-amber-ink">⚠ {warn}</span>}
          <span>{max}</span>
        </div>
      </div>
      <div className="px-2 pb-2">
        <Sparkline data={history} color={isWarn ? '#B91C1C' : color} width={260} height={38} />
      </div>
    </Card>
  );
}

function MonitoreoModule() {
  // simulate 7 channels with a simple stochastic model
  const [running, setRunning] = useState(true);
  const [tick, setTick] = useState(0);
  const [channels, setChannels] = useState(() => ({
    pressure: {
      label: 'Presión de bomba',
      unit: 'PSI',
      value: 482,
      min: 0,
      max: 700,
      warn: 550,
      history: Array.from(
        { length: 40 },
        (_, i) => 480 + Math.sin(i / 4) * 30 + (Math.random() - 0.5) * 20,
      ),
    },
    flow: {
      label: 'Caudal',
      unit: 'lts/min',
      value: 96,
      min: 0,
      max: 140,
      history: Array.from(
        { length: 40 },
        (_, i) => 95 + Math.sin(i / 5) * 6 + (Math.random() - 0.5) * 5,
      ),
    },
    rpm: {
      label: 'RPM cabezal',
      unit: 'rpm',
      value: 420,
      min: 0,
      max: 800,
      history: Array.from({ length: 40 }, () => 420 + (Math.random() - 0.5) * 30),
    },
    torque: {
      label: 'Torque',
      unit: 'Nm',
      value: 1240,
      min: 0,
      max: 2000,
      warn: 1700,
      history: Array.from(
        { length: 40 },
        (_, i) => 1240 + Math.sin(i / 3) * 80 + (Math.random() - 0.5) * 60,
      ),
    },
    wob: {
      label: 'Peso sobre mecha',
      unit: 'kN',
      value: 38,
      min: 0,
      max: 80,
      history: Array.from({ length: 40 }, () => 38 + (Math.random() - 0.5) * 6),
    },
    hook: {
      label: 'Peso de tiro',
      unit: 'kN',
      value: 122,
      min: 0,
      max: 200,
      history: Array.from({ length: 40 }, () => 122 + (Math.random() - 0.5) * 8),
    },
    strokes: {
      label: 'Emboladas',
      unit: 'spm',
      value: 68,
      min: 0,
      max: 120,
      history: Array.from({ length: 40 }, () => 68 + (Math.random() - 0.5) * 4),
    },
  }));

  useEffect(() => {
    if (!running) return;
    const iv = setInterval(() => {
      setTick((t) => t + 1);
      setChannels((prev) => {
        const next = {};
        for (const k in prev) {
          const c = prev[k];
          const drift = (Math.random() - 0.5) * (c.max - c.min) * 0.015;
          const nv = Math.max(c.min, Math.min(c.max, c.value + drift));
          next[k] = { ...c, value: nv, history: [...c.history.slice(1), nv] };
        }
        return next;
      });
    }, 900);
    return () => clearInterval(iv);
  }, [running]);

  // Derived metrics
  const hoursEffective = 194;
  const productivePct = 26;
  const rop = 4.4;

  return (
    <div className="view-in space-y-5">
      {/* top strip */}
      <div className="flex items-center gap-3 flex-wrap">
        <Badge variant="emerald">
          <span className="h-1.5 w-1.5 rounded-full bg-emerald live-dot" /> Conectado
        </Badge>
        <span className="text-[12px] text-muted">
          Última muestra hace <b className="text-ink tnum">{tick > 0 ? '<1s' : '900ms'}</b>
        </span>
        <span className="text-[12px] text-muted">·</span>
        <span className="text-[12px] text-muted mono">rig-1.netto · 7 canales · 1 Hz</span>
        <div className="ml-auto flex items-center gap-2">
          <Tabs
            value="10m"
            onChange={() => {}}
            options={[
              { value: '5m', label: '5m' },
              { value: '10m', label: '10m' },
              { value: '1h', label: '1h' },
              { value: '24h', label: '24h' },
            ]}
          />
          <Button variant="outline" size="sm" onClick={() => setRunning((r) => !r)}>
            <Icon name={running ? 'pause' : 'play'} size={12} /> {running ? 'Pausar' : 'Reanudar'}
          </Button>
          <Button variant="outline" size="sm">
            <Icon name="download" size={12} /> CSV
          </Button>
        </div>
      </div>

      {/* derived metrics */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
        <Card>
          <CardContent className="pt-5">
            <div className="text-[11px] font-semibold text-muted uppercase tracking-wider">
              Horas efectivas (mes)
            </div>
            <div className="text-[28px] font-bold tracking-tight tnum mt-2">
              194 <span className="text-[14px] text-muted font-medium">h</span>
            </div>
            <div className="text-[11px] text-muted mt-1">de 744 h monitoreadas</div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="pt-5">
            <div className="text-[11px] font-semibold text-muted uppercase tracking-wider">
              % productivo
            </div>
            <div className="text-[28px] font-bold tracking-tight tnum mt-2">
              {productivePct}
              <span className="text-[14px] text-muted font-medium">%</span>
            </div>
            <div className="h-1.5 rounded-full bg-slate-100 overflow-hidden mt-3">
              <div
                className="h-full bg-amber rounded-full"
                style={{ width: `${productivePct}%` }}
              />
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="pt-5">
            <div className="flex items-center justify-between">
              <div className="text-[11px] font-semibold text-muted uppercase tracking-wider">
                ROP
              </div>
              <Badge variant="amber">pendiente</Badge>
            </div>
            <div className="text-[28px] font-bold tracking-tight tnum mt-2">
              {rop} <span className="text-[14px] text-muted font-medium">m/h</span>
            </div>
            <div className="text-[11px] text-muted mt-1">requiere depth sensor</div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="pt-5">
            <div className="text-[11px] font-semibold text-muted uppercase tracking-wider">
              Estado del rig
            </div>
            <div className="flex items-center gap-2 mt-2">
              <span className="relative flex h-2 w-2">
                <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-emerald opacity-75" />
                <span className="relative inline-flex rounded-full h-2 w-2 bg-emerald" />
              </span>
              <span className="text-[18px] font-bold text-emerald">Perforando</span>
            </div>
            <div className="text-[11px] text-muted mt-1">Turno tarde · C. Godoy</div>
          </CardContent>
        </Card>
      </div>

      {/* channels grid */}
      <div>
        <div className="flex items-center justify-between mb-3">
          <h2 className="text-[13px] font-semibold tracking-wide uppercase text-muted">
            Canales en vivo
          </h2>
          <span className="text-[11px] text-muted">Sensor NETTO · 7/7 canales</span>
        </div>
        <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
          {Object.entries(channels).map(([k, c]) => (
            <Channel key={k} {...c} />
          ))}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { MonitoreoModule });
