// Stubbed views — real-looking shells but limited interactivity

function StubHeader({ title, subtitle, icon: Icon, action }) {
  return (
    <div className="px-5 pt-5 pb-3 flex items-start justify-between gap-3 shrink-0">
      <div className="flex items-start gap-3">
        {Icon && (
          <div className="w-10 h-10 rounded-md bg-forest-500/10 border border-forest-500/30 text-forest-400 flex items-center justify-center shrink-0">
            <Icon size={20} />
          </div>
        )}
        <div>
          <h1 className="font-display text-xl font-semibold text-slate-100">{title}</h1>
          {subtitle && <p className="text-[13px] text-slate-400 mt-0.5">{subtitle}</p>}
        </div>
      </div>
      {action}
    </div>
  );
}

// 1. Onboarding & setup
function OnboardingView() {
  const { t } = useI18n();
  const camerasBySite = SITES.map((s) => ({
    site: s,
    cams: CAMERAS.filter((c) => c.site_id === s.id),
  }));
  return (
    <div className="flex flex-col h-full overflow-auto">
      <StubHeader
        title="Configuração de Instalações e Câmaras"
        subtitle="Gestão de sites, câmaras (RTSP/ONVIF) e estado dos nós edge."
        icon={Icons.Home}
        action={<Button variant="primary" icon={Icons.Home}>Adicionar instalação</Button>}
      />
      <div className="px-5 pb-5 space-y-4">
        {/* Edge node health */}
        <Section title={<><Icons.Bolt size={13} /> Nós Edge</>} dense>
          <div className="p-4 grid grid-cols-1 md:grid-cols-2 gap-3">
            {SITES.map((s) => (
              <div key={s.id} className="bg-slate-850/40 border border-slate-700/60 rounded-md p-3">
                <div className="flex items-start justify-between gap-2">
                  <div>
                    <div className="font-display font-medium text-slate-100">{s.name}</div>
                    <div className="text-[11px] text-slate-400 font-mono">edge-node-{s.id.slice(-6)}</div>
                  </div>
                  <Pill tone="forest"><span className="w-1.5 h-1.5 rounded-full bg-forest-500 animate-pulseDot" /> {t('common.online')}</Pill>
                </div>
                <div className="grid grid-cols-3 gap-3 mt-3 text-[11px]">
                  <div>
                    <div className="text-slate-500 uppercase tracking-wider text-[10px]">CPU</div>
                    <div className="text-slate-200 font-mono">34%</div>
                  </div>
                  <div>
                    <div className="text-slate-500 uppercase tracking-wider text-[10px]">Hailo</div>
                    <div className="text-slate-200 font-mono">62%</div>
                  </div>
                  <div>
                    <div className="text-slate-500 uppercase tracking-wider text-[10px]">Armazen.</div>
                    <div className="text-slate-200 font-mono">147 / 512 GB</div>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </Section>

        {/* Cameras by site */}
        {camerasBySite.map(({ site, cams }) => (
          <Section
            key={site.id}
            title={<><Icons.Building size={13} /> {site.name} · {cams.length} câmaras</>}
            dense
          >
            <div className="overflow-x-auto">
              <table className="w-full text-[12px]">
                <thead>
                  <tr className="text-left text-[10px] uppercase tracking-wider text-slate-500 border-b border-slate-800/70">
                    <th className="px-3 py-2 font-medium">Câmara</th>
                    <th className="px-3 py-2 font-medium">Fonte</th>
                    <th className="px-3 py-2 font-medium">FPS</th>
                    <th className="px-3 py-2 font-medium">Resolução</th>
                    <th className="px-3 py-2 font-medium">Estado</th>
                  </tr>
                </thead>
                <tbody>
                  {cams.map((c) => (
                    <tr key={c.id} className="border-b border-slate-800/40 hover:bg-slate-850/30">
                      <td className="px-3 py-2 text-slate-200">{c.name} <span className="text-slate-500 font-mono">· {c.short}</span></td>
                      <td className="px-3 py-2 font-mono text-slate-400 text-[11px]">{c.source_url}</td>
                      <td className="px-3 py-2 font-mono text-slate-300">{c.fps}</td>
                      <td className="px-3 py-2 font-mono text-slate-300">{c.resolution}</td>
                      <td className="px-3 py-2">
                        {c.status === 'online' && <Pill tone="forest"><Icons.Wifi size={11} /> {t('common.online')}</Pill>}
                        {c.status === 'offline' && <Pill tone="red"><Icons.WifiOff size={11} /> {t('common.offline')}</Pill>}
                        {c.status === 'degraded' && <Pill tone="amber"><Icons.Wifi size={11} /> {t('common.degraded')}</Pill>}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </Section>
        ))}
      </div>
    </div>
  );
}

// 2. Zone editor — static preview
function ZoneEditorView() {
  const [selectedCam, setSelectedCam] = React.useState(CAMERAS[0] || null);
  const camZones = ZONES.filter((z) => z.camera_id === selectedCam?.id);
  return (
    <div className="flex flex-col h-full overflow-auto">
      <StubHeader
        title="Editor de Zonas"
        subtitle="Desenhe polígonos e atribua um papel semântico (entrada, cofre, perímetro, etc.)."
        icon={Icons.Polygon}
        action={<Pill tone="amber">Pré-visualização estática</Pill>}
      />
      <div className="px-5 pb-5 grid grid-cols-[280px_1fr] gap-4 flex-1 min-h-0">
        {/* Camera list */}
        <Section title="Câmaras" dense className="min-h-0">
          <div className="overflow-y-auto max-h-[560px]">
            {CAMERAS.map((c) => (
              <button
                key={c.id}
                onClick={() => setSelectedCam(c)}
                className={`w-full text-left px-3 py-2 border-b border-slate-800/60 hover:bg-slate-850/60 transition-colors ${selectedCam?.id === c.id ? 'bg-slate-850/80' : ''}`}
              >
                <div className="text-[12px] font-medium text-slate-200">{c.name}</div>
                <div className="text-[10px] text-slate-500 font-mono">{c.short} · {ZONES.filter((z) => z.camera_id === c.id).length} zonas</div>
              </button>
            ))}
          </div>
        </Section>
        {/* Canvas */}
        <Section
          title={<>{selectedCam?.name || '—'} · {camZones.length} zonas definidas</>}
          dense
          action={<Button size="sm" variant="primary" icon={Icons.Polygon}>Nova zona</Button>}
        >
          <div className="p-4">
            <div className="relative aspect-video bg-slate-800 rounded-md overflow-hidden border border-slate-700/60">
              <SyntheticThumb camera={selectedCam} className="absolute inset-0" />
              {camZones.map((z) => (
                <ZoneOverlay key={z.id} zone={z} />
              ))}
              {/* Vertex handles for demo */}
              {camZones.map((z) =>
                z.polygon.map((p, i) => (
                  <div
                    key={`${z.id}-${i}`}
                    className="absolute w-2.5 h-2.5 rounded-full bg-forest-500 border-2 border-navy-900 -translate-x-1/2 -translate-y-1/2"
                    style={{ left: `${p[0] * 100}%`, top: `${p[1] * 100}%` }}
                  />
                ))
              )}
            </div>
            {/* Zones legend */}
            <div className="mt-3 grid grid-cols-2 lg:grid-cols-3 gap-2">
              {camZones.map((z) => {
                const role = ZONE_ROLES[z.semantic_role];
                return (
                  <div key={z.id} className="bg-slate-850/40 border border-slate-700/60 rounded p-2.5 flex items-center justify-between">
                    <div className="flex items-center gap-2 min-w-0">
                      <span className="w-2.5 h-2.5 rounded-full shrink-0" style={{ background: role?.color }} />
                      <div className="min-w-0">
                        <div className="text-[12px] font-medium text-slate-100 truncate">{z.name}</div>
                        <div className="text-[10px] uppercase tracking-wider text-slate-500">{role?.label_pt}</div>
                      </div>
                    </div>
                    <Icons.Gear size={13} className="text-slate-500" />
                  </div>
                );
              })}
              {camZones.length === 0 && (
                <div className="col-span-full text-center text-slate-500 text-[12px] py-4">
                  Sem zonas definidas para esta câmara.
                </div>
              )}
            </div>
          </div>
        </Section>
      </div>
    </div>
  );
}

// 3. Alert rules — if-this-then-that builder
function AlertRulesView() {
  const rules = [
    {
      id: 'r1', name: 'Pessoa não enrolada no cofre fora de horário', enabled: true, severity: 'critical',
      trigger: { class: 'person', zone: 'cofre', identity: 'desconhecida' }, schedule: 'Após 18:00 · seg-sex',
      action: 'Notificar central + SMS gerente',
    },
    {
      id: 'r2', name: 'Permanência > 3 min junto ao ATM', enabled: true, severity: 'high',
      trigger: { class: 'person', zone: 'ATM exterior', dwell: '>180s' }, schedule: 'Sempre',
      action: 'Notificar operador',
    },
    {
      id: 'r3', name: 'Aproximação ao perímetro sem EPI', enabled: true, severity: 'critical',
      trigger: { class: 'person', zone: 'perímetro', attribute: 'sem capacete' }, schedule: 'Sempre',
      action: 'Notificar segurança + sirene',
    },
    {
      id: 'r4', name: 'Veículo no portão norte fora de horário', enabled: false, severity: 'medium',
      trigger: { class: 'vehicle', zone: 'portão norte' }, schedule: 'Após 22:00',
      action: 'Notificar central',
    },
  ];
  return (
    <div className="flex flex-col h-full overflow-auto">
      <StubHeader
        title="Regras de Alerta"
        subtitle="Construtor visual: classe × zona × tempo → notificação."
        icon={Icons.Bell}
        action={<Button variant="primary" icon={Icons.Bell}>Nova regra</Button>}
      />
      <div className="px-5 pb-5 space-y-3">
        {rules.map((r) => (
          <div key={r.id} className="bg-slate-850/40 border border-slate-700/60 rounded-md p-4 hover:border-slate-600/60 transition-colors">
            <div className="flex items-start justify-between gap-3 mb-3">
              <div className="flex items-center gap-3">
                <button
                  className={`w-9 h-5 rounded-full p-0.5 transition-colors ${r.enabled ? 'bg-forest-500' : 'bg-slate-700'}`}
                  aria-label={r.enabled ? 'Disable' : 'Enable'}
                >
                  <span className={`block w-4 h-4 rounded-full bg-white transition-transform ${r.enabled ? 'translate-x-4' : ''}`} />
                </button>
                <div>
                  <div className="text-[13px] font-medium text-slate-100">{r.name}</div>
                  <div className="text-[11px] text-slate-500">{r.schedule}</div>
                </div>
              </div>
              <SeverityBadge severity={r.severity} />
            </div>
            <div className="flex items-center gap-2 flex-wrap text-[11px] font-mono">
              <span className="text-slate-500">SE</span>
              {Object.entries(r.trigger).map(([k, v]) => (
                <Pill key={k} tone="navy">{k} = {v}</Pill>
              ))}
              <Icons.ArrowRight size={13} className="text-slate-500 mx-1" />
              <span className="text-slate-500">ENTÃO</span>
              <Pill tone="forest">{r.action}</Pill>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

// 4. Identities & Access
function IdentitiesView() {
  return (
    <div className="flex flex-col h-full overflow-auto">
      <StubHeader
        title="Identidades e Acessos"
        subtitle="Enrolamento de pessoas e gestão de permissões por zona."
        icon={Icons.Users}
        action={<Button variant="primary" icon={Icons.Users}>Enrolar pessoa</Button>}
      />
      <div className="px-5 pb-5">
        <Section dense>
          <div className="overflow-x-auto">
            <table className="w-full text-[12px]">
              <thead>
                <tr className="text-left text-[10px] uppercase tracking-wider text-slate-500 border-b border-slate-800/70">
                  <th className="px-4 py-2.5 font-medium">Pessoa</th>
                  <th className="px-4 py-2.5 font-medium">Cargo</th>
                  <th className="px-4 py-2.5 font-medium">Permissões</th>
                  <th className="px-4 py-2.5 font-medium">Amostras</th>
                  <th className="px-4 py-2.5 font-medium">Última aparição</th>
                </tr>
              </thead>
              <tbody>
                {IDENTITIES.map((i) => (
                  <tr key={i.id} className="border-b border-slate-800/40 hover:bg-slate-850/30">
                    <td className="px-4 py-3">
                      <div className="flex items-center gap-3">
                        <IdentityAvatar identity={i} size={32} />
                        <div>
                          <div className="text-slate-100 font-medium">{i.name}</div>
                          <div className="text-[10px] font-mono text-slate-500">{i.id}</div>
                        </div>
                      </div>
                    </td>
                    <td className="px-4 py-3 text-slate-300">{i.role}</td>
                    <td className="px-4 py-3">
                      <div className="flex flex-wrap gap-1">
                        {i.permissions.map((p) => (
                          <Pill key={p} tone="slate">
                            <span className="w-1 h-1 rounded-full" style={{ background: ZONE_ROLES[p]?.color || '#94a3b8' }} />
                            {ZONE_ROLES[p]?.label_pt || p}
                          </Pill>
                        ))}
                      </div>
                    </td>
                    <td className="px-4 py-3 font-mono text-slate-300">{i.sample_count}</td>
                    <td className="px-4 py-3 font-mono text-slate-400">{relTime(Date.now() + i.last_seen_at * 1000)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </Section>
      </div>
    </div>
  );
}

// 5. Compliance & Reports — Law 2/10
function ComplianceView() {
  const auditLog = [
    { ts: -120, who: 'Mário Quitumba', action: 'Visualizou clip evt-1011', target: 'clip-1010' },
    { ts: -380, who: 'Domingos Cassule', action: 'Exportou relatório semanal', target: 'rpt-2026-W21' },
    { ts: -780, who: 'Operador Central', action: 'Confirmou alerta crítico', target: 'evt-1' },
    { ts: -1240, who: 'Esperança Tchikuteni', action: 'Pesquisou "carrinha de entregas"', target: 'search' },
    { ts: -2400, who: 'Sistema', action: 'Eliminação automática de 184 clips expirados', target: 'retention' },
    { ts: -6800, who: 'Mário Quitumba', action: 'Visualizou clip evt-1003', target: 'clip-1002' },
  ];

  return (
    <div className="flex flex-col h-full overflow-auto">
      <StubHeader
        title="Conformidade e Relatórios"
        subtitle="Lei 2/10 sobre videovigilância · retenção · consentimento · auditoria."
        icon={Icons.Shield}
        action={<Button variant="primary" icon={Icons.Shield}>Exportar relatório</Button>}
      />
      <div className="px-5 pb-5 space-y-4">
        {/* Posture cards */}
        <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
          <div className="bg-slate-850/40 border border-forest-500/30 rounded-md p-4">
            <div className="flex items-center justify-between mb-2">
              <div className="text-[10px] uppercase tracking-wider text-slate-500 font-medium">Retenção média</div>
              <Icons.Clock size={15} className="text-forest-400" />
            </div>
            <div className="font-display text-2xl font-semibold text-slate-100">23<span className="text-base text-slate-400 ml-1">dias</span></div>
            <div className="text-[11px] text-slate-400 mt-1">Limite legal: 30 dias · em conformidade</div>
          </div>
          <div className="bg-slate-850/40 border border-forest-500/30 rounded-md p-4">
            <div className="flex items-center justify-between mb-2">
              <div className="text-[10px] uppercase tracking-wider text-slate-500 font-medium">Sinalização pública</div>
              <Icons.Shield size={15} className="text-forest-400" />
            </div>
            <div className="font-display text-2xl font-semibold text-slate-100">12/12</div>
            <div className="text-[11px] text-slate-400 mt-1">Avisos visíveis em todas as zonas monitorizadas</div>
          </div>
          <div className="bg-slate-850/40 border border-amber-500/30 rounded-md p-4">
            <div className="flex items-center justify-between mb-2">
              <div className="text-[10px] uppercase tracking-wider text-slate-500 font-medium">Consentimentos</div>
              <Icons.UserCheck size={15} className="text-amber-400" />
            </div>
            <div className="font-display text-2xl font-semibold text-slate-100">94<span className="text-base text-slate-400">%</span></div>
            <div className="text-[11px] text-amber-300 mt-1">3 identidades pendentes de assinatura</div>
          </div>
        </div>

        {/* Audit log */}
        <Section
          title={<><Icons.List size={13} /> Registo de Auditoria</>}
          dense
          action={<Button size="sm" variant="outline" icon={Icons.Filter}>Filtrar</Button>}
        >
          <div className="divide-y divide-slate-800/60">
            {auditLog.map((l, i) => (
              <div key={i} className="px-4 py-2.5 flex items-center gap-3 hover:bg-slate-850/30">
                <div className="font-mono text-[10px] text-slate-500 w-24 shrink-0">{relTime(Date.now() + l.ts * 1000)} atrás</div>
                <div className="text-[12px] text-slate-200 flex-1">
                  <span className="text-slate-100 font-medium">{l.who}</span> {l.action}
                </div>
                <div className="font-mono text-[10px] text-slate-500">{l.target}</div>
              </div>
            ))}
          </div>
        </Section>

        {/* Retention timeline */}
        <Section title={<><Icons.Clock size={13} /> Retenção de Clips</>} dense>
          <div className="p-4 space-y-2">
            {CLIPS.slice(0, 6).map((c) => {
              const cam = lookupCamera(c.camera_id);
              const daysLeft = c.retention_until;
              const pct = Math.max(2, (daysLeft / 30) * 100);
              const tone = daysLeft < 5 ? 'red' : daysLeft < 12 ? 'amber' : 'forest';
              const barColor = daysLeft < 5 ? '#ef4444' : daysLeft < 12 ? '#f59e0b' : '#38a169';
              return (
                <div key={c.id} className="flex items-center gap-3">
                  <div className="w-40 text-[11px] text-slate-300 truncate shrink-0">{cam?.name} <span className="text-slate-500 font-mono">· {c.id}</span></div>
                  <div className="flex-1 h-2 bg-slate-750 rounded-full overflow-hidden relative">
                    <div className="absolute inset-y-0 left-0 rounded-full transition-all" style={{ width: `${pct}%`, background: barColor }} />
                  </div>
                  <Pill tone={tone} className="font-mono w-32 justify-center shrink-0">expira em {daysLeft}d</Pill>
                </div>
              );
            })}
          </div>
        </Section>
      </div>
    </div>
  );
}

window.OnboardingView = OnboardingView;
window.ZoneEditorView = ZoneEditorView;
window.AlertRulesView = AlertRulesView;
window.IdentitiesView = IdentitiesView;
window.ComplianceView = ComplianceView;
