/* Dashboard — Hexis-driven KPIs · Charts · Micro-Apps · Games · E-Wallet */
const { useState: useStateD, useEffect: useEffectD, useRef: useRefD, useMemo: useMemoD } = React;

/* ── LINE CHART ─────────────────────────────────────────────── */
const LineChart = ({ series, labels, height = 320, formatY = v => v }) => {
  const [tip, setTip] = useStateD(null);
  const [muted, setMuted] = useStateD({});
  const W = 800, H = height, padL = 44, padR = 12, padT = 10, padB = 28;
  const innerW = W - padL - padR, innerH = H - padT - padB;
  const allV = series.flatMap(s => muted[s.id] ? [] : s.data);
  const max = Math.max(...allV, 1), min = 0;
  const xFor = i => padL + (i / (labels.length - 1)) * innerW;
  const yFor = v => padT + innerH - ((v - min) / (max - min)) * innerH;
  const yTicks = [0, 0.25, 0.5, 0.75, 1].map(t => min + (max - min) * t);
  const onMove = (e) => {
    const rect = e.currentTarget.getBoundingClientRect();
    const x = ((e.clientX - rect.left) / rect.width) * W;
    const i = Math.round(((x - padL) / innerW) * (labels.length - 1));
    if (i < 0 || i >= labels.length) { setTip(null); return; }
    setTip({ i, x: padL + (i / (labels.length - 1)) * innerW });
  };
  return (
    <div className="chart-wrap" onMouseLeave={() => setTip(null)}>
      <svg className="chart-svg" viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="none" onMouseMove={onMove}>
        <defs>{series.map(s => (
          <linearGradient key={s.id} id={`grad-${s.id}`} x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor={s.color} stopOpacity="0.35" />
            <stop offset="100%" stopColor={s.color} stopOpacity="0" />
          </linearGradient>
        ))}</defs>
        <g className="chart-grid">{yTicks.map((t, i) => <line key={i} x1={padL} x2={W - padR} y1={yFor(t)} y2={yFor(t)} />)}</g>
        <g className="chart-axis">
          {yTicks.map((t, i) => <text key={i} x={padL - 8} y={yFor(t) + 3} textAnchor="end">{formatY(Math.round(t))}</text>)}
          {labels.map((l, i) => <text key={i} x={xFor(i)} y={H - 8} textAnchor="middle">{l}</text>)}
        </g>
        {series.map(s => {
          if (muted[s.id]) return null;
          const pts = s.data.map((d, i) => `${xFor(i)},${yFor(d)}`).join(' ');
          const area = `M ${xFor(0)},${yFor(0)} L ${pts.split(' ').join(' L ')} L ${xFor(s.data.length - 1)},${yFor(0)} Z`;
          return (
            <g key={s.id}>
              <path d={area} fill={`url(#grad-${s.id})`} />
              <polyline className="chart-line" points={pts} stroke={s.color} />
              {tip && <circle className="chart-dot" cx={xFor(tip.i)} cy={yFor(s.data[tip.i])} r="4" stroke={s.color} strokeWidth="2" />}
            </g>
          );
        })}
        {tip && <line x1={tip.x} x2={tip.x} y1={padT} y2={H - padB} stroke="rgba(123,97,255,0.4)" strokeDasharray="3 3" />}
      </svg>
      {tip && (
        <div className="chart-tooltip visible" style={{ left: `${(tip.x / W) * 100}%`, top: 0 }}>
          <div className="tip-title">{labels[tip.i]}</div>
          {series.filter(s => !muted[s.id]).map(s => (
            <div className="tip-row" key={s.id}>
              <span className="swatch" style={{ background: s.color }} />
              <span style={{ color: 'var(--text-2)', marginRight: 8 }}>{s.label}</span>
              <span className="v">{formatY(s.data[tip.i])}</span>
            </div>
          ))}
        </div>
      )}
      <div className="legend">
        {series.map(s => (
          <span key={s.id} className={`legend-item ${muted[s.id] ? 'muted' : ''}`}
            onClick={() => { SoundFX.tap(); setMuted(m => ({ ...m, [s.id]: !m[s.id] })); }}>
            <span className="swatch" style={{ background: s.color }} />{s.label}
          </span>
        ))}
      </div>
    </div>
  );
};

/* ── DONUT CHART ────────────────────────────────────────────── */
const DonutChart = ({ data, total }) => {
  const R = 70, C = Math.PI * 2 * R;
  let acc = 0;
  return (
    <div>
      <div className="donut-wrap">
        <svg viewBox="0 0 200 200" style={{ width: '100%', height: '100%', transform: 'rotate(-90deg)' }}>
          <circle cx="100" cy="100" r={R} fill="none" stroke="rgba(255,255,255,0.06)" strokeWidth="24" />
          {data.map((d, i) => {
            const frac = d.value / total, dash = frac * C, off = -acc;
            acc += dash;
            return <circle key={i} className="donut-arc" cx="100" cy="100" r={R} stroke={d.color} strokeWidth="24" strokeDasharray={`${dash} ${C - dash}`} strokeDashoffset={off} fill="none" />;
          })}
        </svg>
        <div className="donut-center"><div className="v">{total}</div><div className="l">conexões</div></div>
      </div>
      <div className="donut-list">
        {data.map((d, i) => (
          <div className="donut-row" key={i}>
            <span className="swatch" style={{ background: d.color }} />
            <span className="name">{d.name}</span>
            <span className="v">{d.value}</span>
          </div>
        ))}
      </div>
    </div>
  );
};

/* ── KPI CARD ───────────────────────────────────────────────── */
const KPI = ({ lab, v, delta, deltaDir = 'up', icon, spark, sparkColor = '#A78BFA', label, onClick }) => (
  <div className="kpi" style={{ cursor: onClick ? 'pointer' : 'default' }} onClick={onClick}>
    <div className="kpi-head">
      <span className="lab">{lab}</span>
      <div className="ic-wrap"><Icon name={icon} size={14} /></div>
    </div>
    <div className="v">{v} {delta && <span className={`delta ${deltaDir === 'down' ? 'down' : ''}`}>{deltaDir === 'down' ? '−' : '+'}{delta}</span>}</div>
    <div className="l">{label}</div>
    <div className="kpi-spark"><Sparkline data={spark} color={sparkColor} /></div>
  </div>
);

/* ── MICRO APPS DATA ────────────────────────────────────────── */
const MICRO_APPS_DATA = [
  { id: 'DB', layer: 'green', name: 'Central Database',      sub: 'PostgreSQL + pgvector',  stat: '38K',    meta: 'Perfis indexados',      fill: 88 },
  { id: 'CP', layer: 'green', name: 'Cadastro Participantes', sub: 'LinkedIn OAuth · <30s', stat: '2,840',  meta: 'Leads capturados',      fill: 74 },
  { id: 'SK', layer: 'green', name: 'Stakeholders B2B',      sub: 'Validação por Hexis AI', stat: '38',     meta: 'Decisores ativos',      fill: 62 },
  { id: 'BI', layer: 'green', name: 'Briefing Inteligente',  sub: 'Diagnóstico Condicional', stat: '14',    meta: 'Briefings em curso',    fill: 55 },
  { id: 'CI', layer: 'blue',  name: 'Check-in & Agenda',     sub: 'QR Code · NFC · BLE',   stat: '1,247',  meta: 'Check-ins hoje',        fill: 91 },
  { id: 'SF', layer: 'blue',  name: 'Smart Forms & NPS',     sub: 'Adaptive Logic',         stat: '94%',    meta: 'NPS score atual',       fill: 94 },
  { id: 'QG', layer: 'blue',  name: 'Quizzes & Gamification',sub: 'Knowledge Arena™',       stat: '320',    meta: 'Participantes ativos',  fill: 67 },
  { id: 'NO', layer: 'blue',  name: 'Notificações Omnicanal',sub: 'WhatsApp · Push · SMS',  stat: '3 New',  meta: 'Nudges pendentes',      fill: 48 },
  { id: 'MQ', layer: 'purple',name: 'Matchmaking Engine',    sub: 'Match Quest™ · pgvector',stat: '94%',    meta: 'Match Score médio',     fill: 94 },
  { id: 'AR', layer: 'purple',name: 'Analytics & Relatórios',sub: 'D3-BMC · Real-time',     stat: '€1.82M', meta: 'Pipeline calculado',    fill: 82 },
  { id: 'RM', layer: 'purple',name: 'Gestão de Recursos',    sub: 'YOLO v8 · Ocupação',     stat: '78%',    meta: 'Capacidade utilizada',  fill: 78 },
  { id: 'SN', layer: 'purple',name: 'Smart Notes AI',        sub: 'Auto-classificação Hexis',stat: '14',    meta: 'Notas geradas hoje',    fill: 70 },
];
const LAYER_META = {
  green:  { label: '🟢 Camada Core — Capture Nodes',              desc: 'Ingestão e captura de dados comportamentais', color: '#00C48C', cls: 'sn' },
  blue:   { label: '🔵 Camada Operacional — Execution Nodes',      desc: 'Ação física e controlo de fluxo',             color: '#00D1FF', cls: '' },
  purple: { label: '🟣 Camada Inteligência — Decision Interfaces', desc: 'Motor de decisão e insight preditivo',        color: '#7B61FF', cls: 'np' },
};

const MicroAppsLayered = ({ onOpen }) => (
  <div style={{ display: 'flex', flexDirection: 'column', gap: 28 }}>
    {['green', 'blue', 'purple'].map(lid => {
      const lm = LAYER_META[lid];
      return (
        <div key={lid}>
          <div style={{ marginBottom: 14 }}>
            <div style={{ fontSize: 13, fontWeight: 700, color: lm.color, letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: 4 }}>{lm.label}</div>
            <div style={{ fontSize: 12, color: 'var(--text-3)' }}>{lm.desc}</div>
          </div>
          <div className="microapps-grid">
            {MICRO_APPS_DATA.filter(a => a.layer === lid).map(a => (
              <div key={a.id} className={`microapp ${lm.cls}`} onClick={() => { SoundFX.tap(); if (window.HexisEngine) HexisEngine.trackClick(`microapp_${a.id}`); onOpen(a); }}>
                <div className="ma-head">
                  <div className="ma-tag">{a.id}</div>
                  <div><div className="ma-name">{a.name}</div><div className="ma-sub">{a.sub}</div></div>
                </div>
                <div className="ma-body">
                  <div className="ma-stat">{a.stat}</div>
                  <div className="ma-meta">{a.meta}</div>
                  <div className="xp-bar"><div className={`xp-fill ${lid === 'green' ? 'success' : lid === 'purple' ? 'gold' : ''}`} style={{ width: `${a.fill}%` }} /></div>
                </div>
                <div className="pulse-dot" />
              </div>
            ))}
          </div>
        </div>
      );
    })}
  </div>
);

/* ── GAMIFICATION PANEL ─────────────────────────────────────── */
const GamificationPanel = ({ profile }) => {
  const lp = window.HexisEngine ? HexisEngine.getLevelProgress() : { level: 7, tier: 'diamond', xp: 2340, pct: 68, xpToNext: 320 };
  const achievements = [
    { ic: 'crown',  nm: 'Match Master',   pts: '+250', earned: profile?.badges?.includes('Match Master') },
    { ic: 'flame',  nm: 'Streak 7d',      pts: '+120', earned: profile?.badges?.includes('Streak 7d') },
    { ic: 'trophy', nm: 'Top Connector',  pts: '+500', earned: profile?.badges?.includes('Top Connector') },
    { ic: 'medal',  nm: 'Premium Match',  pts: '+180', earned: profile?.badges?.includes('Premium Match') },
    { ic: 'lock',   nm: 'Closer Tier',    pts: '+1000', locked: true },
  ];
  return (
    <div className="gam-panel">
      <svg width="0" height="0" style={{ position: 'absolute' }}>
        <defs>
          <linearGradient id="goldgrad" x1="0%" y1="0%" x2="100%" y2="100%">
            <stop offset="0%" stopColor="#FFD700" />
            <stop offset="100%" stopColor="#F5C518" />
          </linearGradient>
        </defs>
      </svg>
      <div className="gam-row">
        <div className="gam-level">
          <div className="gam-rank-ring">
            <svg viewBox="0 0 88 88">
              <circle className="ring-track" cx="44" cy="44" r="38" />
              <circle className="ring-fill" cx="44" cy="44" r="38" strokeDasharray={`${(lp.pct / 100) * (Math.PI * 2 * 38)} ${Math.PI * 2 * 38}`} />
            </svg>
            <div className="center"><div className="v">L{lp.level}</div><div className="l">{lp.tier}</div></div>
          </div>
          <div className="gam-rank-info">
            <div className="tier">Operativo · Tier {lp.tier?.toUpperCase()}</div>
            <h3>{profile?.name || 'Carolina Sá'}</h3>
            <div className="next">{lp.xpToNext} XP até Level {lp.level + 1} · {lp.nextTier}</div>
          </div>
        </div>
        <div className="gam-stat">
          <div className="v gold">{(profile?.xp || 2340).toLocaleString()}</div>
          <div className="l">XP Acumulado</div>
        </div>
        <div className="gam-stat">
          <div className="v">{profile?.streak || 7}d <span style={{ fontSize: 12, color: 'var(--warning)' }}>🔥</span></div>
          <div className="l">Streak Atual</div>
        </div>
      </div>
      <div className="achievements">
        {achievements.map((a, i) => (
          <div key={i} className={`ach ${a.locked ? 'locked' : ''}`}
            onClick={() => { if (!a.locked && window.HexisEngine) { SoundFX.tap(); HexisEngine.awardXP(5, `Badge: ${a.nm}`); } }}>
            <div className="ic"><Icon name={a.ic} size={14} /></div>
            <span className="nm">{a.nm}</span>
            <span className="pts">{a.pts}</span>
          </div>
        ))}
      </div>
    </div>
  );
};

/* ── KNOWLEDGE ARENA™ — Interactive Quiz ───────────────────── */
const KnowledgeArenaPanel = () => {
  const [cur, setCur] = useStateD(0);
  const [answered, setAnswered] = useStateD(null);
  const [score, setScore] = useStateD(0);
  const [done, setDone] = useStateD(false);

  const QUIZ = [
    { q: 'Qual a percentagem de pipeline atribuível a eventos B2B vs. cold outreach na Marcianus?', opts: ['12%', '34%', '54%', '78%'], correct: 2, xp: 40, explain: 'Eventos B2B geram 3.4× mais pipeline que cold outreach (Marcianus Data, 2025).' },
    { q: 'O Hexis AI usa qual modelo de embeddings como camada base (always-on)?', opts: ['GPT-4 Embeddings', 'nomic-embed-text · 274MB', 'Claude Haiku', 'BERT-large'], correct: 1, xp: 50, explain: 'nomic-embed-text (274MB) é always-on. Mistral 4.5GB é o modelo principal on-demand.' },
    { q: 'Qual o limiar de MIS para injeção automática no CRM (Hot Lead via Tap 3)?', opts: ['MIS > 0.65', 'MIS > 0.75', 'MIS > 0.85', 'MIS > 0.95'], correct: 2, xp: 60, explain: 'Tap3 = Hot Lead. MIS > 0.85 → CRM injection automática via EventOS Kafka.' },
    { q: 'Na fórmula DecisionScore, qual variável tem o maior peso (0.30)?', opts: ['Context', 'Behavioral Gain', 'Relevance', 'Timing'], correct: 2, xp: 50, explain: 'Relevance tem peso 0.30 — é o factor dominante na decisão do Hexis AI.' },
  ];

  const q = QUIZ[cur];
  const handle = (i) => {
    if (answered !== null) return;
    setAnswered(i);
    if (i === q.correct) {
      setScore(s => s + q.xp);
      SoundFX.success();
      if (window.HexisEngine) HexisEngine.awardXP(q.xp, 'Knowledge Arena™');
      ToastBus.push({ kind: 'gold', icon: 'zap', title: `+${q.xp} XP · Correto!`, desc: q.explain, duration: 4000 });
    } else {
      SoundFX.tap();
      ToastBus.push({ icon: 'x', title: 'Incorreto', desc: q.explain, duration: 4000 });
    }
  };
  const next = () => { if (cur + 1 < QUIZ.length) { setCur(c => c + 1); setAnswered(null); } else { setDone(true); if (window.HexisEngine) HexisEngine.completeMission('ka_001', score >= 2 ? true : false); } };
  const reset = () => { setCur(0); setAnswered(null); setScore(0); setDone(false); };

  if (done) return (
    <div className="chart-card" style={{ padding: 40, textAlign: 'center' }}>
      <div style={{ fontSize: 56, marginBottom: 16 }}>🏆</div>
      <span className="eyebrow" style={{ justifyContent: 'center' }}>Knowledge Arena™ · Resultado Final</span>
      <h2 style={{ marginBottom: 8 }}>Quiz Completo</h2>
      <div style={{ fontSize: 40, fontWeight: 900, color: '#FFD700', marginBottom: 8 }}>+{score} XP</div>
      <div style={{ color: 'var(--text-2)', marginBottom: 20, fontSize: 16 }}>{score >= 150 ? 'Pontuação máxima — Insight Leader desbloqueado!' : `${Math.round((score / 200) * 100)}% de precisão`}</div>
      <button className="btn btn-primary btn-lg" onClick={reset}>Jogar novamente</button>
    </div>
  );

  return (
    <div className="chart-card" style={{ padding: 28 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 20 }}>
        <div><span className="eyebrow">Knowledge Arena™</span><h3 style={{ marginBottom: 0 }}>Fintech & B2B Intelligence · Quiz</h3></div>
        <div style={{ textAlign: 'right', flexShrink: 0 }}>
          <div style={{ fontSize: 24, fontWeight: 900, color: '#FFD700' }}>+{score} XP</div>
          <div style={{ fontSize: 12, color: 'var(--text-3)' }}>{cur + 1} / {QUIZ.length}</div>
        </div>
      </div>
      <div style={{ height: 4, background: 'rgba(255,255,255,0.06)', borderRadius: 2, marginBottom: 24 }}>
        <div style={{ height: '100%', width: `${(cur / QUIZ.length) * 100}%`, background: '#FFD700', borderRadius: 2, transition: 'width 0.4s ease' }} />
      </div>
      <div style={{ fontSize: 16, fontWeight: 600, color: '#fff', lineHeight: 1.65, marginBottom: 20 }}>{q.q}</div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        {q.opts.map((opt, i) => {
          let bg = 'rgba(255,255,255,0.04)', border = 'var(--border-1)', col = 'var(--text-1)';
          if (answered !== null) {
            if (i === q.correct) { bg = 'rgba(0,196,140,0.14)'; border = '#00C48C80'; col = '#00C48C'; }
            else if (i === answered) { bg = 'rgba(255,59,92,0.10)'; border = '#FF3B5C80'; col = '#FF3B5C'; }
          }
          return (
            <button key={i} onClick={() => handle(i)}
              style={{ textAlign: 'left', padding: '13px 16px', borderRadius: 10, background: bg, border: `1px solid ${border}`, color: col, fontSize: 14, cursor: answered !== null ? 'default' : 'pointer', transition: 'all 0.2s', fontFamily: 'var(--font-body)', lineHeight: 1.4 }}>
              <span style={{ fontWeight: 700, color: 'var(--text-3)', marginRight: 8 }}>{String.fromCharCode(65 + i)}.</span>{opt}
            </button>
          );
        })}
      </div>
      {answered !== null && (
        <div style={{ marginTop: 16, display: 'flex', justifyContent: 'flex-end' }}>
          <button className="btn btn-primary" onClick={next}>{cur + 1 < QUIZ.length ? 'Próxima →' : 'Ver resultado'}</button>
        </div>
      )}
    </div>
  );
};

/* ── NETWORK DOMINATION™ ────────────────────────────────────── */
const NetworkDominationPanel = ({ profile }) => {
  const LEADERS = [
    { rank: 1, ini: 'MT', nm: 'Miguel Tavares',  co: 'Veridian VC',    score: 2840, delta: '+240', badge: 'Top Connector' },
    { rank: 2, ini: 'CS', nm: profile?.name?.split(' ').slice(0,2).join(' ') || 'Carolina Sá', co: profile?.company || 'Veridian VC', score: profile?.xp || 2340, delta: '+120', badge: 'Deal Maker', isMe: true },
    { rank: 3, ini: 'AC', nm: 'Ana Cardoso',      co: 'Solaris Energy', score: 1980, delta: '+80',  badge: 'Insight Leader' },
    { rank: 4, ini: 'RS', nm: 'Rita Sousa',        co: 'Banco Invicta', score: 1720, delta: '+60' },
    { rank: 5, ini: 'JR', nm: 'João Reis',         co: 'Helix Bio',     score: 1540, delta: '+45' },
    { rank: 6, ini: 'PM', nm: 'Pedro Machado',     co: 'Aether RE',     score: 1380, delta: '+30' },
  ].sort((a, b) => b.score - a.score).map((l, i) => ({ ...l, rank: i + 1 }));
  const medals = ['🥇', '🥈', '🥉'];
  return (
    <div className="chart-card" style={{ padding: 24 }}>
      <div className="chart-head" style={{ marginBottom: 20 }}>
        <div className="chart-title"><span className="eyebrow">Network Domination™</span><h3 style={{ marginBottom: 0 }}>Leaderboard · Veridian Tech Summit</h3></div>
        <span className="chip chip-success">Live</span>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {LEADERS.map(l => (
          <div key={l.rank} style={{ display: 'grid', gridTemplateColumns: '28px 40px 1fr auto', gap: 12, alignItems: 'center', padding: '10px 14px', borderRadius: 10, background: l.isMe ? 'rgba(123,97,255,0.12)' : 'rgba(255,255,255,0.03)', border: `1px solid ${l.isMe ? 'rgba(123,97,255,0.4)' : 'var(--border-1)'}` }}
            onClick={() => { SoundFX.tap(); ToastBus.push({ icon: 'users', title: l.nm, desc: `${l.co} · ${l.score.toLocaleString()} XP` }); }}>
            <div style={{ fontSize: 15, textAlign: 'center' }}>{medals[l.rank - 1] || l.rank}</div>
            <div className="team-av" style={{ width: 36, height: 36, fontSize: 12, background: l.isMe ? 'linear-gradient(135deg,#5D3FD3,#7B61FF)' : undefined }}>{l.ini}</div>
            <div>
              <div style={{ fontWeight: 700, fontSize: 14, color: l.isMe ? 'var(--purple-soft)' : '#fff' }}>{l.nm} {l.isMe && <span style={{ fontSize: 10, color: 'var(--text-3)' }}>(você)</span>}</div>
              <div style={{ fontSize: 12, color: 'var(--text-3)' }}>{l.co}{l.badge && <span className="chip chip-gold" style={{ fontSize: 10, padding: '1px 6px', marginLeft: 6 }}>{l.badge}</span>}</div>
            </div>
            <div style={{ textAlign: 'right' }}>
              <div style={{ fontWeight: 800, fontSize: 16, color: l.rank <= 3 ? '#FFD700' : '#fff' }}>{l.score.toLocaleString()}</div>
              <div style={{ fontSize: 11, color: '#00C48C' }}>{l.delta} XP</div>
            </div>
          </div>
        ))}
      </div>
      <div style={{ marginTop: 16, display: 'flex', gap: 10, justifyContent: 'center' }}>
        <button className="btn btn-primary btn-sm" onClick={() => { SoundFX.success(); if (window.HexisEngine) HexisEngine.awardXP(50, 'Network Domination™ · Desafio'); ToastBus.push({ kind: 'gold', icon: 'trophy', title: '+50 XP · Desafio aceite!', desc: 'Aceita 2 missões de networking para subir.' }); }}>
          Desafiar #1 · +50 XP
        </button>
        <button className="btn btn-ghost btn-sm" onClick={() => { SoundFX.tap(); ToastBus.push({ icon: 'share', title: 'Leaderboard partilhado', desc: 'Link copiado para a área de transferência.' }); }}>
          Partilhar ranking
        </button>
      </div>
    </div>
  );
};

/* ── MISSION ENGINE™ ────────────────────────────────────────── */
const MissionEnginePanel = () => {
  const [active, setActive] = useStateD(null);
  const missions = window.HexisEngine ? HexisEngine.getActiveMissions() : [];

  const accept = (m) => {
    SoundFX.success();
    if (window.HexisEngine) {
      HexisEngine.acceptMission(m.id);
      setTimeout(() => HexisEngine.completeMission(m.id, true), m.timeLimit * 1000 * 0.1);
    }
  };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
      {missions.length === 0 && (
        <div className="chart-card" style={{ padding: 32, textAlign: 'center' }}>
          <div style={{ fontSize: 32, marginBottom: 12 }}>✓</div>
          <div style={{ color: 'var(--text-2)' }}>Todas as missões foram completadas! Hexis lança novas em breve.</div>
        </div>
      )}
      {missions.map(m => {
        const pct = Math.round((m.elapsed / m.timeLimit) * 100);
        const isActive = m.status === 'active';
        return (
          <div key={m.id} className="chart-card" style={{ padding: '16px 18px', cursor: 'pointer', border: `1px solid ${m.color}40`, background: m.color + '06' }}
            onClick={() => { SoundFX.tap(); setActive(active === m.id ? null : m.id); }}>
            <div style={{ display: 'flex', gap: 14, alignItems: 'flex-start' }}>
              <div style={{ width: 38, height: 38, borderRadius: 10, background: m.color + '20', border: `1px solid ${m.color}40`, display: 'flex', alignItems: 'center', justifyContent: 'center', color: m.color, flexShrink: 0 }}>
                <Icon name={m.icon} size={17} />
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 3, flexWrap: 'wrap' }}>
                  <span style={{ fontSize: 10, fontWeight: 700, color: m.color, textTransform: 'uppercase', letterSpacing: '0.08em' }}>{m.game}</span>
                  <span className="chip chip-success" style={{ fontSize: 10, padding: '1px 7px' }}>Ativa · Hexis AI</span>
                </div>
                <div style={{ fontWeight: 700, fontSize: 14, color: '#fff', marginBottom: 3 }}>{m.title}</div>
                {active === m.id && <div style={{ fontSize: 13, color: 'var(--text-2)', lineHeight: 1.55, marginBottom: 10 }}>{m.desc}</div>}
                <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginTop: 10 }}>
                  <div style={{ flex: 1 }}>
                    <div style={{ height: 4, background: 'rgba(255,255,255,0.06)', borderRadius: 2, overflow: 'hidden' }}>
                      <div style={{ height: '100%', width: `${pct}%`, background: m.color, borderRadius: 2, transition: 'width 0.6s' }} />
                    </div>
                  </div>
                  <div style={{ fontWeight: 900, fontSize: 16, color: m.color, flexShrink: 0 }}>+{m.reward.xp} XP</div>
                  <button className="btn btn-sm" style={{ background: m.color + '20', border: `1px solid ${m.color}60`, color: m.color, flexShrink: 0 }}
                    onClick={(e) => { e.stopPropagation(); accept(m); }}>
                    Aceitar
                  </button>
                </div>
              </div>
            </div>
          </div>
        );
      })}
    </div>
  );
};

/* ── HEXIS CONSOLE ──────────────────────────────────────────── */
const HexisConsolePanel = ({ profile }) => {
  const [activeLayer, setActiveLayer] = useStateD(null);
  const [cpu, setCpu] = useStateD(42);
  const [lat, setLat] = useStateD(87);
  useEffectD(() => {
    const t = setInterval(() => {
      setCpu(c => Math.max(18, Math.min(88, c + (Math.random() * 8 - 4))));
      setLat(l => Math.max(35, Math.min(260, l + (Math.random() * 18 - 9))));
    }, 3500);
    return () => clearInterval(t);
  }, []);
  const cpuWarn = cpu > 80, latWarn = lat > 200;
  const mis = profile?.misScore?.toFixed(3) || '0.720';
  const ds = window.HexisEngine ? HexisEngine.getDecisionScore().toFixed(3) : '0.720';

  const PVA7 = [
    { id: 'L1', nm: 'Perfil Base',    desc: 'Dados estruturados · Cargo · Sector · Empresa', w: 35, color: '#7B61FF', ok: true },
    { id: 'L2', nm: 'Comportamento',  desc: 'MIS · Dwell · NFC Taps · Session Frequency',     w: 25, color: '#A78BFA', ok: true },
    { id: 'L3', nm: 'Grafo Social',   desc: 'Conexões · Graus de separação · Proximidade',    w: 15, color: '#00D1FF', ok: true },
    { id: 'L4', nm: 'Histórico',      desc: 'Eventos passados · Outcomes · Pipeline',         w: 10, color: '#00C48C', ok: true },
    { id: 'L5', nm: 'Contexto',       desc: 'Momento · Localização · Agenda · Spatial',       w:  8, color: '#FFD700', ok: true },
    { id: 'L6', nm: 'Semântica NLP',  desc: 'Intents · Tópicos · Sentimento · Keywords',      w:  4, color: '#FF7849', ok: true },
    { id: 'L7', nm: 'Web Fallback',   desc: 'Firecrawl · <10% uso · último recurso',          w:  3, color: '#FF3B5C', ok: false },
  ];
  const ROUTING = [
    { step: 1, nm: 'Redis Cache',            desc: 'Decisão cached — custo ~0',         time: '<2ms',   hit: true  },
    { step: 2, nm: 'Regras Determinísticas', desc: 'Rule engine hard-coded — sem LLM',  time: '~5ms',   hit: true  },
    { step: 3, nm: 'pgvector Cosine Sim.',   desc: 'Similaridade vetorial · nomic',     time: '~40ms',  hit: false },
    { step: 4, nm: 'Mistral 4.5GB',          desc: 'LLM principal · último recurso',    time: '~200ms', hit: false },
  ];

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12 }}>
        {[
          { lab: 'CPU',       v: `${Math.round(cpu)}%`,       warn: cpuWarn, note: cpuWarn ? 'AI desativada local' : 'Normal',   ic: 'cpu' },
          { lab: 'Latência',  v: `${Math.round(lat)}ms`,      warn: latWarn, note: latWarn ? 'Cache forçado' : 'Normal',         ic: 'zap' },
          { lab: 'MIS Score', v: mis,                          warn: false,   note: parseFloat(mis) > 0.85 ? 'Hot Lead' : 'Warm', ic: 'target' },
          { lab: 'Decision',  v: ds,                           warn: false,   note: 'DecisionScore atual',                        ic: 'sparkles' },
        ].map((m, i) => (
          <div key={i} style={{ padding: '14px 16px', borderRadius: 12, background: m.warn ? 'rgba(255,59,92,0.10)' : 'var(--surface-1)', border: `1px solid ${m.warn ? 'rgba(255,59,92,0.4)' : 'var(--border-1)'}` }}>
            <div style={{ fontSize: 10, color: 'var(--text-3)', marginBottom: 4, textTransform: 'uppercase', letterSpacing: '0.07em' }}>{m.lab}</div>
            <div style={{ fontSize: 20, fontWeight: 900, color: m.warn ? '#FF3B5C' : 'var(--purple-soft)', marginBottom: 2 }}>{m.v}</div>
            <div style={{ fontSize: 11, color: m.warn ? '#FF3B5C' : 'var(--text-3)' }}>{m.note}</div>
          </div>
        ))}
      </div>
      <div className="chart-card" style={{ padding: 24 }}>
        <div className="chart-head" style={{ marginBottom: 20 }}>
          <div className="chart-title"><span className="eyebrow">RAG · PVA-7</span><h3 style={{ marginBottom: 0 }}>Pipeline de Recuperação Aumentada</h3></div>
          <span className="chip chip-success">Online</span>
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {PVA7.map(l => (
            <div key={l.id} style={{ cursor: 'pointer', padding: '11px 14px', borderRadius: 10, background: activeLayer === l.id ? l.color + '10' : 'rgba(255,255,255,0.02)', border: `1px solid ${activeLayer === l.id ? l.color + '40' : 'var(--border-1)'}` }}
              onClick={() => { SoundFX.tap(); setActiveLayer(activeLayer === l.id ? null : l.id); }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                <div style={{ width: 32, height: 32, borderRadius: 8, background: l.color + '18', display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'var(--font-mono)', fontWeight: 800, fontSize: 10, color: l.color, flexShrink: 0 }}>{l.id}</div>
                <div style={{ flex: 1 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    <span style={{ fontWeight: 700, fontSize: 14, color: '#fff' }}>{l.nm}</span>
                    <span className={`chip ${l.ok ? 'chip-success' : 'chip-purple'}`} style={{ fontSize: 10, padding: '1px 6px' }}>{l.ok ? 'Ativo' : 'Standby'}</span>
                  </div>
                  {activeLayer === l.id && <div style={{ fontSize: 12, color: 'var(--text-3)', marginTop: 2 }}>{l.desc}</div>}
                </div>
                <div style={{ textAlign: 'right', flexShrink: 0 }}><div style={{ fontWeight: 800, fontSize: 16, color: l.color }}>{l.w}%</div></div>
              </div>
              <div style={{ marginTop: 8, height: 3, background: 'rgba(255,255,255,0.06)', borderRadius: 2 }}>
                <div style={{ height: '100%', width: `${l.w * 2.86}%`, background: l.color, borderRadius: 2 }} />
              </div>
            </div>
          ))}
        </div>
      </div>
      <div className="chart-card" style={{ padding: 24 }}>
        <div className="chart-head" style={{ marginBottom: 20 }}>
          <div className="chart-title"><span className="eyebrow">Cost-First Routing</span><h3 style={{ marginBottom: 0 }}>Hierarquia de Decisão</h3></div>
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {ROUTING.map((r, i) => (
            <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 14px', borderRadius: 10, background: r.hit ? 'rgba(0,196,140,0.08)' : 'rgba(255,255,255,0.02)', border: `1px solid ${r.hit ? 'rgba(0,196,140,0.3)' : 'var(--border-1)'}` }}>
              <div style={{ width: 26, height: 26, borderRadius: '50%', background: r.hit ? '#00C48C' : 'rgba(255,255,255,0.08)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 11, color: r.hit ? '#fff' : 'var(--text-3)', fontWeight: 700, flexShrink: 0 }}>{r.step}</div>
              <div style={{ flex: 1 }}><div style={{ fontWeight: 700, fontSize: 13, color: r.hit ? '#00C48C' : 'var(--text-2)' }}>{r.nm}</div><div style={{ fontSize: 12, color: 'var(--text-3)' }}>{r.desc}</div></div>
              <div style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: r.hit ? '#00C48C' : 'var(--text-3)', flexShrink: 0 }}>{r.time}</div>
              {r.hit && <span className="chip chip-success" style={{ fontSize: 10, padding: '2px 7px', flexShrink: 0 }}>HIT</span>}
            </div>
          ))}
        </div>
      </div>
      <div className="chart-card" style={{ padding: 24 }}>
        <span className="eyebrow">Hexis Decision Engine</span>
        <h3 style={{ marginBottom: 16 }}>Fórmulas de Pontuação</h3>
        <div style={{ padding: '16px 20px', borderRadius: 12, background: 'rgba(123,97,255,0.06)', border: '1px solid var(--border-purple)', fontFamily: 'var(--font-mono)', fontSize: 13, lineHeight: 2.1 }}>
          <div style={{ color: 'var(--purple-soft)', fontWeight: 700 }}>DecisionScore = <span style={{ color: '#fff' }}>{ds}</span></div>
          <div style={{ paddingLeft: 20, color: 'var(--text-2)' }}>
            <span style={{ color: '#7B61FF' }}>0.30</span> × Relevance + <span style={{ color: '#00D1FF' }}>0.20</span> × Context<br />
            + <span style={{ color: '#00C48C' }}>0.20</span> × Behavioral_Gain + <span style={{ color: '#FFD700' }}>0.15</span> × Graph_Proximity + <span style={{ color: '#FF7849' }}>0.15</span> × Timing
          </div>
        </div>
        <div style={{ marginTop: 12, padding: '14px 18px', borderRadius: 10, background: 'rgba(255,255,255,0.02)', border: '1px solid var(--border-1)', fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--text-3)', lineHeight: 1.9 }}>
          <div style={{ color: 'var(--purple-soft)', fontWeight: 700, marginBottom: 4 }}>MIS = <span style={{ color: '#fff' }}>{mis}</span></div>
          (Tap_Intensity × Tap_Weight) + Normalized_Dwell + Session_Freq + (Semantic × Recency)<br />
          <span style={{ color: '#00C48C' }}>{parseFloat(mis) > 0.85 ? '✓ Hot Lead — CRM Injection elegível via Tap 3' : parseFloat(mis) > 0.70 ? '⚠ Warm Lead — continua a aumentar engajamento' : '· Cold — aumenta tapCount e dwell time'}</span>
        </div>
      </div>
    </div>
  );
};

/* ── E-WALLET DASHBOARD PANEL ───────────────────────────────── */
const DashWallet = ({ profile }) => {
  const [walletTab, setWalletTab] = useStateD('overview');
  const [topupAmt, setTopupAmt] = useStateD('');
  const [sendAmt, setSendAmt] = useStateD('');
  const [sendTo, setSendTo] = useStateD('');
  const [sending, setSending] = useStateD(false);

  const balance = profile?.walletBalance ?? 2400;
  const txs = profile?.walletTransactions ?? [];

  const doTopup = (amt) => {
    const n = parseInt(amt, 10);
    if (!n || n <= 0) return;
    if (window.HexisEngine) HexisEngine.walletTopUp(n);
    setTopupAmt('');
    SoundFX.success();
    ToastBus.push({ kind: 'success', icon: 'credit-card', title: `+€${n} adicionados`, desc: 'Saldo atualizado na E-Wallet Marcianus.' });
  };

  const doSend = () => {
    const n = parseFloat(sendAmt);
    if (!n || n <= 0 || !sendTo) return;
    if (n > balance) { ToastBus.push({ icon: 'alert-circle', title: 'Saldo insuficiente', desc: `Disponível: €${balance.toLocaleString()}` }); return; }
    setSending(true);
    setTimeout(() => {
      if (window.HexisEngine) HexisEngine.walletSpend(`Transferência para ${sendTo}`, n);
      setSending(false); setSendAmt(''); setSendTo('');
      SoundFX.success();
      ToastBus.push({ kind: 'success', icon: 'send', title: `€${n} enviados`, desc: `Para ${sendTo} · processado em <5s` });
    }, 1200);
  };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
      {/* Balance card */}
      <div style={{ padding: 28, borderRadius: 20, background: 'linear-gradient(135deg, #1a1440, #2d1b6b)', border: '1px solid rgba(123,97,255,0.4)', position: 'relative', overflow: 'hidden' }}>
        <div style={{ position: 'absolute', top: -40, right: -40, width: 160, height: 160, borderRadius: '50%', background: 'rgba(123,97,255,0.15)', pointerEvents: 'none' }} />
        <div style={{ fontSize: 12, color: 'rgba(255,255,255,0.5)', letterSpacing: '0.12em', textTransform: 'uppercase', marginBottom: 8 }}>Saldo disponível · Marcianus E-Wallet</div>
        <div style={{ fontSize: 48, fontWeight: 900, color: '#fff', marginBottom: 4 }}>€{balance.toLocaleString('pt-PT')}</div>
        <div style={{ fontSize: 13, color: 'rgba(255,255,255,0.5)' }}>{profile?.name || 'Carolina Sá'} · {profile?.company || 'Veridian VC'}</div>
        <div style={{ display: 'flex', gap: 10, marginTop: 20, flexWrap: 'wrap' }}>
          {[
            { label: 'Enviar', icon: 'send', action: () => setWalletTab('send') },
            { label: 'Receber', icon: 'download', action: () => { SoundFX.tap(); ToastBus.push({ icon: 'qr-code', title: 'QR Code gerado', desc: 'Partilha para receber pagamentos.' }); } },
            { label: 'Recarregar', icon: 'plus', action: () => setWalletTab('topup') },
            { label: 'Histórico', icon: 'clock', action: () => setWalletTab('history') },
          ].map(a => (
            <button key={a.label} className="btn btn-ghost btn-sm" style={{ flex: 1 }} onClick={() => { SoundFX.tap(); a.action(); }}>
              <Icon name={a.icon} size={14} /> {a.label}
            </button>
          ))}
        </div>
      </div>

      {/* Stats */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12 }}>
        {[
          { lab: 'Cashback', v: `€${txs.filter(t => t.type === 'credit').reduce((a, t) => a + t.amount, 0).toLocaleString()}`, ic: 'zap', color: '#00C48C' },
          { lab: 'Volume 30d', v: `€${Math.abs(txs.slice(0,4).reduce((a, t) => a + t.amount, 0)).toLocaleString()}`, ic: 'chart-line', color: '#7B61FF' },
          { lab: 'Comissões', v: `€${txs.filter(t => t.label.includes('afiliado') || t.label.includes('Cashback')).reduce((a, t) => a + t.amount, 0).toLocaleString()}`, ic: 'share', color: '#FFD700' },
        ].map((s, i) => (
          <div key={i} style={{ padding: '14px 16px', borderRadius: 12, background: 'var(--surface-1)', border: '1px solid var(--border-1)' }}>
            <div style={{ fontSize: 10, color: 'var(--text-3)', marginBottom: 4, textTransform: 'uppercase' }}>{s.lab}</div>
            <div style={{ fontSize: 22, fontWeight: 900, color: s.color }}>{s.v}</div>
          </div>
        ))}
      </div>

      {/* Tabs */}
      <div style={{ display: 'flex', gap: 8, borderBottom: '1px solid var(--border-1)', paddingBottom: 0 }}>
        {[['overview', 'Visão geral'], ['history', 'Histórico'], ['topup', 'Recarregar'], ['send', 'Enviar']].map(([id, label]) => (
          <button key={id} onClick={() => { SoundFX.tap(); setWalletTab(id); }}
            style={{ padding: '8px 16px', background: 'none', border: 'none', cursor: 'pointer', fontSize: 13, fontWeight: 700, color: walletTab === id ? 'var(--purple-soft)' : 'var(--text-3)', borderBottom: walletTab === id ? '2px solid var(--purple-soft)' : '2px solid transparent', transition: 'all 0.2s' }}>
            {label}
          </button>
        ))}
      </div>

      {/* Tab content */}
      {walletTab === 'overview' && (
        <div className="chart-card" style={{ padding: 20 }}>
          <h4 style={{ marginBottom: 16 }}>Transações recentes</h4>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {txs.slice(0, 5).map(t => (
              <div key={t.id} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 14px', borderRadius: 10, background: 'rgba(255,255,255,0.02)', border: '1px solid var(--border-1)' }}>
                <div style={{ width: 36, height: 36, borderRadius: 9, background: t.type === 'credit' ? 'rgba(0,196,140,0.15)' : 'rgba(255,59,92,0.12)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: t.type === 'credit' ? '#00C48C' : '#FF3B5C', flexShrink: 0 }}>
                  <Icon name={t.icon || 'credit-card'} size={15} />
                </div>
                <div style={{ flex: 1 }}><div style={{ fontSize: 13, fontWeight: 600, color: '#fff' }}>{t.label}</div><div style={{ fontSize: 11, color: 'var(--text-3)' }}>{t.date}</div></div>
                <div style={{ fontWeight: 800, fontSize: 15, color: t.type === 'credit' ? '#00C48C' : '#FF3B5C' }}>{t.amount > 0 ? '+' : ''}€{Math.abs(t.amount).toLocaleString()}</div>
              </div>
            ))}
          </div>
        </div>
      )}

      {walletTab === 'history' && (
        <div className="chart-card" style={{ padding: 20 }}>
          <h4 style={{ marginBottom: 16 }}>Todas as transações</h4>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {txs.map(t => (
              <div key={t.id} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 14px', borderRadius: 10, background: 'rgba(255,255,255,0.02)', border: '1px solid var(--border-1)' }}>
                <div style={{ width: 32, height: 32, borderRadius: 8, background: t.type === 'credit' ? 'rgba(0,196,140,0.15)' : 'rgba(255,59,92,0.10)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: t.type === 'credit' ? '#00C48C' : '#FF3B5C', flexShrink: 0 }}>
                  <Icon name={t.icon || 'credit-card'} size={13} />
                </div>
                <div style={{ flex: 1 }}><div style={{ fontSize: 13, fontWeight: 600, color: '#fff' }}>{t.label}</div><div style={{ fontSize: 11, color: 'var(--text-3)' }}>{t.date}</div></div>
                <div style={{ fontWeight: 800, fontSize: 14, color: t.type === 'credit' ? '#00C48C' : '#FF3B5C' }}>{t.amount > 0 ? '+' : ''}€{Math.abs(t.amount).toLocaleString()}</div>
              </div>
            ))}
          </div>
        </div>
      )}

      {walletTab === 'topup' && (
        <div className="chart-card" style={{ padding: 24 }}>
          <h4 style={{ marginBottom: 4 }}>Recarregar E-Wallet</h4>
          <div style={{ color: 'var(--text-2)', fontSize: 13, marginBottom: 20 }}>Valores instantâneos. Sem taxas adicionais.</div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 10, marginBottom: 16 }}>
            {[100, 250, 500, 1000].map(v => (
              <button key={v} className="btn btn-ghost" onClick={() => doTopup(v)} style={{ fontWeight: 700 }}>€{v}</button>
            ))}
          </div>
          <div style={{ display: 'flex', gap: 10 }}>
            <input value={topupAmt} onChange={e => setTopupAmt(e.target.value.replace(/\D/g, ''))} placeholder="Outro valor (€)" style={{ flex: 1, padding: '12px 16px', borderRadius: 10, background: 'rgba(255,255,255,0.04)', border: '1px solid var(--border-1)', color: '#fff', fontSize: 14, fontFamily: 'var(--font-body)' }} />
            <button className="btn btn-primary" onClick={() => doTopup(topupAmt)} disabled={!topupAmt}>Confirmar</button>
          </div>
        </div>
      )}

      {walletTab === 'send' && (
        <div className="chart-card" style={{ padding: 24 }}>
          <h4 style={{ marginBottom: 4 }}>Enviar fundos</h4>
          <div style={{ color: 'var(--text-2)', fontSize: 13, marginBottom: 20 }}>Transferência interna P2P entre membros Marcianus.</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            <input value={sendTo} onChange={e => setSendTo(e.target.value)} placeholder="Email ou nome do destinatário" style={{ padding: '12px 16px', borderRadius: 10, background: 'rgba(255,255,255,0.04)', border: '1px solid var(--border-1)', color: '#fff', fontSize: 14, fontFamily: 'var(--font-body)' }} />
            <input value={sendAmt} onChange={e => setSendAmt(e.target.value.replace(/[^\d.]/g, ''))} placeholder={`Valor (disponível: €${balance.toLocaleString()})`} style={{ padding: '12px 16px', borderRadius: 10, background: 'rgba(255,255,255,0.04)', border: '1px solid var(--border-1)', color: '#fff', fontSize: 14, fontFamily: 'var(--font-body)' }} />
            <button className="btn btn-primary" onClick={doSend} disabled={sending || !sendAmt || !sendTo}>
              {sending ? <><span className="loading-spinner" style={{ width: 14, height: 14, border: '2px solid rgba(255,255,255,0.3)', borderTop: '2px solid #fff', borderRadius: '50%', display: 'inline-block', animation: 'spin 0.8s linear infinite', marginRight: 8 }} />A processar…</> : `Enviar €${sendAmt || '0'}`}
            </button>
          </div>
        </div>
      )}
    </div>
  );
};

/* ── SMART NOTES ────────────────────────────────────────────── */
const SmartNotes = ({ profile }) => {
  const [newNote, setNewNote] = useStateD('');
  const [notes, setNotes] = useStateD([
    { who: 'Miguel Tavares · Veridian', when: '14:32', body: 'Interesse forte em ESG-linked debt. Mencionou roadshow em junho.', tags: ['Hot', 'ESG'] },
    { who: 'Rita Sousa · Banco Invicta', when: '14:18', body: 'CFO procura bridge de €2M para Q3. Pedir intro ao Pedro.', tags: ['Pipeline', 'Bridge'] },
    { who: 'Ana Cardoso · Solaris', when: '13:55', body: 'Decisora final em RFP solar — janela 3 semanas.', tags: ['Decision', 'Solar'] },
    { who: 'João Reis · Helix Bio', when: '13:40', body: 'Interesse em parceria PT-EU para clinical trials.', tags: ['Partner'] },
  ]);
  const addNote = () => {
    if (!newNote.trim()) return;
    const now = new Date().toLocaleTimeString('pt-PT', { hour: '2-digit', minute: '2-digit' });
    setNotes(prev => [{ who: profile?.name || 'Eu', when: now, body: newNote.trim(), tags: ['Novo'] }, ...prev]);
    setNewNote('');
    if (window.HexisEngine) HexisEngine.awardXP(10, 'Smart Note adicionada');
    SoundFX.success();
  };
  return (
    <div className="notebook">
      <div style={{ display: 'flex', gap: 10, marginBottom: 14 }}>
        <input value={newNote} onChange={e => setNewNote(e.target.value)} onKeyDown={e => e.key === 'Enter' && addNote()} placeholder="Nova nota rápida… (Enter para guardar)" style={{ flex: 1, padding: '10px 14px', borderRadius: 10, background: 'rgba(255,255,255,0.04)', border: '1px solid var(--border-1)', color: '#fff', fontSize: 13, fontFamily: 'var(--font-body)' }} />
        <button className="btn btn-primary btn-sm" onClick={addNote}><Icon name="plus" size={14} /></button>
      </div>
      {notes.map((n, i) => (
        <div key={i} className="note-item" style={{ cursor: 'pointer' }} onClick={() => { SoundFX.tap(); ToastBus.push({ icon: 'sticky-note', title: n.who, desc: n.body }); }}>
          <div className="nh"><span className="who">{n.who}</span><span className="when">{n.when}</span></div>
          <div className="body">{n.body}</div>
          <div className="tags">{n.tags.map(t => <span key={t} className="chip chip-purple">{t}</span>)}</div>
        </div>
      ))}
    </div>
  );
};

/* ── STAKEHOLDERS ───────────────────────────────────────────── */
const Stakeholders = ({ onNav }) => {
  const list = [
    { ini: 'MT', nm: 'Miguel Tavares', role: 'Veridian VC · Partner',    score: 98, action: () => { SoundFX.success(); if (window.HexisEngine) HexisEngine.awardXP(20, 'Contacto stakeholder'); ToastBus.push({ kind: 'success', icon: 'users', title: 'Intro enviada', desc: 'Miguel Tavares notificado. Match 98% confirmado.' }); } },
    { ini: 'RS', nm: 'Rita Sousa',     role: 'Banco Invicta · CFO',      score: 94, action: () => { SoundFX.tap(); ToastBus.push({ icon: 'calendar', title: 'Reunião confirmada', desc: 'Rita Sousa · Hoje 16:00 · Banco Invicta' }); } },
    { ini: 'AC', nm: 'Ana Cardoso',    role: 'Solaris Energy · CEO',     score: 91, action: () => { SoundFX.tap(); ToastBus.push({ icon: 'send', title: 'Follow-up enviado', desc: 'Ana Cardoso · RFP solar · Resposta em 24h' }); } },
    { ini: 'JR', nm: 'João Reis',      role: 'Helix Bio · CSO',          score: 88, action: () => { SoundFX.tap(); ToastBus.push({ icon: 'users', title: 'Perfil aberto', desc: 'João Reis · Interesse em clinical trials PT-EU' }); } },
    { ini: 'PM', nm: 'Pedro Machado',  role: 'Aether RE · Director',     score: 86, action: () => { SoundFX.tap(); ToastBus.push({ icon: 'users', title: 'Perfil aberto', desc: 'Pedro Machado · Real Estate · Pipeline €5.4M' }); } },
  ];
  return (
    <div className="sk-list">
      {list.map((s, i) => (
        <div key={i} className="sk-item" style={{ cursor: 'pointer' }} onClick={s.action}>
          <div className="av">{s.ini}</div>
          <div><div className="nm">{s.nm}</div><div className="role">{s.role}</div></div>
          <span className="score-pill">{s.score}</span>
        </div>
      ))}
    </div>
  );
};

/* ── DASHBOARD PAGE ─────────────────────────────────────────── */
const DashboardPage = ({ onNav }) => {
  const [section, setSection] = useStateD('overview');
  const [period, setPeriod] = useStateD('30d');
  const [chartMode, setChartMode] = useStateD('pipeline');
  const [profile, setProfile] = useStateD(window.HexisEngine ? HexisEngine.getProfile() : {});

  /* Subscribe to HexisEngine profile changes */
  useEffectD(() => {
    if (!window.HexisEngine) return;
    return HexisEngine.subscribe(p => setProfile({ ...p }));
  }, []);

  /* Get Hexis-driven metrics */
  const metrics = useMemoD(() => {
    if (window.HexisEngine) return HexisEngine.getMetrics(period);
    return { pipeline: 1820000, matchScore: 94, meetings: 186, connections: 186, conversion: 31.4, spark_pipeline: [0.8,1,1.2,1.4,1.6,1.7,1.8,1.82], spark_match: [80,84,88,92,94,94,94,94], spark_meetings: [40,65,90,118,145,160,175,186], spark_conversion: [18,21,24,26,28,29.5,30.8,31.4], series_pipeline: { '7d': [[], []], '30d': [[340,580,1100,1820],[42,78,124,186]], '90d': [[1200,2100,4100],[120,220,380]], '1y': [[3200,5800,8400,12400],[320,520,780,1120]] }, series_match: { '7d': [[], []], '30d': [[80,86,90,94],[12,18,28,42]], '90d': [[78,84,92],[38,52,88]], '1y': [[76,82,88,94],[80,140,220,320]] }, labels: { '7d': ['L','M','T','Q','S','S','D'], '30d': ['S1','S2','S3','S4'], '90d': ['Jan','Fev','Mar'], '1y': ['Q1','Q2','Q3','Q4'] } };
  }, [period, profile.xp]);

  const pip_series = metrics.series_pipeline[period] || metrics.series_pipeline['30d'];
  const mch_series = metrics.series_match[period] || metrics.series_match['30d'];
  const chart_labels = metrics.labels[period];
  const pipeline_data = [
    { id: 'pp', label: 'Pipeline (€K)', color: '#7B61FF', data: pip_series[0] || [] },
    { id: 'mt', label: 'Meetings',      color: '#00D1FF', data: pip_series[1] || [] },
  ];
  const match_data = [
    { id: 'av', label: 'Match avg', color: '#A78BFA', data: mch_series[0] || [] },
    { id: 'pr', label: 'Premium',   color: '#FFD700', data: mch_series[1] || [] },
  ];

  const sections = [
    { id: 'overview',     l: 'Visão Geral',    ic: 'layout-dashboard' },
    { id: 'events',       l: 'Eventos',         ic: 'calendar',        n: 6  },
    { id: 'pipeline',     l: 'Pipeline',        ic: 'chart-line',      n: 12 },
    { id: 'connections',  l: 'Conexões',        ic: 'users' },
    { id: 'gamification', l: 'Gamification',    ic: 'trophy' },
    { id: 'missions',     l: 'Missões Ativas',  ic: 'target',          n: (window.HexisEngine ? HexisEngine.getActiveMissions().length : 4) },
    { id: 'wallet',       l: 'E-Wallet',        ic: 'credit-card' },
    { id: 'micro-apps',   l: 'Micro-Apps',      ic: 'grid' },
    { id: 'hexis',        l: 'Hexis Console',   ic: 'cpu' },
    { id: 'notes',        l: 'Smart Notes',     ic: 'sticky-note',     n: 14 },
    { id: 'reports',      l: 'Relatórios',      ic: 'newspaper' },
  ];

  const exportData = () => {
    const data = JSON.stringify({ profile, metrics: HexisEngine?.getMetrics('30d'), exported_at: new Date().toISOString() }, null, 2);
    const blob = new Blob([data], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url; a.download = `marcianus_report_${Date.now()}.json`; a.click();
    URL.revokeObjectURL(url);
    ToastBus.push({ kind: 'success', icon: 'download', title: 'Relatório exportado', desc: 'JSON com métricas Hexis AI completas.' });
    if (window.HexisEngine) HexisEngine.awardXP(5, 'Relatório exportado');
  };

  const renderSection = () => {
    if (section === 'wallet') return (
      <div><div className="section-head" style={{ marginBottom: 24 }}><div className="left"><span className="eyebrow">Financeiro · Marcianus</span><h2>E-Wallet</h2></div></div>
        <DashWallet profile={profile} /></div>
    );
    if (section === 'missions') return (
      <div><div className="section-head" style={{ marginBottom: 24 }}><div className="left"><span className="eyebrow">Behavioral Engine · Live</span><h2>Missões Ativas · 6 Game Types</h2></div></div>
        <MissionEnginePanel /></div>
    );
    if (section === 'micro-apps') return (
      <div>
        <div className="section-head" style={{ marginBottom: 24 }}><div className="left"><span className="eyebrow">Sistema Marcianus™</span><h2>12 Micro-Apps · 3 Camadas Sistémicas</h2></div></div>
        <div style={{ marginBottom: 16, padding: '12px 16px', borderRadius: 10, background: 'rgba(123,97,255,0.06)', border: '1px solid var(--border-purple)', fontSize: 13, color: 'var(--text-2)', lineHeight: 1.6 }}>
          <strong style={{ color: 'var(--purple-soft)' }}>Fluxo:</strong> Micro-Apps → EventOS → BD Central → Hexis AI → D3-BMC
        </div>
        <MicroAppsLayered onOpen={a => { if (window.HexisEngine) HexisEngine.awardXP(8, `Micro-App: ${a.id}`); ToastBus.push({ kind: a.layer === 'purple' ? 'gold' : '', icon: 'sparkles', title: `${a.id} · ${a.name}`, desc: `${a.sub} · Módulo aberto.` }); }} />
      </div>
    );
    if (section === 'hexis') return (
      <div>
        <div className="section-head" style={{ marginBottom: 24 }}><div className="left"><span className="eyebrow">Hexis AI · Comando Central</span><h2>Consola de Inteligência</h2></div>
          <div style={{ display: 'flex', gap: 8 }}><span className="chip chip-success">Online · 24/7</span><span className="chip chip-purple">PVA-7</span></div>
        </div>
        <HexisConsolePanel profile={profile} />
      </div>
    );
    if (section === 'gamification') return (
      <div>
        <div className="section-head" style={{ marginBottom: 24 }}><div className="left"><span className="eyebrow">Behavioral Design B2B</span><h2>Gamification · XP · Ranking</h2></div></div>
        <GamificationPanel profile={profile} />
        <div style={{ marginTop: 24 }}><KnowledgeArenaPanel /></div>
        <div style={{ marginTop: 24 }}><NetworkDominationPanel profile={profile} /></div>
      </div>
    );
    if (section === 'notes') return (
      <div>
        <div className="section-head" style={{ marginBottom: 24 }}><div className="left"><span className="eyebrow">Hexis Smart Notes</span><h2>Notas · AI Auto-classificadas</h2></div></div>
        <SmartNotes profile={profile} />
      </div>
    );
    if (section === 'reports') return (
      <div>
        <div className="section-head" style={{ marginBottom: 24 }}><div className="left"><span className="eyebrow">Relatórios · D3-BMC</span><h2>Analytics & Exportação</h2></div>
          <button className="btn btn-primary" onClick={exportData}><Icon name="download" size={14} /> Exportar JSON</button>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 16 }}>
          {[
            { title: 'Pipeline por Sector', icon: 'chart-bar', desc: 'Breakdown de €' + (metrics.pipeline / 1000).toFixed(0) + 'K por vertical', action: () => { SoundFX.tap(); ToastBus.push({ icon: 'chart-bar', title: 'Relatório Pipeline', desc: 'Exportando dados por sector...' }); exportData(); } },
            { title: 'Match Score Evolution', icon: 'target', desc: `Score ${metrics.matchScore}% · Evolução 90d`, action: () => { SoundFX.tap(); setSection('overview'); setChartMode('match'); } },
            { title: 'ROI por Evento', icon: 'chart-line', desc: '3.4× vs. networking tradicional', action: () => { SoundFX.tap(); ToastBus.push({ icon: 'chart-line', title: 'ROI Report', desc: '3.4× ROI confirmado em 318 eventos.' }); } },
            { title: 'Behavioral Intelligence', icon: 'cpu', desc: `MIS ${(profile.misScore || 0.72).toFixed(3)} · ${profile.tapCount || 42} taps registados`, action: () => { SoundFX.tap(); setSection('hexis'); } },
          ].map((r, i) => (
            <div key={i} className="chart-card" style={{ padding: 24, cursor: 'pointer' }} onClick={r.action}>
              <div style={{ width: 40, height: 40, borderRadius: 10, background: 'rgba(123,97,255,0.14)', border: '1px solid var(--border-purple)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--purple-soft)', marginBottom: 14 }}><Icon name={r.icon} size={20} /></div>
              <h4 style={{ marginBottom: 6 }}>{r.title}</h4>
              <div style={{ fontSize: 13, color: 'var(--text-2)' }}>{r.desc}</div>
            </div>
          ))}
        </div>
      </div>
    );

    /* overview (default) */
    return (
      <>
        <div className="kpi-row">
          <KPI lab="Pipeline 30d" v={<>€<AnimNum value={metrics.pipeline / 1000} decimals={2} />K</>} delta={`${metrics.pipeline > 1820000 ? '+' : ''}${Math.round((metrics.pipeline / 1820000 - 1) * 100) || 38}%`} icon="chart-line" spark={metrics.spark_pipeline} sparkColor="#7B61FF" label="Receita atribuída a eventos" onClick={() => { SoundFX.tap(); setChartMode('pipeline'); }} />
          <KPI lab="Match Score" v={<><AnimNum value={metrics.matchScore} />%</>} delta={metrics.matchScore - 88} icon="target" spark={metrics.spark_match} sparkColor="#A78BFA" label="Média ponderada Hexis AI" onClick={() => { SoundFX.tap(); setChartMode('match'); }} />
          <KPI lab="Meetings" v={<AnimNum value={metrics.meetings} />} delta={Math.round(metrics.meetings * 0.22)} icon="users" spark={metrics.spark_meetings} sparkColor="#00D1FF" label="Agendadas no período" onClick={() => { SoundFX.tap(); setSection('connections'); }} />
          <KPI lab="Conversion" v={<><AnimNum value={metrics.conversion} decimals={1} />%</>} delta={metrics.conversion - 22} icon="zap" spark={metrics.spark_conversion} sparkColor="#FFD700" label="Conexão → Reunião" onClick={() => { SoundFX.tap(); setSection('pipeline'); }} />
        </div>

        <div className="chart-card">
          <div className="chart-head">
            <div className="chart-title"><h3>Performance Temporal</h3><div className="sub">Hexis AI · Dados calculados em tempo real · clica nas legendas para isolar</div></div>
            <div className="chart-controls">
              <div className="seg">
                <button className={chartMode === 'pipeline' ? 'on' : ''} onClick={() => { SoundFX.tap(); setChartMode('pipeline'); }}>Pipeline</button>
                <button className={chartMode === 'match' ? 'on' : ''} onClick={() => { SoundFX.tap(); setChartMode('match'); }}>Match Score</button>
              </div>
            </div>
          </div>
          <div className="filter-bar">
            <span className="lab">Sectores</span>
            {['Banca', 'Tech', 'Saúde', 'Energia', 'Real Estate'].map(s => (
              <span key={s} className="filter-chip on" style={{ cursor: 'pointer' }} onClick={() => { SoundFX.tap(); ToastBus.push({ icon: 'filter', title: `Filtro: ${s}`, desc: 'Dados filtrados por sector.' }); }}>{s} <span className="x">×</span></span>
            ))}
            <span className="filter-chip" style={{ cursor: 'pointer' }} onClick={() => { SoundFX.tap(); ToastBus.push({ icon: 'plus', title: 'Adicionar sector', desc: 'Funcionalidade em breve.' }); }}><Icon name="plus" size={12} /> Adicionar</span>
          </div>
          <LineChart
            series={chartMode === 'pipeline' ? pipeline_data : match_data}
            labels={chart_labels}
            height={300}
            formatY={v => chartMode === 'pipeline' ? (v >= 1000 ? (v / 1000).toFixed(1) + 'M' : v + 'K') : v}
          />
        </div>

        <div className="chart-row-2">
          <div className="chart-card">
            <div className="chart-head">
              <div className="chart-title"><h3>Smart Notes em direto</h3><div className="sub">Auto-classificadas pela Hexis</div></div>
              <button className="btn btn-ghost btn-sm" onClick={() => { SoundFX.tap(); setSection('notes'); }}>Ver todas</button>
            </div>
            <SmartNotes profile={profile} />
          </div>
          <div className="chart-card">
            <div className="chart-head">
              <div className="chart-title"><h3>Distribuição por sector</h3><div className="sub">Conexões registadas hoje</div></div>
            </div>
            <DonutChart total={metrics.connections} data={[
              { name: 'Banca',       value: Math.round(metrics.connections * 0.34), color: '#7B61FF' },
              { name: 'Tech',        value: Math.round(metrics.connections * 0.26), color: '#00D1FF' },
              { name: 'Saúde',       value: Math.round(metrics.connections * 0.15), color: '#00C48C' },
              { name: 'Energia',     value: Math.round(metrics.connections * 0.14), color: '#FFD700' },
              { name: 'Real Estate', value: Math.round(metrics.connections * 0.11), color: '#FF3B5C' },
            ]} />
          </div>
        </div>

        {/* Missions preview */}
        <div style={{ marginTop: 32 }}>
          <div className="section-head" style={{ marginBottom: 16 }}>
            <div className="left"><span className="eyebrow">Behavioral Engine · Live</span><h3 style={{ fontSize: 22 }}>Missões ativas agora</h3></div>
            <button className="btn btn-ghost btn-sm" onClick={() => { SoundFX.tap(); setSection('missions'); }}>Ver todas <Icon name="arrow-right" size={13} /></button>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12 }}>
            {(window.HexisEngine ? HexisEngine.getActiveMissions() : []).slice(0, 3).map((m, i) => (
              <div key={m.id} className="chart-card" style={{ padding: '14px 16px', cursor: 'pointer', border: `1px solid ${m.color}30`, background: m.color + '06' }}
                onClick={() => { SoundFX.tap(); HexisEngine.acceptMission(m.id); setSection('missions'); }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 8 }}>
                  <div style={{ width: 32, height: 32, borderRadius: 8, background: m.color + '20', display: 'flex', alignItems: 'center', justifyContent: 'center', color: m.color, flexShrink: 0 }}><Icon name={m.icon} size={15} /></div>
                  <div>
                    <div style={{ fontSize: 10, fontWeight: 700, color: m.color, textTransform: 'uppercase' }}>{m.game}</div>
                    <div style={{ fontSize: 13, fontWeight: 600, color: '#fff', lineHeight: 1.3 }}>{m.title}</div>
                  </div>
                </div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                  <div style={{ flex: 1, height: 4, background: 'rgba(255,255,255,0.06)', borderRadius: 2 }}>
                    <div style={{ height: '100%', width: `${Math.round((m.elapsed / m.timeLimit) * 100)}%`, background: m.color, borderRadius: 2 }} />
                  </div>
                  <div style={{ fontSize: 13, fontWeight: 800, color: m.color, flexShrink: 0 }}>+{m.reward.xp} XP</div>
                </div>
              </div>
            ))}
          </div>
        </div>

        <div className="section-head" style={{ marginBottom: 20, marginTop: 32 }}>
          <div className="left"><span className="eyebrow">Micro-apps · 12 módulos · 3 camadas</span><h3 style={{ fontSize: 26 }}>Ferramentas operacionais</h3></div>
          <button className="btn btn-ghost btn-sm" onClick={() => { SoundFX.tap(); setSection('micro-apps'); }}>Ver todos <Icon name="grid" size={13} /></button>
        </div>
        <GamificationPanel profile={profile} />
        <MicroAppsLayered onOpen={a => { if (window.HexisEngine) HexisEngine.awardXP(8, `App: ${a.id}`); ToastBus.push({ kind: a.layer === 'purple' ? 'gold' : '', icon: 'sparkles', title: `${a.id} · ${a.name}`, desc: `${a.sub}` }); }} />

        <div className="chart-row-2" style={{ marginTop: 24 }}>
          <div className="chart-card">
            <div className="chart-head"><div className="chart-title"><h3>Stakeholders prioritários</h3><div className="sub">Top decisores por Match Score · clica para acionar</div></div></div>
            <Stakeholders onNav={onNav} />
          </div>
          <div className="chart-card">
            <div className="chart-head"><div className="chart-title"><h3>Próximas ações · Hexis AI</h3><div className="sub">Ações sugeridas com base em comportamento</div></div></div>
            <div className="sk-list">
              {[
                { ic: 'send',     t: 'Enviar follow-up à Ana Cardoso',   s: 'RFP aberto há 11 dias · janela curta',      cta: 'Enviar',      xp: 30 },
                { ic: 'calendar', t: 'Confirmar reunião com Rita Sousa',  s: 'Hoje · 16:00 · CFO Banco Invicta',          cta: 'Confirmar',   xp: 20 },
                { ic: 'users',    t: 'Intro Miguel Tavares ↔ João Reis',  s: 'Match 96% · ESG ↔ Health-tech',            cta: 'Apresentar',  xp: 50 },
                { ic: 'rocket',   t: 'Lançar campanha pós-evento',        s: 'Drip 5 emails · ' + (metrics.meetings) + ' contactos', cta: 'Ativar', xp: 15 },
              ].map((a, i) => (
                <div key={i} className="sk-item" style={{ gridTemplateColumns: 'auto 1fr auto' }}>
                  <div className="av" style={{ background: 'rgba(123,97,255,0.18)', color: 'var(--purple-soft)' }}><Icon name={a.ic} size={14} /></div>
                  <div><div className="nm">{a.t}</div><div className="role">{a.s}</div></div>
                  <button className="btn btn-purple-soft btn-sm" onClick={() => { SoundFX.success(); if (window.HexisEngine) HexisEngine.awardXP(a.xp, a.t); ToastBus.push({ kind: 'success', icon: 'check', title: 'Ação executada · +' + a.xp + ' XP', desc: a.t }); }}>{a.cta}</button>
                </div>
              ))}
            </div>
          </div>
        </div>
      </>
    );
  };

  return (
    <div className="page active">
      <div className="dash">
        {/* STICKY SIDEBAR */}
        <aside className="dash-side" style={{ position: 'sticky', top: 80, height: 'calc(100vh - 80px)', overflowY: 'auto', alignSelf: 'flex-start' }}>
          <h6>Operação</h6>
          {sections.map(s => (
            <div key={s.id} className={`dash-nav-item ${section === s.id ? 'active' : ''}`}
              onClick={() => { SoundFX.tap(); setSection(s.id); if (window.HexisEngine) HexisEngine.trackClick(`dash_section_${s.id}`); }}>
              <div className="ic"><Icon name={s.ic} size={15} /></div>
              <span>{s.l}</span>
              {s.n > 0 && <span className={`badge ${s.n > 10 ? 'gold' : ''}`}>{s.n}</span>}
            </div>
          ))}
          <div style={{ height: 16 }} />
          <h6>Sistema</h6>
          <div className="dash-nav-item" onClick={() => { SoundFX.tap(); setSection('hexis'); }}>
            <div className="ic"><Icon name="cpu" size={15} /></div><span>Hexis Console</span>
            <span className="chip chip-success" style={{ fontSize: 10, padding: '1px 6px', marginLeft: 'auto' }}>Live</span>
          </div>
          <div className="dash-nav-item" onClick={() => { SoundFX.tap(); ToastBus.push({ icon: 'sliders', title: 'Definições', desc: 'Painel de configuração em breve.' }); }}>
            <div className="ic"><Icon name="sliders" size={15} /></div><span>Definições</span>
          </div>
          <div className="dash-nav-item" onClick={() => { SoundFX.tap(); ToastBus.push({ icon: 'shield-check', title: 'Privacidade', desc: 'RGPD ✓ · ISO 27001 ✓ · Dados EU-only.' }); }}>
            <div className="ic"><Icon name="shield-check" size={15} /></div><span>Privacidade</span>
          </div>

          {/* Wallet summary in sidebar */}
          <div style={{ margin: '16px 8px 0', padding: '12px 14px', borderRadius: 10, background: 'linear-gradient(135deg, rgba(123,97,255,0.15), rgba(0,209,255,0.08))', border: '1px solid rgba(123,97,255,0.3)', cursor: 'pointer' }}
            onClick={() => { SoundFX.tap(); setSection('wallet'); }}>
            <div style={{ fontSize: 10, color: 'var(--text-3)', marginBottom: 4 }}>E-WALLET</div>
            <div style={{ fontWeight: 900, fontSize: 18, color: '#fff' }}>€{(profile.walletBalance || 2400).toLocaleString()}</div>
            <div style={{ fontSize: 11, color: '#00C48C', marginTop: 2 }}>+3% cashback ativo</div>
          </div>
        </aside>

        <main className="dash-main">
          <div className="dash-header">
            <div className="dash-title">
              <h1>Hub Operacional</h1>
              <div className="sub">Live · Veridian Tech Summit · Lisboa · MIS {(profile.misScore || 0.72).toFixed(3)}</div>
            </div>
            <div className="dash-quick-actions">
              <div className="seg">
                {['7d', '30d', '90d', '1y'].map(p => (
                  <button key={p} className={period === p ? 'on' : ''} onClick={() => { SoundFX.tap(); setPeriod(p); }}>{p.toUpperCase()}</button>
                ))}
              </div>
              <button className="btn btn-ghost btn-sm" onClick={exportData}><Icon name="download" size={14} /> Export</button>
              <button className="btn btn-primary btn-sm" onClick={() => { SoundFX.success(); fireConfetti({ x: window.innerWidth - 100, y: 200 }); if (window.HexisEngine) HexisEngine.awardXP(10, 'Briefing partilhado'); ToastBus.push({ kind: 'gold', icon: 'sparkles', title: 'Briefing partilhado', desc: 'Equipa notificada.' }); }}>Partilhar</button>
            </div>
          </div>

          {renderSection()}
        </main>
      </div>
    </div>
  );
};

window.DashboardPage = DashboardPage;
