/* Dark dashboard section - Resend-inspired (original layout) */
const { useEffect: useEffectD, useState: useStateD } = React;

function DarkDashboard() {
  const [num, setNum] = useStateD({ conv: 1284, leads: 312, ped: 87, fup: 154 });

  useEffectD(() => {
    const id = setInterval(() => {
      setNum(n => ({
        conv: n.conv + Math.floor(Math.random() * 3),
        leads: n.leads + (Math.random() > 0.6 ? 1 : 0),
        ped: n.ped + (Math.random() > 0.75 ? 1 : 0),
        fup: n.fup + (Math.random() > 0.7 ? 1 : 0)
      }));
    }, 2200);
    return () => clearInterval(id);
  }, []);

  const cardStyle = {
    background: 'linear-gradient(180deg, rgba(255,255,255,0.04), rgba(255,255,255,0.015))',
    border: '1px solid var(--dark-line-2)',
    borderRadius: 14,
    padding: 18,
    position: 'relative',
    overflow: 'hidden'
  };

  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 18 }}>
      {/* Left: dashboard */}
      <div style={cardStyle}>
        {/* dashboard header */}
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 18 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <div style={{
              width: 24, height: 24, borderRadius: 7,
              background: 'radial-gradient(120% 120% at 0% 0%, #5CE1E6, #2563EB)',
              boxShadow: '0 6px 14px -6px rgba(37,99,235,0.6)'
            }} />
            <span style={{ fontSize: 13, fontWeight: 600 }}>Central de Operação</span>
            <span className="chip dark mono" style={{ fontSize: 10.5 }}>live · loja-centro</span>
          </div>
          <div style={{ display: 'flex', gap: 6 }}>
            {['1h', '24h', '7d'].map((t, i) => (
              <span key={t} className="mono" style={{
                fontSize: 11, padding: '4px 9px', borderRadius: 6,
                color: i === 1 ? '#fff' : 'var(--dark-muted)',
                background: i === 1 ? 'rgba(255,255,255,0.08)' : 'transparent',
                border: '1px solid ' + (i === 1 ? 'var(--dark-line-2)' : 'transparent')
              }}>{t}</span>
            ))}
          </div>
        </div>

        {/* metric tiles */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 10, marginBottom: 16 }}>
          <MetricTile label="Conversas respondidas" value={num.conv} delta="+12%" color="#5CE1E6" />
          <MetricTile label="Leads capturados" value={num.leads} delta="+24%" color="#2563EB" />
          <MetricTile label="Pedidos gerados" value={num.ped} delta="+9%" color="#C6A15B" />
          <MetricTile label="Follow-ups agendados" value={num.fup} delta="+3%" color="#22c55e" />
        </div>

        {/* chart */}
        <DashChart />

        {/* event log */}
        <div style={{ marginTop: 16, display: 'flex', flexDirection: 'column', gap: 6 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 4 }}>
            <span className="mono" style={{ fontSize: 11, color: 'var(--dark-muted)', letterSpacing: '0.06em', textTransform: 'uppercase' }}>Eventos · ao vivo</span>
            <span className="mono" style={{ fontSize: 11, color: '#22c55e' }}>● streaming</span>
          </div>
          <LogRow time="14:32:08" tag="POST" tagColor="#5CE1E6" msg="agent.reply · conversa_8421 · 412ms" />
          <LogRow time="14:32:05" tag="EVT"  tagColor="#C6A15B" msg="lead.created · Marina S. · pedido pendente" />
          <LogRow time="14:32:02" tag="200"  tagColor="#22c55e" msg="webhook.crm · sincronizado em 88ms" />
          <LogRow time="14:31:57" tag="POST" tagColor="#5CE1E6" msg="followup.scheduled · template_promo_24h" />
        </div>
      </div>

      {/* Right: code + alerts + status */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
        <div style={cardStyle}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
            <span className="mono" style={{ fontSize: 11.5, color: 'var(--dark-muted)' }}>POST /v1/agent/reply</span>
            <span className="chip dark mono" style={{ fontSize: 10.5 }}>200 OK · 412ms</span>
          </div>
          <pre className="code" style={{ margin: 0, whiteSpace: 'pre-wrap' }}>
{`{
  `}<span className="k">"channel"</span>{`: `}<span className="s">"whatsapp"</span>{`,
  `}<span className="k">"intent"</span>{`: `}<span className="s">"pedido"</span>{`,
  `}<span className="k">"confidence"</span>{`: `}<span className="n">0.96</span>{`,
  `}<span className="k">"actions"</span>{`: [`}<span className="s">"crm.create_lead"</span>{`,
              `}<span className="s">"followup.schedule_24h"</span>{`],
  `}<span className="k">"reply"</span>{`: `}<span className="s">"Sim, entregamos! Posso..."</span>{`
}`}
          </pre>
        </div>

        <div style={cardStyle}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
            <span className="mono" style={{ fontSize: 11.5, color: 'var(--dark-muted)', letterSpacing: '0.06em', textTransform: 'uppercase' }}>Alertas para equipe</span>
            <span className="mono" style={{ fontSize: 11, color: '#C6A15B' }}>2 abertos</span>
          </div>
          <Alert color="#C6A15B" title="Lead quente sem resposta" sub="Pedro M. · WhatsApp · há 8 min" />
          <Alert color="#2563EB" title="Alta demanda em delivery" sub="14 conversas simultâneas · pico" last />
        </div>

        <div style={cardStyle}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
            <span className="mono" style={{ fontSize: 11.5, color: 'var(--dark-muted)', letterSpacing: '0.06em', textTransform: 'uppercase' }}>Status da automação</span>
            <span className="mono" style={{ fontSize: 11, color: '#22c55e' }}>● healthy</span>
          </div>
          <StatusRow name="Agente IA · WhatsApp" pct={100} />
          <StatusRow name="Sincronização CRM" pct={99.8} />
          <StatusRow name="Pipeline n8n" pct={100} />
          <StatusRow name="Webhook Meta Ads" pct={97.2} warn last />
        </div>
      </div>
    </div>
  );
}

function MetricTile({ label, value, delta, color }) {
  return (
    <div style={{
      padding: 12,
      background: 'rgba(255,255,255,0.025)',
      border: '1px solid var(--dark-line)',
      borderRadius: 10,
      position: 'relative',
      overflow: 'hidden'
    }}>
      <div style={{
        position: 'absolute', top: 0, left: 0, width: '100%', height: 2,
        background: `linear-gradient(90deg, ${color}, transparent)`
      }} />
      <div className="mono" style={{ fontSize: 10.5, color: 'var(--dark-muted)', textTransform: 'uppercase', letterSpacing: '0.04em', marginBottom: 6 }}>
        {label}
      </div>
      <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between' }}>
        <div style={{ fontSize: 22, fontWeight: 600, letterSpacing: '-0.02em' }}>{value.toLocaleString('pt-BR')}</div>
        <span className="mono" style={{ fontSize: 11, color: '#22c55e' }}>{delta}</span>
      </div>
    </div>
  );
}

function DashChart() {
  // Mock sparkline / area chart with gradient
  const points = [12, 18, 14, 22, 28, 24, 32, 30, 38, 35, 44, 48, 42, 52, 58, 55, 64, 70, 68, 76, 82, 78, 88, 95];
  const max = 100;
  const w = 100, h = 100;
  const step = w / (points.length - 1);
  const path = points.map((p, i) => `${i === 0 ? 'M' : 'L'} ${(i * step).toFixed(2)} ${(h - (p / max) * h).toFixed(2)}`).join(' ');
  const area = path + ` L ${w} ${h} L 0 ${h} Z`;

  return (
    <div style={{
      border: '1px solid var(--dark-line)', borderRadius: 10,
      padding: 12, background: 'rgba(255,255,255,0.015)'
    }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
        <span className="mono" style={{ fontSize: 11, color: 'var(--dark-muted)', textTransform: 'uppercase', letterSpacing: '0.04em' }}>
          Conversões · últimas 24h
        </span>
        <span className="mono" style={{ fontSize: 11, color: '#fff' }}>R$ 14.328</span>
      </div>
      <svg viewBox={`0 0 ${w} ${h}`} preserveAspectRatio="none" style={{ width: '100%', height: 90 }}>
        <defs>
          <linearGradient id="darkArea" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor="#5CE1E6" stopOpacity="0.45" />
            <stop offset="100%" stopColor="#5CE1E6" stopOpacity="0" />
          </linearGradient>
          <linearGradient id="darkLine" x1="0" y1="0" x2="1" y2="0">
            <stop offset="0%" stopColor="#2563EB" />
            <stop offset="100%" stopColor="#5CE1E6" />
          </linearGradient>
        </defs>
        <path d={area} fill="url(#darkArea)" />
        <path d={path} fill="none" stroke="url(#darkLine)" strokeWidth="1.5" vectorEffect="non-scaling-stroke" />
        {/* live dot */}
        <circle cx={w} cy={h - (points[points.length - 1] / max) * h} r="2" fill="#5CE1E6">
          <animate attributeName="r" values="2;4;2" dur="1.8s" repeatCount="indefinite" />
        </circle>
      </svg>
    </div>
  );
}

function LogRow({ time, tag, tagColor, msg }) {
  return (
    <div className="mono" style={{
      display: 'grid', gridTemplateColumns: '60px 50px 1fr', gap: 10,
      fontSize: 11.5, padding: '4px 0', color: 'var(--dark-muted)',
      borderBottom: '1px dashed rgba(255,255,255,0.05)'
    }}>
      <span>{time}</span>
      <span style={{ color: tagColor }}>{tag}</span>
      <span style={{ color: '#e5e7eb' }}>{msg}</span>
    </div>
  );
}

function Alert({ color, title, sub, last }) {
  return (
    <div style={{
      display: 'flex', gap: 10, padding: '10px 0',
      borderBottom: last ? 'none' : '1px dashed rgba(255,255,255,0.06)'
    }}>
      <span style={{ width: 4, alignSelf: 'stretch', borderRadius: 99, background: color, marginTop: 2 }} />
      <div style={{ flex: 1 }}>
        <div style={{ fontSize: 13, color: '#fff', marginBottom: 2 }}>{title}</div>
        <div className="mono" style={{ fontSize: 11, color: 'var(--dark-muted)' }}>{sub}</div>
      </div>
    </div>
  );
}

function StatusRow({ name, pct, warn, last }) {
  return (
    <div style={{
      padding: '10px 0',
      borderBottom: last ? 'none' : '1px dashed rgba(255,255,255,0.06)'
    }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 6 }}>
        <span style={{ fontSize: 12.5, color: '#e5e7eb' }}>{name}</span>
        <span className="mono" style={{ fontSize: 11, color: warn ? '#C6A15B' : '#22c55e' }}>{pct.toFixed(1)}%</span>
      </div>
      <div style={{ height: 3, borderRadius: 99, background: 'rgba(255,255,255,0.06)', overflow: 'hidden' }}>
        <div style={{
          height: '100%', width: `${pct}%`,
          background: warn ? 'linear-gradient(90deg, #C6A15B, #f4d089)' : 'linear-gradient(90deg, #2563EB, #5CE1E6)'
        }} />
      </div>
    </div>
  );
}

window.DarkDashboard = DarkDashboard;
