/* SISTEMA screen wrapper: run · observar.
   Reuses DevInbox/DevOverview/DevCosts and adds SistemaKPIs as new flagship page. */

const SistemaScreen = ({ variation, onOpenChat }) => {
  const [sub, setSub] = useSubNav('digi-sistema-sub', 'kpis');

  // Force dark theme
  React.useEffect(() => {
    const prev = document.documentElement.dataset.theme;
    document.documentElement.dataset.theme = 'dark';
    return () => { if (prev) document.documentElement.dataset.theme = prev; };
  }, []);

  React.useEffect(() => {
    const onKey = (e) => {
      if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA') return;
      const map = { '1':'inbox','2':'overview','3':'kpis','4':'costs','5':'integrations' };
      if (e.key === 'a' || e.key === 'A') { setSub('alerts'); return; }
      if (map[e.key]) setSub(map[e.key]);
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, []);

  const Comp = { inbox: DevInbox, overview: DevOverview, costs: DevCosts, kpis: SistemaKPIs }[sub];

  const stub = (title, desc) => (
    <div style={{ padding: 40, maxWidth: 600 }}>
      <div style={{ fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', letterSpacing: '0.08em' }}>SISTEMA · {title.toUpperCase()}</div>
      <h2 className="font-display" style={{ margin: '6px 0 10px', fontSize: 22 }}>{title}</h2>
      <p style={{ color: 'var(--text-muted)', fontSize: 13, lineHeight: 1.6 }}>{desc}</p>
      <div className="ai-surface" style={{ marginTop: 16, padding: 14, borderRadius: 8, fontSize: 12.5 }}>
        <span className="ai-chip"><span className="ai-dot" />Digi AI</span>
        <p style={{ margin: '8px 0 0' }}>Secção em build. Prioridade actual: KPIs · Saúde do Agente.</p>
      </div>
    </div>
  );

  const stubs = {
    integrations: ['Integrations', 'WhatsApp Cloud · Meta Graph · Google Ads · Office365 · Primavera (PENDING) · ProdTrack · FileMaker SAT · SharePoint · Brevo · Langfuse.'],
    alerts: ['Alerts', 'Feed priorizado. 2 críticos (quality_kb, Primavera), 2 warnings, flags para prompt improvement.'],
  };

  const renderSub = () => {
    if (stubs[sub]) return stub(...stubs[sub]);
    if (Comp) return <Comp onOpenChat={onOpenChat} variation={variation} />;
    return <SistemaKPIs onOpenChat={onOpenChat} />;
  };

  return (
    <div style={{ display: 'flex', background: 'var(--bg)', height: '100%', minHeight: 0, overflow: 'hidden' }}>
      <div style={{ flex: 1, minWidth: 0, minHeight: 0, height: '100%', overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
        {renderSub()}
      </div>
    </div>
  );
};

window.SistemaScreen = SistemaScreen;
