/* Simulação interativa do app Nivelio.
   Reproduz a tela de detalhe do reservatório com nível em tempo real,
   bomba ligando/desligando conforme configuração do usuário. */

const { useState, useEffect, useRef } = React;

// ─── Reservoir widget ──────────────────────────────────────────
function Reservoir({ level, status, color, h = 220, w = 180 }) {
  const fillH = Math.max(0, Math.min(100, level));
  return (
    <div style={{
      position: 'relative', width: w, height: h,
      borderRadius: 18, border: '1.5px solid rgba(148,163,184,0.18)',
      background: 'rgba(15,23,42,0.6)', overflow: 'hidden',
      boxShadow: 'inset 0 2px 0 rgba(255,255,255,0.04)',
    }}>
      {/* water fill */}
      <div style={{
        position: 'absolute', left: 0, right: 0, bottom: 0,
        height: `${fillH}%`,
        transition: 'height 1.2s cubic-bezier(.22,.9,.32,1), background 0.6s',
      }}>
        <div style={{
          position: 'absolute', inset: 0,
          background: `linear-gradient(180deg, ${color}aa 0%, ${color}dd 100%)`,
        }} />
        {/* waves */}
        <svg viewBox="0 0 144 12" preserveAspectRatio="none"
          style={{
            position: 'absolute', top: -1, left: 0, width: '200%', height: 14,
            animation: 'wave-scroll 2.4s linear infinite',
          }}>
          <path d="M0,6 Q9,0 18,6 Q27,12 36,6 Q45,0 54,6 Q63,12 72,6 Q81,0 90,6 Q99,12 108,6 Q117,0 126,6 Q135,12 144,6 L144,12 L0,12 Z"
                fill={`${color}`} opacity="0.85"/>
        </svg>
        <svg viewBox="0 0 144 12" preserveAspectRatio="none"
          style={{
            position: 'absolute', top: 1, left: 0, width: '200%', height: 14,
            animation: 'wave-scroll-rev 3.4s linear infinite',
            opacity: 0.55,
          }}>
          <path d="M0,6 Q9,0 18,6 Q27,12 36,6 Q45,0 54,6 Q63,12 72,6 Q81,0 90,6 Q99,12 108,6 Q117,0 126,6 Q135,12 144,6 L144,12 L0,12 Z"
                fill={color}/>
        </svg>
      </div>
      {/* label */}
      <div style={{
        position: 'absolute', inset: 0, display: 'flex',
        flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
        textShadow: '0 2px 8px rgba(0,0,0,0.7)', pointerEvents: 'none',
      }}>
        <span style={{ fontSize: 36, fontWeight: 800, color: '#fff', lineHeight: 1, letterSpacing: '-0.02em' }}>
          {level.toFixed(1)}%
        </span>
        <span style={{ fontSize: 11, fontWeight: 600, color: 'rgba(255,255,255,0.85)', letterSpacing: '0.12em', marginTop: 6 }}>
          {status}
        </span>
      </div>
      {/* tick marks */}
      <div style={{ position: 'absolute', right: 6, top: 8, bottom: 8, display: 'flex', flexDirection: 'column', justifyContent: 'space-between', pointerEvents: 'none' }}>
        {[100, 75, 50, 25, 0].map(t => (
          <div key={t} style={{ width: 6, height: 1, background: 'rgba(255,255,255,0.18)' }}/>
        ))}
      </div>
    </div>
  );
}

// ─── Stat tile ─────────────────────────────────────────────────
function StatTile({ icon, label, value, valueColor }) {
  return (
    <div style={{
      background: 'rgba(30,41,59,0.6)', border: '1px solid rgba(148,163,184,0.08)',
      borderRadius: 14, padding: '12px 14px', display: 'flex', flexDirection: 'column', gap: 4,
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 6, color: '#94A3B8', fontSize: 11 }}>
        <span style={{ width: 14, height: 14, display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}>{icon}</span>
        {label}
      </div>
      <div style={{ fontSize: 14, fontWeight: 700, color: valueColor || '#F8FAFC', letterSpacing: '0.02em' }}>{value}</div>
    </div>
  );
}

// ─── Pump button ───────────────────────────────────────────────
function PumpBtn({ label, icon, active, color, onClick }) {
  return (
    <button onClick={onClick} style={{
      flex: 1, padding: '14px 8px', borderRadius: 14, border: '1.5px solid',
      borderColor: active ? color : 'rgba(148,163,184,0.15)',
      background: active ? `${color}22` : 'rgba(30,41,59,0.6)',
      color: active ? color : '#94A3B8',
      display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6,
      cursor: 'pointer', transition: 'all 0.2s', fontWeight: 600, fontSize: 12,
    }}>
      <div style={{ width: 32, height: 32, borderRadius: '50%',
        background: active ? `${color}33` : 'rgba(148,163,184,0.12)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>{icon}</div>
      {label}
    </button>
  );
}

// ─── Main App Simulator ────────────────────────────────────────
function NivelioAppSim({ compact = false }) {
  // Configurable thresholds
  const [onLevel, setOnLevel] = useState(30);   // liga abaixo
  const [offLevel, setOffLevel] = useState(95); // desliga acima
  const [mode, setMode] = useState('auto');     // auto / on / off

  // Live state
  const [level, setLevel] = useState(43.8);
  const [pumpOn, setPumpOn] = useState(false);
  const [sessionTime, setSessionTime] = useState(0);
  const [history, setHistory] = useState([]);
  const [paused, setPaused] = useState(false);

  // Tick simulation — every ~700ms
  useEffect(() => {
    if (paused) return;
    const id = setInterval(() => {
      setLevel(prev => {
        // Determine pump state
        let nextPump = pumpOn;
        if (mode === 'on') nextPump = true;
        else if (mode === 'off') nextPump = false;
        else {
          if (prev <= onLevel) nextPump = true;
          else if (prev >= offLevel) nextPump = false;
        }

        // Consumption (always small drain) + pump fill
        const drain = 0.4 + Math.random() * 0.3;
        const fill = nextPump ? 1.6 + Math.random() * 0.4 : 0;
        let next = prev - drain + fill;
        next = Math.max(0, Math.min(100, next));

        if (nextPump !== pumpOn) {
          setPumpOn(nextPump);
          if (nextPump) setSessionTime(0);
        }
        if (nextPump) setSessionTime(s => s + 1);

        setHistory(h => [...h.slice(-39), next]);
        return next;
      });
    }, 700);
    return () => clearInterval(id);
  }, [pumpOn, mode, onLevel, offLevel, paused]);

  const status = level >= 70 ? 'CHEIO' : level >= 30 ? 'MÉDIO' : level < 15 ? 'CRÍTICO' : 'BAIXO';
  const color = level >= 70 ? '#22C55E' : level >= 30 ? '#F59E0B' : '#EF4444';
  const fmtTime = s => {
    if (s < 60) return `${s}s`;
    const m = Math.floor(s / 60);
    const sec = s % 60;
    return `${m}m ${sec}s`;
  };

  return (
    <div className="ns-app" style={{
      width: '100%',
      maxWidth: compact ? 340 : 380,
      background: '#0A1220',
      borderRadius: 28,
      border: '1px solid rgba(148,163,184,0.12)',
      overflow: 'hidden',
      boxShadow: '0 40px 100px rgba(0,0,0,0.6), 0 0 0 1px rgba(56,189,248,0.08)',
      fontFamily: 'Inter, sans-serif',
      color: '#F8FAFC',
      position: 'relative',
    }}>
      {/* Top bar (no status bar — clean) */}
      <div style={{
        padding: '20px 18px 14px',
        borderBottom: '1px solid rgba(148,163,184,0.06)',
        display: 'flex', alignItems: 'center', gap: 12,
      }}>
        <div style={{
          width: 36, height: 36, borderRadius: 10,
          background: 'rgba(56,189,248,0.12)', border: '1px solid rgba(56,189,248,0.2)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#38BDF8" strokeWidth="2"><path d="m15 18-6-6 6-6"/></svg>
        </div>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 17, fontWeight: 700, letterSpacing: '-0.01em' }}>Caixa Dagua</div>
          <div style={{ fontSize: 11, color: '#94A3B8', display: 'flex', alignItems: 'center', gap: 5, marginTop: 2 }}>
            <span style={{
              width: 6, height: 6, borderRadius: '50%', background: '#22C55E',
              boxShadow: '0 0 6px #22C55E',
            }}/>
            Online · atualiza em tempo real
          </div>
        </div>
      </div>

      {/* Reservoir hero */}
      <div style={{ padding: '24px 18px 18px', display: 'flex', justifyContent: 'center' }}>
        <Reservoir level={level} status={status} color={color} />
      </div>

      {/* Stats grid */}
      <div style={{ padding: '0 18px', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
        <StatTile
          label="Status"
          icon={<svg viewBox="0 0 24 24" width="14" height="14" fill={color}><path d="M12 2.69l5.66 5.66a8 8 0 1 1-11.31 0z"/></svg>}
          value={status}
          valueColor={color}
        />
        <StatTile
          label="Bomba"
          icon={<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke={pumpOn ? '#38BDF8' : '#94A3B8'} strokeWidth="2"><path d="M9 9V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v5"/><rect x="6" y="9" width="12" height="12" rx="2"/></svg>}
          value={pumpOn ? 'LIGADA' : 'DESLIGADA'}
          valueColor={pumpOn ? '#38BDF8' : '#94A3B8'}
        />
        <StatTile
          label="Conexão"
          icon={<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="#22C55E" strokeWidth="2"><path d="M5 12.55a11 11 0 0 1 14.08 0"/><path d="M1.42 9a16 16 0 0 1 21.16 0"/><path d="M8.53 16.11a6 6 0 0 1 6.95 0"/><line x1="12" y1="20" x2="12" y2="20"/></svg>}
          value="Online"
          valueColor="#22C55E"
        />
        <StatTile
          label="Alerta mín."
          icon={<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="#F59E0B" strokeWidth="2"><path d="M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/></svg>}
          value={`${onLevel}%`}
          valueColor="#F59E0B"
        />
      </div>

      {/* Pump control */}
      <div style={{ padding: '20px 18px 8px' }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 10 }}>
          <span style={{ fontSize: 14, fontWeight: 700 }}>Controle da Bomba</span>
          <span style={{ fontSize: 11, color: pumpOn ? '#38BDF8' : '#94A3B8', display: 'flex', alignItems: 'center', gap: 4 }}>
            <span style={{ width: 6, height: 6, borderRadius: '50%', background: pumpOn ? '#38BDF8' : '#94A3B8' }}/>
            {pumpOn ? `Ligada · ${fmtTime(sessionTime)}` : 'Desligada'}
          </span>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <PumpBtn label="Ligar" color="#22C55E" active={mode === 'on'}
            onClick={() => setMode('on')}
            icon={<svg width="16" height="16" viewBox="0 0 24 24" fill={mode==='on'?'#22C55E':'#94A3B8'}><polygon points="5 3 19 12 5 21 5 3"/></svg>}
          />
          <PumpBtn label="Desligar" color="#EF4444" active={mode === 'off'}
            onClick={() => setMode('off')}
            icon={<svg width="14" height="14" viewBox="0 0 24 24" fill={mode==='off'?'#EF4444':'#94A3B8'}><rect x="6" y="6" width="12" height="12" rx="1"/></svg>}
          />
          <PumpBtn label="Auto" color="#38BDF8" active={mode === 'auto'}
            onClick={() => setMode('auto')}
            icon={<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke={mode==='auto'?'#38BDF8':'#94A3B8'} strokeWidth="2"><path d="M21 12a9 9 0 1 1-3-6.7"/><polyline points="21 3 21 9 15 9"/></svg>}
          />
        </div>
      </div>

      {/* Mini sparkline */}
      <div style={{ padding: '8px 18px 18px' }}>
        <div style={{
          background: 'rgba(30,41,59,0.5)', border: '1px solid rgba(148,163,184,0.08)',
          borderRadius: 14, padding: '14px 14px 10px', position: 'relative', overflow: 'hidden',
        }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 10, color: '#94A3B8', marginBottom: 4 }}>
            <span>Últimos 30s</span>
            <span style={{ color }}>{level.toFixed(1)}%</span>
          </div>
          <svg viewBox="0 0 240 60" preserveAspectRatio="none" style={{ width: '100%', height: 44, display: 'block' }}>
            <defs>
              <linearGradient id="lineGrad" x1="0" y1="0" x2="0" y2="1">
                <stop offset="0%" stopColor="#38BDF8" stopOpacity="0.5"/>
                <stop offset="100%" stopColor="#38BDF8" stopOpacity="0"/>
              </linearGradient>
            </defs>
            {history.length > 1 && (() => {
              const pts = history.map((v, i) => `${(i / (history.length - 1)) * 240},${60 - (v / 100) * 60}`).join(' ');
              const area = `0,60 ${pts} 240,60`;
              return (<>
                <polyline points={area} fill="url(#lineGrad)" />
                <polyline points={pts} fill="none" stroke="#38BDF8" strokeWidth="1.6"/>
              </>);
            })()}
            {/* threshold lines */}
            <line x1="0" x2="240" y1={60 - (onLevel/100)*60} y2={60 - (onLevel/100)*60} stroke="#EF4444" strokeWidth="0.8" strokeDasharray="2,3" opacity="0.6"/>
            <line x1="0" x2="240" y1={60 - (offLevel/100)*60} y2={60 - (offLevel/100)*60} stroke="#22C55E" strokeWidth="0.8" strokeDasharray="2,3" opacity="0.6"/>
          </svg>
          <div style={{ display: 'flex', gap: 12, fontSize: 9, color: '#94A3B8', marginTop: 4 }}>
            <span style={{ display:'flex', alignItems:'center', gap:4 }}><span style={{ width:8, height:1, background:'#EF4444' }}/>liga &lt; {onLevel}%</span>
            <span style={{ display:'flex', alignItems:'center', gap:4 }}><span style={{ width:8, height:1, background:'#22C55E' }}/>desliga &gt; {offLevel}%</span>
          </div>
        </div>
      </div>

      {/* Sliders for thresholds — interactive demo */}
      <div style={{
        padding: '14px 18px 22px',
        background: 'linear-gradient(180deg, transparent 0%, rgba(56,189,248,0.04) 100%)',
        borderTop: '1px dashed rgba(148,163,184,0.12)',
      }}>
        <div style={{ fontSize: 11, fontWeight: 700, color: '#38BDF8', letterSpacing: '0.08em', marginBottom: 10, textTransform: 'uppercase' }}>
          ⚙ Configuração — ajuste e veja
        </div>

        <div style={{ marginBottom: 12 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11, marginBottom: 4 }}>
            <span style={{ color: '#CBD5E1' }}>Liga bomba abaixo de</span>
            <span style={{ color: '#EF4444', fontWeight: 700 }}>{onLevel}%</span>
          </div>
          <input type="range" min="5" max="60" value={onLevel}
            onChange={e => setOnLevel(Math.min(parseInt(e.target.value), offLevel - 5))}
            style={{ width: '100%', accentColor: '#EF4444' }}/>
        </div>

        <div>
          <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11, marginBottom: 4 }}>
            <span style={{ color: '#CBD5E1' }}>Desliga bomba acima de</span>
            <span style={{ color: '#22C55E', fontWeight: 700 }}>{offLevel}%</span>
          </div>
          <input type="range" min="60" max="100" value={offLevel}
            onChange={e => setOffLevel(Math.max(parseInt(e.target.value), onLevel + 5))}
            style={{ width: '100%', accentColor: '#22C55E' }}/>
        </div>
      </div>
    </div>
  );
}

window.NivelioAppSim = NivelioAppSim;
window.Reservoir = Reservoir;
