/* Live dashboard mockup with animated chart + AI typing */
const useTicker = (interval = 1500) => {
  const [tick, setTick] = React.useState(0);
  React.useEffect(() => {
    const id = setInterval(() => setTick(t => t + 1), interval);
    return () => clearInterval(id);
  }, [interval]);
  return tick;
};

const AreaChart = () => {
  const tick = useTicker(2200);
  const points = React.useMemo(() => {
    const n = 28;
    let v = 50 + Math.random() * 20;
    const out = [];
    for (let i = 0; i < n; i++) {
      v += (Math.random() - 0.45) * 16;
      v = Math.max(20, Math.min(96, v));
      out.push(v);
    }
    return out;
  }, [tick]);
  const points2 = React.useMemo(() => {
    return points.map(p => Math.max(15, Math.min(80, p - 12 - Math.random() * 12)));
  }, [points]);

  const W = 600, H = 130, P = 4;
  const path = (arr) => {
    return arr.map((y, i) => {
      const x = P + (i / (arr.length - 1)) * (W - P*2);
      const yy = H - P - (y / 100) * (H - P*2);
      return `${i === 0 ? 'M' : 'L'} ${x.toFixed(1)} ${yy.toFixed(1)}`;
    }).join(' ');
  };
  const area = (arr) => {
    return path(arr) + ` L ${W - P} ${H - P} L ${P} ${H - P} Z`;
  };

  return (
    <svg viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="none" style={{ width: '100%', height: '100%' }}>
      <defs>
        <linearGradient id="ag1" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0" stopColor="#22c55e" stopOpacity="0.4" />
          <stop offset="1" stopColor="#22c55e" stopOpacity="0" />
        </linearGradient>
        <linearGradient id="ag2" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0" stopColor="#06b6d4" stopOpacity="0.3" />
          <stop offset="1" stopColor="#06b6d4" stopOpacity="0" />
        </linearGradient>
        <linearGradient id="ag-line" x1="0" y1="0" x2="1" y2="0">
          <stop offset="0" stopColor="#22c55e" />
          <stop offset="1" stopColor="#06b6d4" />
        </linearGradient>
        {[0,1,2,3].map(i => (
          <line key={i} x1={P} x2={W-P} y1={P + ((H-P*2) * i)/3} y2={P + ((H-P*2) * i)/3} stroke="rgba(255,255,255,0.04)" />
        ))}
      </defs>
      {[0,1,2,3].map(i => (
        <line key={i} x1={P} x2={W-P} y1={P + ((H-P*2) * i)/3} y2={P + ((H-P*2) * i)/3} stroke="rgba(255,255,255,0.05)" strokeDasharray="2 4" />
      ))}
      <path d={area(points2)} fill="url(#ag2)" style={{ transition: 'd 1s ease' }} />
      <path d={path(points2)} fill="none" stroke="#06b6d4" strokeWidth="1.2" opacity="0.55" style={{ transition: 'd 1s ease' }} />
      <path d={area(points)} fill="url(#ag1)" style={{ transition: 'd 1s ease' }} />
      <path d={path(points)} fill="none" stroke="url(#ag-line)" strokeWidth="1.6" style={{ transition: 'd 1s ease' }} />
    </svg>
  );
};

const TypingAI = () => {
  const messages = [
    { p: 'Detecté un patrón en las citas de mañana. ', hl: '3 clientes recurrentes podrían cambiar al horario AM.', s: ' Sugiero contactarlos hoy.' },
    { p: '', hl: 'Inventario crítico:', s: ' 4 productos bajo el umbral. Generé orden automática a proveedor.' },
    { p: 'El restaurante de Sur tiene ', hl: '+18% de ventas los jueves.', s: ' Activo promo automatizada para replicar en otras sucursales.' },
  ];
  const [idx, setIdx] = React.useState(0);
  const [shown, setShown] = React.useState('');
  const [phase, setPhase] = React.useState(0); // 0: prefix, 1: hl, 2: suffix, 3: hold

  React.useEffect(() => {
    const m = messages[idx];
    let target = '';
    if (phase === 0) target = m.p;
    else if (phase === 1) target = m.p + m.hl;
    else if (phase === 2) target = m.p + m.hl + m.s;

    if (phase === 3) {
      const id = setTimeout(() => {
        setIdx(i => (i + 1) % messages.length);
        setShown('');
        setPhase(0);
      }, 4200);
      return () => clearTimeout(id);
    }

    if (shown.length < target.length) {
      const id = setTimeout(() => setShown(target.slice(0, shown.length + 1)), 22 + Math.random() * 18);
      return () => clearTimeout(id);
    } else {
      setPhase(p => p + 1);
    }
  }, [shown, phase, idx]);

  // render with highlighting
  const m = messages[idx];
  const pLen = m.p.length;
  const hlLen = m.hl.length;
  const visible = shown;
  const partP = visible.slice(0, Math.min(pLen, visible.length));
  const partHL = visible.slice(pLen, Math.min(pLen + hlLen, visible.length));
  const partS = visible.slice(pLen + hlLen);

  return (
    <p className="dash-ai-text dash-ai-cursor">
      {partP}<span className="hl">{partHL}</span>{partS}
    </p>
  );
};

const useCount = (target, duration = 1600) => {
  const [v, setV] = React.useState(0);
  const ref = React.useRef(null);
  React.useEffect(() => {
    let started = false;
    const obs = new IntersectionObserver((entries) => {
      entries.forEach(e => {
        if (e.isIntersecting && !started) {
          started = true;
          const start = performance.now();
          const tick = (now) => {
            const t = Math.min(1, (now - start) / duration);
            const eased = 1 - Math.pow(1 - t, 3);
            setV(Math.round(target * eased));
            if (t < 1) requestAnimationFrame(tick);
          };
          requestAnimationFrame(tick);
        }
      });
    }, { threshold: 0.4 });
    if (ref.current) obs.observe(ref.current);
    return () => obs.disconnect();
  }, [target, duration]);
  return [v, ref];
};

const Counter = ({ target, suffix = '', prefix = '' }) => {
  const [v, ref] = useCount(target);
  return <span ref={ref} className="grad">{prefix}{v.toLocaleString('es-MX')}{suffix}</span>;
};

const KPI = ({ label, value, delta, down }) => {
  const tick = useTicker(2400);
  const display = React.useMemo(() => {
    const variation = (Math.sin(tick * 1.3) * 0.04) + 1;
    if (typeof value === 'number') return Math.round(value * variation).toLocaleString('es-MX');
    return value;
  }, [tick, value]);
  return (
    <div className="dash-kpi">
      <div className="l">{label}</div>
      <div className="v">{display}</div>
      <div className={`d ${down ? 'down' : ''}`}>{down ? '↓' : '↑'} {delta}</div>
    </div>
  );
};

const Icon = ({ name, size = 16 }) => {
  const paths = {
    home: <><path d="M3 12L12 4l9 8" /><path d="M5 10v10h14V10" /></>,
    activity: <polyline points="22 12 18 12 15 21 9 3 6 12 2 12" />,
    users: <><circle cx="9" cy="7" r="4" /><path d="M3 21v-2a4 4 0 0 1 4-4h4a4 4 0 0 1 4 4v2" /><circle cx="17" cy="7" r="3" /></>,
    box: <><path d="M21 8l-9 4-9-4 9-4z" /><path d="M3 8v9l9 4 9-4V8" /></>,
    settings: <><circle cx="12" cy="12" r="3" /><path d="M19 12a7 7 0 0 0-.1-1.2l2-1.6-2-3.4-2.4.9a7 7 0 0 0-2-1.2L14 3h-4l-.5 2.5a7 7 0 0 0-2 1.2l-2.4-.9-2 3.4 2 1.6A7 7 0 0 0 5 12a7 7 0 0 0 .1 1.2l-2 1.6 2 3.4 2.4-.9a7 7 0 0 0 2 1.2L10 21h4l.5-2.5a7 7 0 0 0 2-1.2l2.4.9 2-3.4-2-1.6a7 7 0 0 0 .1-1.2z" /></>,
    chart: <><path d="M3 3v18h18" /><polyline points="7 14 11 10 14 13 21 6" /></>,
    bell: <><path d="M18 8a6 6 0 0 0-12 0c0 7-3 9-3 9h18s-3-2-3-9" /><path d="M13.7 21a2 2 0 0 1-3.4 0" /></>,
    sparkles: <><path d="M12 3l2 5 5 2-5 2-2 5-2-5-5-2 5-2z" /><path d="M19 14l1 2 2 1-2 1-1 2-1-2-2-1 2-1z" /></>,
  };
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">
      {paths[name]}
    </svg>
  );
};

// Section content components
const AIPopup = () => {
  const [open, setOpen] = React.useState(false);
  return (
    <>
      <button
        className="dash-ai-popup-btn"
        onClick={() => setOpen(true)}
        style={{
          position: 'absolute',
          bottom: 16,
          right: 16,
          width: 48,
          height: 48,
          borderRadius: 12,
          background: 'var(--grad)',
          border: 'none',
          color: '#fff',
          cursor: 'pointer',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          boxShadow: '0 4px 12px rgba(34,197,94,0.3)',
          zIndex: 100,
          transition: 'transform 0.2s',
        }}
        onMouseEnter={(e) => e.target.style.transform = 'scale(1.05)'}
        onMouseLeave={(e) => e.target.style.transform = 'scale(1)'}
      >
        <Icon name="sparkles" size={20} />
      </button>
      {open && (
        <div
          className="dash-ai-popup-overlay"
          onClick={() => setOpen(false)}
          style={{
            position: 'absolute',
            inset: 0,
            background: 'rgba(0,0,0,0.5)',
            zIndex: 99,
            borderRadius: 8,
          }}
        />
      )}
      {open && (
        <div
          className="dash-ai-popup"
          style={{
            position: 'absolute',
            bottom: 16,
            right: 16,
            width: 320,
            background: '#0b0f19',
            border: '1px solid rgba(255,255,255,0.1)',
            borderRadius: 12,
            boxShadow: '0 8px 24px rgba(0,0,0,0.4)',
            zIndex: 100,
            overflow: 'hidden',
          }}
        >
          <div className="dash-ai-head">
            <div className="ic"><Icon name="sparkles" size={13} /></div>
            <div className="t">Asistente IA</div>
            <div className="ping" />
            <button
              onClick={() => setOpen(false)}
              style={{
                marginLeft: 'auto',
                background: 'none',
                border: 'none',
                color: 'rgba(255,255,255,0.5)',
                cursor: 'pointer',
                fontSize: 18,
              }}
            >
              ×
            </button>
          </div>
          <div style={{ padding: 12 }}>
            <TypingAI />
          </div>
        </div>
      )}
    </>
  );
};

const ResumenView = () => (
  <div style={{ minHeight: 600 }}>
    <div className="dash-kpi-row">
      <KPI label="Citas hoy" value={42} delta="+12% vs ayer" />
      <KPI label="Ingresos" value="$58,420" delta="+8.4%" />
      <KPI label="Ocupación" value="87%" delta="+5pts" />
      <KPI label="No-show" value={6} delta="−2.1%" down />
    </div>
    <div className="dash-chart">
      <div className="dash-chart-head">
        <span className="t">Flujo de pacientes · 28 días</span>
        <span className="legend">
          <span><i style={{ background: '#22c55e' }} /> Atendidos</span>
          <span><i style={{ background: '#06b6d4' }} /> Programados</span>
        </span>
      </div>
      <div style={{ position: 'absolute', left: 14, right: 14, top: 36, bottom: 14 }}>
        <AreaChart />
      </div>
    </div>
    <div className="dash-rows">
      <div className="dash-row">
        <span className="av">MR</span>
        <div>
          <div className="nm">María Rodríguez · Consulta general</div>
        </div>
        <span className="ag">15:00</span>
        <span className="st">Confirmada</span>
      </div>
      <div className="dash-row">
        <span className="av">JL</span>
        <div>
          <div className="nm">Javier López · Seguimiento</div>
        </div>
        <span className="ag">15:30</span>
        <span className="st info">Recordatorio enviado</span>
      </div>
      <div className="dash-row">
        <span className="av">AC</span>
        <div>
          <div className="nm">Ana Carrillo · Primera vez</div>
        </div>
        <span className="ag">16:00</span>
        <span className="st warn">Falta confirmar</span>
      </div>
    </div>
    <div className="dash-ai">
      <div className="dash-ai-head">
        <div className="ic"><Icon name="sparkles" size={13} /></div>
        <div className="t">Asistente IA</div>
        <div className="ping" />
      </div>
      <TypingAI />
    </div>
  </div>
);

const PacientesView = () => (
  <div style={{ minHeight: 600 }}>
    <div className="dash-kpi-row">
      <KPI label="Total pacientes" value={1,247} delta="+23 este mes" />
      <KPI label="Activos" value={892} delta="+5.2%" />
      <KPI label="Nuevos" value={34} delta="+12%" />
      <KPI label="Retención" value={94} delta="+2pts" />
    </div>
    <div className="dash-table">
      <div className="dash-table-head">
        <span>Paciente</span>
        <span>Última visita</span>
        <span>Estado</span>
        <span>Acciones</span>
      </div>
      <div className="dash-table-body">
        {[
          { name: 'María Rodríguez', last: '15 abr 2026', status: 'Activo' },
          { name: 'Javier López', last: '22 abr 2026', status: 'Activo' },
          { name: 'Ana Carrillo', last: '29 abr 2026', status: 'Pendiente' },
          { name: 'Carlos Méndez', last: '10 abr 2026', status: 'Inactivo' },
          { name: 'Laura Vega', last: '18 abr 2026', status: 'Activo' },
        ].map((p, i) => (
          <div key={i} className="dash-table-row">
            <span className="nm">{p.name}</span>
            <span className="ag">{p.last}</span>
            <span className={`st ${p.status === 'Inactivo' ? 'warn' : p.status === 'Pendiente' ? 'info' : ''}`}>{p.status}</span>
            <span className="actions">
              <button style={{ padding: '4px 8px', borderRadius: 6, background: 'rgba(34,197,94,0.1)', border: 'none', color: '#22c55e', fontSize: 12, cursor: 'pointer' }}>Ver</button>
            </span>
          </div>
        ))}
      </div>
    </div>
    <AIPopup />
  </div>
);

const CitasView = () => (
  <div style={{ minHeight: 600 }}>
    <div className="dash-kpi-row">
      <KPI label="Citas hoy" value={42} delta="+12% vs ayer" />
      <KPI label="Confirmadas" value={38} delta="+8%" />
      <KPI label="Pendientes" value={4} delta="-2" />
      <KPI label="No-show" value={6} delta="−2.1%" down />
    </div>
    <div className="dash-rows">
      {[
        { name: 'María Rodríguez · Consulta general', time: '15:00', status: 'Confirmada' },
        { name: 'Javier López · Seguimiento', time: '15:30', status: 'info', statusText: 'Recordatorio enviado' },
        { name: 'Ana Carrillo · Primera vez', time: '16:00', status: 'warn', statusText: 'Falta confirmar' },
        { name: 'Carlos Méndez · Cardiología', time: '16:30', status: 'Confirmada' },
        { name: 'Laura Vega · Dermatología', time: '17:00', status: 'Confirmada' },
        { name: 'Roberto Sánchez · Laboratorio', time: '17:30', status: 'info', statusText: 'En espera' },
      ].map((c, i) => (
        <div key={i} className="dash-row">
          <span className="av">{c.name.split(' ').map(n => n[0]).join('')}</span>
          <div>
            <div className="nm">{c.name}</div>
          </div>
          <span className="ag">{c.time}</span>
          <span className={`st ${c.status}`}>{c.statusText || c.status}</span>
        </div>
      ))}
    </div>
    <AIPopup />
  </div>
);

const InventarioView = () => (
  <div style={{ minHeight: 600 }}>
    <div className="dash-kpi-row">
      <KPI label="Productos" value={234} delta="+12" />
      <KPI label="Stock bajo" value={8} delta="−3" />
      <KPI label="Valor total" value="$124,500" delta="+5.2%" />
      <KPI label="Rotación" value="2.3x" delta="+0.4x" />
    </div>
    <div className="dash-table">
      <div className="dash-table-head">
        <span>Producto</span>
        <span>Categoría</span>
        <span>Stock</span>
        <span>Estado</span>
      </div>
      <div className="dash-table-body">
        {[
          { name: 'Paracetamol 500mg', cat: 'Medicamentos', stock: 145, status: 'OK' },
          { name: 'Ibuprofeno 400mg', cat: 'Medicamentos', stock: 89, status: 'OK' },
          { name: 'Guantes quirúrgicos', cat: 'Suministros', stock: 23, status: 'warn', statusText: 'Bajo' },
          { name: 'Jeringas 5ml', cat: 'Suministros', stock: 156, status: 'OK' },
          { name: 'Alcohol etílico', cat: 'Limpieza', stock: 8, status: 'warn', statusText: 'Crítico' },
        ].map((p, i) => (
          <div key={i} className="dash-table-row">
            <span className="nm">{p.name}</span>
            <span className="ag">{p.cat}</span>
            <span>{p.stock}</span>
            <span className={`st ${p.status === 'warn' ? 'warn' : ''}`}>{p.statusText || p.status}</span>
          </div>
        ))}
      </div>
    </div>
    <AIPopup />
  </div>
);

const AsistenteView = () => (
  <div style={{ minHeight: 600 }}>
    <div className="dash-kpi-row">
      <KPI label="Consultas hoy" value={47} delta="+15%" />
      <KPI label="Acciones sugeridas" value={12} delta="+4" />
      <KPI label="Tiempo ahorro" value="2.4h" delta="+0.8h" />
      <KPI label="Precisión" value={94} delta="+3%" />
    </div>
    <div className="dash-ai-full">
      <div className="dash-ai-head">
        <div className="ic"><Icon name="sparkles" size={13} /></div>
        <div className="t">Asistente IA · Historial</div>
        <div className="ping" />
      </div>
      <div className="dash-ai-history">
        <div className="dash-ai-msg">
          <div className="dash-ai-msg-label">Sugerencia 14:25</div>
          <p>Detecté un patrón en las citas de mañana. <span className="hl">3 clientes recurrentes podrían cambiar al horario AM.</span> Sugiero contactarlos hoy.</p>
          <div className="dash-ai-actions">
            <button style={{ padding: '6px 12px', borderRadius: 6, background: '#22c55e', border: 'none', color: '#0b0f19', fontSize: 12, fontWeight: 600, cursor: 'pointer' }}>Contactar</button>
            <button style={{ padding: '6px 12px', borderRadius: 6, background: 'rgba(255,255,255,0.1)', border: 'none', color: '#fff', fontSize: 12, cursor: 'pointer' }}>Ignorar</button>
          </div>
        </div>
        <div className="dash-ai-msg">
          <div className="dash-ai-msg-label">Alerta 14:18</div>
          <p><span className="hl">Inventario crítico:</span> 4 productos bajo el umbral. Generé orden automática a proveedor.</p>
          <div className="dash-ai-actions">
            <button style={{ padding: '6px 12px', borderRadius: 6, background: '#22c55e', border: 'none', color: '#0b0f19', fontSize: 12, fontWeight: 600, cursor: 'pointer' }}>Ver orden</button>
          </div>
        </div>
        <div className="dash-ai-msg">
          <div className="dash-ai-msg-label">Oportunidad 13:52</div>
          <p>El restaurante de Sur tiene <span className="hl">+18% de ventas los jueves.</span> Activo promo automatizada para replicar en otras sucursales.</p>
        </div>
      </div>
      <div className="dash-ai-input">
        <input type="text" placeholder="Pregunta al asistente..." style={{ width: '100%', padding: '12px 16px', borderRadius: 8, background: 'rgba(255,255,255,0.05)', border: '1px solid rgba(255,255,255,0.1)', color: '#fff', fontSize: 14 }} />
      </div>
    </div>
    <AIPopup />
  </div>
);

const ReportesView = () => (
  <div style={{ minHeight: 600 }}>
    <div className="dash-kpi-row">
      <KPI label="Ingresos mes" value="$1.2M" delta="+8.4%" />
      <KPI label="Crecimiento" value="+15%" delta="+3pts" />
      <KPI label="Pacientes nuevos" value={234} delta="+12%" />
      <KPI label="Satisfacción" value={4.7} delta="+0.2" />
    </div>
    <div className="dash-chart" style={{ height: 200 }}>
      <div className="dash-chart-head">
        <span className="t">Ingresos por servicio · 6 meses</span>
      </div>
      <div style={{ position: 'absolute', left: 14, right: 14, top: 36, bottom: 14 }}>
        <AreaChart />
      </div>
    </div>
    <div className="dash-table">
      <div className="dash-table-head">
        <span>Servicio</span>
        <span>Ingresos</span>
        <span>Citas</span>
        <span>Tendencia</span>
      </div>
      <div className="dash-table-body">
        {[
          { name: 'Consulta general', income: '$45,200', citas: 234, trend: '↑ +12%' },
          { name: 'Cardiología', income: '$38,100', citas: 156, trend: '↑ +8%' },
          { name: 'Dermatología', income: '$29,800', citas: 189, trend: '↑ +15%' },
          { name: 'Laboratorio', income: '$22,400', citas: 312, trend: '↓ -3%' },
          { name: 'Vacunación', income: '$18,600', citas: 445, trend: '↑ +22%' },
        ].map((s, i) => (
          <div key={i} className="dash-table-row">
            <span className="nm">{s.name}</span>
            <span className="ag">{s.income}</span>
            <span>{s.citas}</span>
            <span className={`st ${s.trend.includes('-') ? 'warn' : ''}`}>{s.trend}</span>
          </div>
        ))}
      </div>
    </div>
    <AIPopup />
  </div>
);

const AlertasView = () => (
  <div style={{ minHeight: 600 }}>
    <div className="dash-kpi-row">
      <KPI label="Alertas activas" value={3} delta="−2" />
      <KPI label="Críticas" value={1} delta="0" />
      <KPI label="Resueltas hoy" value={7} delta="+3" />
      <KPI label="Tiempo respuesta" value="2.1h" delta="−0.5h" />
    </div>
    <div className="dash-rows">
      {[
        { type: 'critical', title: 'Stock crítico - Alcohol etílico', desc: '8 unidades restantes. Umbral mínimo: 20', time: 'Hace 5 min' },
        { type: 'warning', title: 'No-show elevado - Dr. Méndez', desc: '18% no-show vs promedio 12%. Revisar recordatorios', time: 'Hace 23 min' },
        { type: 'info', title: 'Nueva integración - HubSpot', desc: 'Sincronización completada exitosamente', time: 'Hace 1h' },
      ].map((a, i) => (
        <div key={i} className={`dash-row ${a.type === 'critical' ? 'dash-row-critical' : a.type === 'warning' ? 'dash-row-warning' : ''}`}>
          <span className={`av ${a.type === 'critical' ? 'critical' : a.type === 'warning' ? 'warning' : 'info'}`}>
            <window.MartzIcon name={a.type === 'critical' ? 'alert' : a.type === 'warning' ? 'warning' : 'info'} size={17} strokeWidth={2} />
          </span>
          <div>
            <div className="nm">{a.title}</div>
            <div className="ag" style={{ fontSize: 12, opacity: 0.7 }}>{a.desc}</div>
          </div>
          <span className="ag">{a.time}</span>
          <span className="st">Ver</span>
        </div>
      ))}
    </div>
    <AIPopup />
  </div>
);

const AjustesView = () => (
  <div style={{ minHeight: 600 }}>
    <div className="dash-settings">
      <div className="dash-settings-section">
        <h4>General</h4>
        <div className="dash-setting">
          <label>Nombre de la clínica</label>
          <input type="text" defaultValue="Clínica Noria" style={{ padding: '8px 12px', borderRadius: 6, background: 'rgba(255,255,255,0.05)', border: '1px solid rgba(255,255,255,0.1)', color: '#fff', fontSize: 14 }} />
        </div>
        <div className="dash-setting">
          <label>Zona horaria</label>
          <select style={{ padding: '8px 12px', borderRadius: 6, background: 'rgba(255,255,255,0.05)', border: '1px solid rgba(255,255,255,0.1)', color: '#fff', fontSize: 14 }}>
            <option>America/Mexico_City</option>
            <option>America/Los_Angeles</option>
            <option>America/New_York</option>
          </select>
        </div>
      </div>
      <div className="dash-settings-section">
        <h4>Notificaciones</h4>
        <div className="dash-setting">
          <label>Recordatorios de citas</label>
          <div style={{ display: 'flex', gap: 8 }}>
            <button style={{ padding: '6px 12px', borderRadius: 6, background: '#22c55e', border: 'none', color: '#0b0f19', fontSize: 12, fontWeight: 600 }}>Activado</button>
          </div>
        </div>
        <div className="dash-setting">
          <label>Alertas de stock bajo</label>
          <div style={{ display: 'flex', gap: 8 }}>
            <button style={{ padding: '6px 12px', borderRadius: 6, background: '#22c55e', border: 'none', color: '#0b0f19', fontSize: 12, fontWeight: 600 }}>Activado</button>
          </div>
        </div>
        <div className="dash-setting">
          <label>Reportes diarios</label>
          <div style={{ display: 'flex', gap: 8 }}>
            <button style={{ padding: '6px 12px', borderRadius: 6, background: 'rgba(255,255,255,0.1)', border: 'none', color: '#fff', fontSize: 12 }}>Desactivado</button>
          </div>
        </div>
      </div>
      <div className="dash-settings-section">
        <h4>Integraciones</h4>
        <div className="dash-setting">
          <label>HubSpot</label>
          <span className="dash-setting-status" style={{ color: '#22c55e', fontSize: 12 }}>● Conectado</span>
        </div>
        <div className="dash-setting">
          <label>Stripe</label>
          <span className="dash-setting-status" style={{ color: '#22c55e', fontSize: 12 }}>● Conectado</span>
        </div>
        <div className="dash-setting">
          <label>WhatsApp Business</label>
          <button style={{ padding: '6px 12px', borderRadius: 6, background: 'rgba(34,197,94,0.1)', border: '1px solid #22c55e', color: '#22c55e', fontSize: 12, cursor: 'pointer' }}>Conectar</button>
        </div>
      </div>
    </div>
    <AIPopup />
  </div>
);

const Dashboard = () => {
  const [activeView, setActiveView] = React.useState('resumen');

  const views = {
    resumen: { title: 'Resumen de hoy', component: ResumenView },
    pacientes: { title: 'Pacientes', component: PacientesView },
    citas: { title: 'Citas', component: CitasView },
    inventario: { title: 'Inventario', component: InventarioView },
    asistente: { title: 'Asistente IA', component: AsistenteView },
    reportes: { title: 'Reportes', component: ReportesView },
    alertas: { title: 'Alertas', component: AlertasView },
    ajustes: { title: 'Ajustes', component: AjustesView },
  };

  const currentView = views[activeView];

  return (
    <div className="dash-wrap">
      <div className="dash-bar">
        <span className="dash-dot r" />
        <span className="dash-dot y" />
        <span className="dash-dot g" />
        <span className="dash-url">app.martzlab.com/clinica-noria</span>
      </div>
      <div className="dash-body">
        <aside className="dash-side">
          <div className="dash-logo-row">
            <div className="dash-logo-mark">M</div>
            <div className="dash-logo-name">Clínica Noria</div>
          </div>
          <div className="dash-section-label">Operación</div>
          <div className={`dash-nav-item ${activeView === 'resumen' ? 'active' : ''}`} onClick={() => setActiveView('resumen')} style={{ cursor: 'pointer' }}><Icon name="home" /> Resumen</div>
          <div className={`dash-nav-item ${activeView === 'pacientes' ? 'active' : ''}`} onClick={() => setActiveView('pacientes')} style={{ cursor: 'pointer' }}><Icon name="users" /> Pacientes</div>
          <div className={`dash-nav-item ${activeView === 'citas' ? 'active' : ''}`} onClick={() => setActiveView('citas')} style={{ cursor: 'pointer' }}><Icon name="activity" /> Citas</div>
          <div className={`dash-nav-item ${activeView === 'inventario' ? 'active' : ''}`} onClick={() => setActiveView('inventario')} style={{ cursor: 'pointer' }}><Icon name="box" /> Inventario</div>
          <div className="dash-section-label">Inteligencia</div>
          <div className={`dash-nav-item ${activeView === 'asistente' ? 'active' : ''}`} onClick={() => setActiveView('asistente')} style={{ cursor: 'pointer' }}><Icon name="sparkles" /> Asistente IA</div>
          <div className={`dash-nav-item ${activeView === 'reportes' ? 'active' : ''}`} onClick={() => setActiveView('reportes')} style={{ cursor: 'pointer' }}><Icon name="chart" /> Reportes</div>
          <div className={`dash-nav-item ${activeView === 'alertas' ? 'active' : ''}`} onClick={() => setActiveView('alertas')} style={{ cursor: 'pointer' }}><Icon name="bell" /> Alertas <span style={{ marginLeft:'auto', background:'#22c55e', color:'#0b0f19', fontSize:10, padding:'1px 6px', borderRadius:6, fontWeight:600 }}>3</span></div>
          <div className={`dash-nav-item ${activeView === 'ajustes' ? 'active' : ''}`} onClick={() => setActiveView('ajustes')} style={{ cursor: 'pointer' }}><Icon name="settings" /> Ajustes</div>
        </aside>
        <main className="dash-main">
          <div className="dash-head">
            <h3>{currentView.title}</h3>
            <div className="dash-head-meta">Martes · 29 abr · 14:32</div>
          </div>
          <currentView.component />
        </main>
      </div>
    </div>
  );
};

window.Dashboard = Dashboard;
window.Counter = Counter;
window.Icon = Icon;
