/* Tela de histórico — versão estática estilizada para a galeria de telas */

const { useState: useStateH } = React;

function HistoryScreen() {
  const [tab, setTab] = useStateH('24h');

  // Pontos de dados — 24 horas
  const pts24h = [98, 100, 100, 100, 100, 95, 70, 48, 45, 47, 49];
  const stats24h = { min: '44.3%', minColor: '#EF4444', avg: '81.6%', avgColor: '#38BDF8', max: '100%', maxColor: '#22C55E' };

  // Barras — 7 dias
  const days7 = [
    { d: '28/04', v: 3.9 },
    { d: '29/04', v: 0 },
    { d: '30/04', v: 0 },
    { d: '01/05', v: 0 },
    { d: '02/05', v: 0.4 },
    { d: '03/05', v: 1.4 },
    { d: '04/05', v: 1.0 },
  ];
  const stats7d = { total: '6.7h', max: '3.9h', avg: '1.0h' };

  return (
    <div style={{
      width: 340, minHeight: 720, background: '#0A1220', borderRadius: 28,
      border: '1px solid rgba(148,163,184,0.12)', overflow: 'hidden',
      display: 'flex', flexDirection: 'column',
      boxShadow: '0 40px 100px rgba(0,0,0,0.6), 0 0 0 1px rgba(56,189,248,0.06)',
      fontFamily: 'Inter, sans-serif', color: '#F8FAFC',
    }}>
      {/* Header */}
      <div style={{ padding: '20px 18px 14px', display: 'flex', alignItems: 'center', gap: 12 }}>
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2"><path d="m15 18-6-6 6-6"/></svg>
        <div>
          <div style={{ fontSize: 18, fontWeight: 700 }}>Histórico</div>
          <div style={{ fontSize: 12, color: '#94A3B8' }}>Caixa Dagua</div>
        </div>
      </div>

      {/* Tabs */}
      <div style={{ padding: '0 18px', display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 8, marginBottom: 16 }}>
        {[
          { k: '24h', l: '24 horas', s: 'Nível' },
          { k: '7d',  l: '7 dias',   s: 'Bomba' },
          { k: '30d', l: '30 dias',  s: 'Bomba' },
        ].map(t => (
          <button key={t.k} onClick={() => setTab(t.k)} style={{
            padding: '10px 6px', borderRadius: 10, border: 'none', cursor: 'pointer',
            background: tab === t.k ? '#38BDF8' : 'rgba(30,41,59,0.6)',
            color: tab === t.k ? '#0A1220' : '#CBD5E1',
            display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 2,
            transition: 'all 0.2s',
          }}>
            <span style={{ fontSize: 13, fontWeight: 700 }}>{t.l}</span>
            <span style={{ fontSize: 10, opacity: 0.7 }}>{t.s}</span>
          </button>
        ))}
      </div>

      {/* Stats trio */}
      <div style={{ padding: '0 18px', display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 8, marginBottom: 16 }}>
        {tab === '24h' ? (
          [
            { v: stats24h.min, l: 'Mínimo', c: stats24h.minColor },
            { v: stats24h.avg, l: 'Média',  c: stats24h.avgColor },
            { v: stats24h.max, l: 'Máximo', c: stats24h.maxColor },
          ].map((s, i) => (
            <div key={i} style={{
              background: `${s.c}15`, border: `1px solid ${s.c}30`,
              borderRadius: 12, padding: '12px 8px', textAlign: 'center',
            }}>
              <div style={{ fontSize: 18, fontWeight: 800, color: s.c, letterSpacing: '-0.02em' }}>{s.v}</div>
              <div style={{ fontSize: 10, color: '#94A3B8', marginTop: 2 }}>{s.l}</div>
            </div>
          ))
        ) : (
          [
            { v: stats7d.total, l: 'Total no período', c: '#38BDF8' },
            { v: stats7d.max,   l: 'Maior dia',         c: '#F59E0B' },
            { v: stats7d.avg,   l: 'Média/dia',         c: '#22C55E' },
          ].map((s, i) => (
            <div key={i} style={{
              background: `${s.c}15`, border: `1px solid ${s.c}30`,
              borderRadius: 12, padding: '12px 8px', textAlign: 'center',
            }}>
              <div style={{ fontSize: 18, fontWeight: 800, color: s.c, letterSpacing: '-0.02em' }}>{s.v}</div>
              <div style={{ fontSize: 10, color: '#94A3B8', marginTop: 2 }}>{s.l}</div>
            </div>
          ))
        )}
      </div>

      {/* Chart area */}
      <div style={{ padding: '0 18px 18px' }}>
        <div style={{
          background: 'rgba(30,41,59,0.5)', border: '1px solid rgba(148,163,184,0.1)',
          borderRadius: 14, padding: '16px 14px 12px', position: 'relative',
        }}>
          {tab === '24h' ? (
            <svg viewBox="0 0 280 130" style={{ width: '100%', height: 130 }}>
              {/* gridlines */}
              {[0, 25, 50, 75, 100].map(y => (
                <g key={y}>
                  <line x1="20" x2="280" y1={120 - (y/100)*100} y2={120 - (y/100)*100} stroke="rgba(148,163,184,0.1)" strokeWidth="0.5"/>
                  <text x="0" y={120 - (y/100)*100 + 3} fontSize="8" fill="#94A3B8">{y}%</text>
                </g>
              ))}
              {(() => {
                const xs = pts24h.map((_, i) => 20 + (i / (pts24h.length - 1)) * 260);
                const ys = pts24h.map(v => 120 - (v / 100) * 100);
                const path = pts24h.map((_, i) => `${i===0?'M':'L'}${xs[i]},${ys[i]}`).join(' ');
                const areaPath = `${path} L${xs[xs.length-1]},120 L${xs[0]},120 Z`;
                return (<>
                  <defs>
                    <linearGradient id="histGrad" x1="0" y1="0" x2="0" y2="1">
                      <stop offset="0%" stopColor="#38BDF8" stopOpacity="0.4"/>
                      <stop offset="100%" stopColor="#38BDF8" stopOpacity="0"/>
                    </linearGradient>
                  </defs>
                  <path d={areaPath} fill="url(#histGrad)"/>
                  <path d={path} fill="none" stroke="#38BDF8" strokeWidth="2"/>
                  {pts24h.map((v, i) => (
                    <circle key={i} cx={xs[i]} cy={ys[i]} r="2.5" fill="#38BDF8" stroke="#0A1220" strokeWidth="1"/>
                  ))}
                </>);
              })()}
              <text x="20" y="128" fontSize="8" fill="#94A3B8">14:00</text>
              <text x="260" y="128" fontSize="8" fill="#94A3B8">18:00</text>
            </svg>
          ) : (
            <svg viewBox="0 0 280 130" style={{ width: '100%', height: 130 }}>
              {[0, 1, 2, 3, 4, 5].map(y => (
                <g key={y}>
                  <line x1="20" x2="280" y1={110 - (y/5)*95} y2={110 - (y/5)*95} stroke="rgba(148,163,184,0.1)" strokeWidth="0.5"/>
                  <text x="0" y={110 - (y/5)*95 + 3} fontSize="8" fill="#94A3B8">{y}h</text>
                </g>
              ))}
              {days7.map((d, i) => {
                const x = 32 + i * 35;
                const h = (d.v / 5) * 95;
                return (
                  <g key={i}>
                    {h > 0 && (
                      <rect x={x} y={110 - h} width="22" height={h} rx="3"
                            fill="#38BDF8" opacity={d.v >= 3 ? 1 : 0.7}/>
                    )}
                    <text x={x + 11} y="125" fontSize="7" fill="#94A3B8" textAnchor="middle">{d.d}</text>
                  </g>
                );
              })}
            </svg>
          )}
        </div>
      </div>

      {/* List */}
      <div style={{ padding: '0 18px 22px' }}>
        <div style={{ fontSize: 13, fontWeight: 700, marginBottom: 10 }}>
          {tab === '24h' ? 'Leituras recentes' : 'Por dia'}
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
          {tab === '24h' ? (
            [
              { v: '43.8%', t: '18:25', s: 'Bomba desligada' },
              { v: '46.2%', t: '18:25', s: 'Bomba desligada' },
              { v: '43.2%', t: '18:24', s: 'Bomba desligada' },
              { v: '45.3%', t: '18:23', s: 'Bomba desligada' },
            ].map((r, i) => (
              <div key={i} style={{
                display: 'flex', alignItems: 'center', gap: 8, padding: '8px 10px',
                background: 'rgba(30,41,59,0.5)', borderRadius: 10, fontSize: 11,
              }}>
                <span style={{ width: 6, height: 6, borderRadius: '50%', background: '#F59E0B' }}/>
                <span style={{ color: '#F59E0B', fontWeight: 700 }}>{r.v}</span>
                <span style={{ color: '#94A3B8', flex: 1 }}>{r.s}</span>
                <span style={{ color: '#94A3B8' }}>{r.t}</span>
              </div>
            ))
          ) : (
            [
              { d: 'Seg, 04/05', v: '1.0h ligada', c: '#38BDF8' },
              { d: 'Dom, 03/05', v: '1.4h ligada', c: '#38BDF8' },
              { d: 'Sáb, 02/05', v: '0.4h ligada', c: '#38BDF8' },
              { d: 'Sex, 01/05', v: 'Não acionada', c: '#64748B' },
            ].map((r, i) => (
              <div key={i} style={{
                display: 'flex', alignItems: 'center', gap: 8, padding: '8px 10px',
                background: 'rgba(30,41,59,0.5)', borderRadius: 10, fontSize: 11,
              }}>
                <span style={{ color: '#CBD5E1', flex: 1 }}>{r.d}</span>
                <span style={{ color: r.c, fontWeight: 600 }}>{r.v}</span>
              </div>
            ))
          )}
        </div>
      </div>
    </div>
  );
}

// ─── Configuration screen (sliders) ────────────────────────────
function ConfigSlider({ icon, title, value, valueColor, desc, pct, color, dotted }) {
  return (
    <div style={{ marginBottom: 18 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13, fontWeight: 700, color: '#F8FAFC' }}>
          {icon}
          {title}
        </div>
        <span style={{ color: valueColor || color, fontWeight: 700, fontSize: 13 }}>{value}</span>
      </div>
      <div style={{ position: 'relative', height: 6, marginBottom: desc ? 8 : 0 }}>
        {/* dotted track */}
        <div style={{
          position: 'absolute', inset: 0,
          backgroundImage: `radial-gradient(circle, rgba(148,163,184,0.35) 1px, transparent 1.2px)`,
          backgroundSize: '8px 6px',
          backgroundPosition: 'left center',
          backgroundRepeat: 'repeat-x',
        }}/>
        {/* filled portion */}
        <div style={{
          position: 'absolute', left: 0, top: 1, height: 4, width: `${pct}%`,
          background: color, borderRadius: 2,
        }}/>
        {/* thumb */}
        <div style={{
          position: 'absolute', left: `calc(${pct}% - 8px)`, top: -4,
          width: 14, height: 14, borderRadius: '50%', background: color,
          boxShadow: `0 0 12px ${color}88, 0 0 0 3px rgba(10,18,32,0.8)`,
        }}/>
      </div>
      {desc && (
        <div style={{ fontSize: 11, color: '#94A3B8', lineHeight: 1.45, marginTop: 8 }}>{desc}</div>
      )}
    </div>
  );
}

function ConfigScreen() {
  return (
    <div style={{
      width: 340, minHeight: 720, background: '#0A1220', borderRadius: 28,
      border: '1px solid rgba(148,163,184,0.12)', overflow: 'hidden',
      display: 'flex', flexDirection: 'column',
      boxShadow: '0 40px 100px rgba(0,0,0,0.6), 0 0 0 1px rgba(56,189,248,0.06)',
      fontFamily: 'Inter, sans-serif', color: '#F8FAFC',
    }}>
      {/* Header */}
      <div style={{ padding: '20px 18px 18px', display: 'flex', alignItems: 'center', gap: 12, borderBottom: '1px solid rgba(148,163,184,0.08)' }}>
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2"><path d="m15 18-6-6 6-6"/></svg>
        <div style={{ fontSize: 17, fontWeight: 700 }}>Configuração Técnica</div>
      </div>

      {/* Scroll body */}
      <div style={{ flex: 1, overflowY: 'auto', padding: '18px' }}>
        <ConfigSlider
          icon={<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#38BDF8" strokeWidth="2"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>}
          title="Delay de acionamento"
          value="0 seg"
          valueColor="#38BDF8"
          desc="Tempo de espera antes de acionar a bomba após atingir o nível de acionamento."
          pct={2}
          color="#38BDF8"
        />

        <ConfigSlider
          icon={<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#38BDF8" strokeWidth="2"><path d="M3 12a9 9 0 1 0 9-9"/><polyline points="3 4 3 12 11 12"/></svg>}
          title="Cooldown após desligar"
          value="Sem espera"
          valueColor="#38BDF8"
          desc="Tempo mínimo que a bomba fica desligada entre dois ciclos consecutivos. Evita liga/desliga repetido, mas valores altos atrasam o reacionamento."
          pct={4}
          color="#38BDF8"
        />

        <ConfigSlider
          icon={<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#F59E0B" strokeWidth="2"><circle cx="12" cy="12" r="10"/><path d="M4.93 4.93l14.14 14.14"/></svg>}
          title="Tempo máximo ligada"
          value="1h 30min"
          valueColor="#F59E0B"
          desc="Segurança: a bomba é desligada automaticamente se ultrapassar esse tempo. Defina de acordo com o volume do reservatório e a vazão da bomba."
          pct={42}
          color="#F59E0B"
        />

        {/* Limites de Alerta */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 14, fontWeight: 700, color: '#38BDF8', margin: '4px 0 16px', paddingTop: 14, borderTop: '1px solid rgba(148,163,184,0.08)' }}>
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#38BDF8" strokeWidth="2"><path d="M18 8a6 6 0 0 0-12 0c0 7-3 9-3 9h18s-3-2-3-9"/><path d="M13.73 21a2 2 0 0 1-3.46 0"/></svg>
          Limites de Alerta
        </div>

        <ConfigSlider
          icon={<span style={{ fontSize: 14 }}>🚨</span>}
          title="Nível crítico"
          value="15%"
          valueColor="#EF4444"
          pct={15}
          color="#EF4444"
        />

        <ConfigSlider
          icon={<svg width="14" height="14" viewBox="0 0 24 24" 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"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>}
          title="Nível mínimo"
          value="30%"
          valueColor="#F59E0B"
          pct={30}
          color="#F59E0B"
        />

        <ConfigSlider
          icon={<svg width="14" height="14" viewBox="0 0 24 24" fill="#38BDF8"><path d="M12 2.69l5.66 5.66a8 8 0 1 1-11.31 0z"/></svg>}
          title="Nível máximo"
          value="90%"
          valueColor="#22C55E"
          pct={90}
          color="#22C55E"
        />
      </div>

      {/* Footer */}
      <div style={{ padding: '14px 18px 18px', borderTop: '1px solid rgba(148,163,184,0.08)' }}>
        <button style={{
          width: '100%', padding: '14px', borderRadius: 14, border: 'none',
          background: '#38BDF8', color: '#0A1220', fontWeight: 700, fontSize: 14, cursor: 'pointer',
        }}>Salvar Configuração</button>
      </div>
    </div>
  );
}

// ─── Notification preview ──────────────────────────────────────
function NotifScreen() {
  return (
    <div style={{
      width: 340, minHeight: 720, background: '#0A1220', borderRadius: 28,
      border: '1px solid rgba(148,163,184,0.12)', overflow: 'hidden',
      display: 'flex', flexDirection: 'column',
      boxShadow: '0 40px 100px rgba(0,0,0,0.6), 0 0 0 1px rgba(56,189,248,0.06)',
      fontFamily: 'Inter, sans-serif', color: '#F8FAFC',
      padding: '20px 18px',
    }}>
      <div style={{ fontSize: 18, fontWeight: 700, marginBottom: 16 }}>Notificações</div>
      {[
        { icon: '⚠', color: '#EF4444', title: 'Nível crítico', sub: 'Bloco B · 14% — bomba ligando', t: 'agora' },
        { icon: '✓', color: '#22C55E', title: 'Bomba desligou', sub: 'Torre Principal atingiu 95%', t: '2min' },
        { icon: '⚡', color: '#38BDF8', title: 'Sensor calibrado', sub: 'Cisterna · leitura precisa', t: '1h' },
        { icon: '📊', color: '#F59E0B', title: 'Consumo acima do normal', sub: '+18% vs média da semana', t: '3h' },
      ].map((n, i) => (
        <div key={i} style={{
          display: 'flex', gap: 12, padding: '12px',
          background: 'rgba(30,41,59,0.5)', borderRadius: 14,
          marginBottom: 8, border: `1px solid ${n.color}20`,
        }}>
          <div style={{
            width: 36, height: 36, borderRadius: 10, flexShrink: 0,
            background: `${n.color}20`, color: n.color,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontSize: 16, fontWeight: 700,
          }}>{n.icon}</div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
              <span style={{ fontSize: 13, fontWeight: 700 }}>{n.title}</span>
              <span style={{ fontSize: 10, color: '#94A3B8' }}>{n.t}</span>
            </div>
            <div style={{ fontSize: 11, color: '#94A3B8', marginTop: 2 }}>{n.sub}</div>
          </div>
        </div>
      ))}
    </div>
  );
}

window.HistoryScreen = HistoryScreen;
window.ConfigScreen = ConfigScreen;
window.NotifScreen = NotifScreen;
