// Control Center: prioridade executiva — atenção, saúde do sistema, KPIs enxutos, tarefas e atividade.
// Dados ilustrativos (window.VXData.cc). Itens cujo módulo ainda não existe usam o padrão "não disponível" (desabilitado + Em breve).
function CcPanel({ title, sub, action, children, gap = 20, pad, style }) {
  const { Card, CardHeader } = window.VRticeDesignSystem_d763eb;
  const { bp } = useShell();
  return <Card variant="panel" padding={pad ?? (bp === 'mobile' ? 20 : '28px 32px')} gap={gap} style={style}><CardHeader title={title} subtitle={sub} action={action} />{children}</Card>;
}

function CcLink({ route, children }) {
  const { Badge } = window.VRticeDesignSystem_d763eb;
  const { go } = useShell();
  if (!window.VX_NAV.ready(route)) return <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8, fontSize: 14, fontWeight: 600, color: 'var(--text-subtle)' }}>{children}<Badge variant="meta" tone="neutral">Em breve</Badge></span>;
  return <a href="#" onClick={e => { e.preventDefault(); go(route); }} style={{ fontSize: 14, fontWeight: 600, textDecoration: 'none' }}>{children}</a>;
}

// Dashboard (v0 aprovado no Claude Design, projeto "Vértice OS Presentation"): visão geral e operações.
// Acrescenta, abaixo do layout original, só blocos operacionais que não existem no Painel administrativo.
// Dados ilustrativos (window.VXData). CcPanel/CcLink acima são compartilhados com outras telas.
const VX_DASH_BLUE = 'var(--vx-blue-500)', VX_DASH_SKY = 'var(--vx-sky-400)';
const VX_DASH_ADMIN_ROUTES = ['users', 'roles', 'orgs', 'integrations', 'audit', 'admin'];

function RevenueChart() {
  return (
    <svg viewBox="0 0 1000 340" style={{ width: '100%', height: 'auto', display: 'block', overflow: 'visible' }} fontFamily="Geist Mono, monospace" fontSize="13" fill="var(--text-muted)">
      <defs><linearGradient id="dash-rv" x1="0" y1="0" x2="0" y2="1"><stop offset="0" style={{ stopColor: 'var(--vx-blue-600)', stopOpacity: 0.45 }} /><stop offset="1" style={{ stopColor: 'var(--vx-blue-600)', stopOpacity: 0 }} /></linearGradient></defs>
      <g stroke="var(--overlay-07)" strokeDasharray="4 6">{[10, 85, 160, 235, 310].map(y => <line key={y} x1="90" y1={y} x2="1000" y2={y} />)}</g>
      <text x="0" y="14">$ 700 mil</text><text x="0" y="89">$ 525 mil</text><text x="0" y="164">$ 350 mil</text><text x="0" y="239">$ 175 mil</text><text x="0" y="314">R$ 0 mil</text>
      <path d="M100 180 C 200 176, 240 168, 280 168 S 420 160, 460 158 S 580 146, 640 142 S 760 128, 820 124 S 940 112, 990 110 L990 310 L100 310 Z" fill="url(#dash-rv)" />
      <path d="M100 186 C 200 182, 240 174, 280 174 S 420 166, 460 164 S 580 154, 640 150 S 760 134, 820 131 S 940 120, 990 118" fill="none" style={{ stroke: VX_DASH_SKY }} strokeWidth="2.5" strokeDasharray="6 6" />
      <path d="M100 180 C 200 176, 240 168, 280 168 S 420 160, 460 158 S 580 146, 640 142 S 760 128, 820 124 S 940 112, 990 110" fill="none" style={{ stroke: VX_DASH_BLUE }} strokeWidth="4" />
      <circle cx="820" cy="124" r="7" fill="var(--chart-plot-bg)" style={{ stroke: VX_DASH_BLUE }} strokeWidth="3" />
      <g><rect x="730" y="40" width="180" height="58" rx="10" fill="var(--chart-tooltip-bg)" stroke="var(--overlay-12)" /><circle cx="752" cy="69" r="6" style={{ fill: VX_DASH_SKY }} /><text x="768" y="62" fontFamily="Geist, sans-serif" fontSize="12" fill="var(--text-secondary)">Mai (Realizado)</text><text x="768" y="84" fontSize="15" fill="var(--text-primary)" fontWeight="500">R$ 530 mil</text></g>
      <g textAnchor="middle">{[['Jan', 100], ['Fev', 280], ['Mar', 460], ['Abr', 640], ['Mai', 820], ['Jun', 990]].map(([m, x]) => <text key={m} x={x} y="336">{m}</text>)}</g>
    </svg>
  );
}

function DashboardScreen() {
  const { PageHeader, KpiCard, Card, CardHeader, ProgressBar, Table, Badge, AvatarGroup, Button, IconButton, EmptyState, Checkbox } = window.VRticeDesignSystem_d763eb;
  const { go, bp, toast } = useShell();
  const { can } = useAccess();
  const D = window.VXData, CC = D.cc;
  const [done, setDone] = React.useState([]);
  const [tasks, setTasks] = React.useState(CC.tasks);
  const attention = CC.attention.filter(a => !VX_DASH_ADMIN_ROUTES.includes(a.route) && can(a.perm) && !done.includes(a.t));
  const row = k => ({ borderTop: k ? '1px solid var(--border-subtle)' : 'none' });
  const blocks = [
    { id: 'kpis', title: 'Indicadores', span: 12, node: (
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(min(230px,100%), 1fr))', gap: 20 }}>
        {D.kpis.map(([l, v, d, c, t]) => <KpiCard key={l} label={l} value={v} delta={d} caption={c} trend={t} />)}
      </div>) },
    { id: 'revenue', title: 'Evolução de Receita', span: 8, node: (
      <Card variant="panel" gap={24}>
        <CardHeader title="Evolução de Receita" subtitle="Realizado vs Projetado (Jan — Jun)" action={
          <div style={{ display: 'flex', gap: 20, fontSize: 13, border: '1px solid var(--overlay-10)', borderRadius: 12, padding: '10px 16px' }}>
            <span style={{ display: 'flex', alignItems: 'center', gap: 8 }}><span style={{ width: 16, height: 6, borderRadius: 3, background: VX_DASH_BLUE }} />Realizado</span>
            <span style={{ display: 'flex', alignItems: 'center', gap: 8 }}><span style={{ width: 16, height: 6, borderRadius: 3, background: VX_DASH_SKY }} />Projetado</span>
          </div>} />
        <RevenueChart />
      </Card>) },
    { id: 'pipeline', title: 'Pipeline de Licitações', span: 4, node: (
      <Card variant="card" gap={28}>
        <CardHeader eyebrow="Pipeline" title="Licitações" size="lg" />
        {D.pipeline.map(([l, n, v, p]) => <ProgressBar key={l} label={l} valueLabel={n} value={p} caption={v} />)}
      </Card>) },
    { id: 'contracts', title: 'Contratos Recentes', span: 12, node: (
      <Card variant="panel" style={{ overflowX: 'auto' }}>
        <CardHeader title="Contratos Recentes" subtitle="Últimos contratos firmados e vigentes" action={<CcLink route="obras">Gerenciar</CcLink>} />
        <VxTable id="dashboard" cellX={16} rowY={16} columns={[
          { key: 'c', label: 'Contrato / Cliente', sort: r => r[0], width: 'minmax(240px,2fr)', render: r => <span style={{ display: 'flex', flexDirection: 'column', gap: 4 }}><span style={{ fontWeight: 600 }}>{r[0]}</span><span style={{ fontSize: 13, color: 'var(--text-muted)' }}>{r[1]}</span></span> },
          { key: 'm', label: 'Município', sort: r => r[2], width: 'minmax(140px,1fr)', render: r => <span style={{ color: 'var(--text-strong)' }}>{r[2]}</span> },
          { key: 'v', label: 'Valor', sort: r => Number(String(r[3]).replace(/[^\d,]/g, '').replace(',', '.')) || null, width: 'minmax(140px,1fr)', render: r => <span style={{ fontFamily: 'var(--font-mono)', fontSize: 14 }}>{r[3]}</span> },
          { key: 's', label: 'Status', sortable: false, width: '100px', align: 'right', render: () => <Badge>ATIVO</Badge> },
        ]} rows={D.contracts} />
      </Card>) },
    { id: 'resources', title: 'Planejamento de Recursos', span: 12, node: (
      <Card variant="panel">
        <CardHeader title="Planejamento de Recursos" subtitle="Alocação de força de trabalho" divider action={
          <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 6 }}>
            <span style={{ fontSize: 11, letterSpacing: '0.14em', color: 'var(--text-muted)' }}>UTILIZAÇÃO GERAL</span>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}><span style={{ fontSize: 26, fontWeight: 600, color: 'var(--text-accent)' }}>82%</span><span style={{ fontSize: 12, color: 'var(--text-secondary)', border: '1px solid var(--overlay-14)', borderRadius: 6, padding: '4px 8px' }}>37 de 45 ativos</span></div>
          </div>} />
        {D.teams.map(([n, u, c, av, free]) => (
          <Card key={n} variant="inset" gap={14}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 12 }}><span style={{ fontSize: 15, fontWeight: 600 }}>{n}</span><span style={{ fontFamily: 'var(--font-mono)', fontSize: 14, color: 'var(--text-accent)' }}>{u}/{c} <span style={{ color: 'var(--text-muted)' }}>{Math.round(u / c * 100)}%</span></span></div>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}><AvatarGroup names={av} /><span style={{ fontSize: 13, color: 'var(--text-muted)' }}>Disponíveis: <strong style={{ color: 'var(--text-primary)' }}>{free}</strong></span></div>
            <ProgressBar value={u / c * 100} height={4} />
          </Card>
        ))}
      </Card>) },
    { id: 'attention', title: 'Precisa da sua atenção', span: 8, node: (
      <CcPanel title="Precisa da sua atenção" sub="Operação e comercial · ordenado por urgência" gap={8}>
        {!attention.length && <EmptyState variant="block" icon="ph-check-circle" title="Tudo resolvido">Novos itens aparecem aqui quando exigirem uma decisão.</EmptyState>}
        {attention.map((a, k) => (
          <div key={a.t} style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '14px 0', ...row(k), flexWrap: bp === 'mobile' ? 'wrap' : 'nowrap' }}>
            <span style={{ width: 38, height: 38, flex: 'none', borderRadius: 10, background: vxMix(VX_TONE[a.tone], 14), display: 'flex', alignItems: 'center', justifyContent: 'center' }}><i className={'ph ' + a.icon} style={{ fontSize: 19, color: VX_TONE[a.tone] }} /></span>
            <span style={{ flex: '1 1 220px', minWidth: 0, display: 'flex', flexDirection: 'column', gap: 3 }}><span style={{ fontSize: 14, fontWeight: 600 }}>{a.t}</span><span style={{ fontSize: 13, color: 'var(--text-muted)' }}>{a.d}</span></span>
            <span style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--text-subtle)' }}>{a.age}</span>
            {window.VX_NAV.ready(a.route) ? <Button size="sm" variant="secondary" onClick={() => go(a.route)}>{a.cta}</Button> : <SoonBtn size="sm" variant="secondary">{a.cta}</SoonBtn>}
            <IconButton size="sm" icon="ph-check" label="Marcar como resolvido" onClick={() => { setDone(d => [...d, a.t]); toast('Item resolvido'); }} />
          </div>
        ))}
      </CcPanel>) },
    { id: 'tasks', title: 'Tarefas de hoje', span: 4, node: (
      <CcPanel title="Tarefas de hoje" sub="O que precisa ser executado" gap={4}>
        {tasks.map((t, k) => (
          <div key={t[0]} style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, ...row(k), padding: '6px 0' }}>
            <Checkbox checked={t[2]} onChange={v => setTasks(ts => ts.map((x, j) => j === k ? [x[0], x[1], v] : x))} label={<span style={{ textDecoration: t[2] ? 'line-through' : 'none', color: t[2] ? 'var(--text-subtle)' : 'var(--text-strong)' }}>{t[0]}</span>} />
            <span style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: t[1] === 'hoje' ? 'var(--status-warning)' : 'var(--text-subtle)' }}>{t[1]}</span>
          </div>
        ))}
      </CcPanel>) },
  ];
  return <BlockGrid id="dashboard" blocks={blocks} header={<><PageHeader size="lg" title="Visão Geral & Operações" description="Licitações, contratos e capacidade da operação." /><DemoNotice>Os indicadores, gráficos e alertas desta visão geral são exemplos e ainda não vêm do banco. Dados reais: Comercial, CRM, Oportunidades e Integrações.</DemoNotice></>} />;
}
window.DashboardScreen = DashboardScreen;
