/* eslint-disable @next/next/no-img-element */
import { useCallback, useEffect, useMemo, useRef, useState } from "react"
import { createRoot } from "react-dom/client"
import { invoke } from "@tauri-apps/api/core"
import { Store } from "@tauri-apps/plugin-store"
import { appLocalDataDir } from "@tauri-apps/api/path"
import { ExternalLink, Eye, EyeOff, GalleryVerticalEnd, Loader2, RefreshCw } from "lucide-react"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "./components/ui/tabs"
import { cn } from "./lib/utils"

type MachineOs = {
  name: string
  version?: string | null
  architecture?: string | null
}

type MachineMetrics = {
  collectedAt: string
  cpuLogicalCores: number
  cpuPhysicalCores?: number | null
  cpuUsagePercent: number
  memoryTotalBytes: number
  memoryUsedBytes: number
  memoryUsedPercent: number
  uptimeSeconds: number
}

type MachineInventory = {
  cpuBrand?: string | null
  hostIdentifier?: string | null
}

type MachineProfile = {
  hostname: string
  os: MachineOs
  macAddresses: string[]
  serialNumbers: string[]
  inventory: MachineInventory
  metrics: MachineMetrics
}

type MachineRegisterResponse = {
  machineId: string
  tenantId?: string | null
  companyId?: string | null
  companySlug?: string | null
  machineToken: string
  machineEmail?: string | null
  expiresAt?: number | null
  persona?: string | null
  assignedUserId?: string | null
  collaborator?: {
    email: string
    name?: string | null
  } | null
}

type CompanyOption = {
  id: string
  tenantId: string
  name: string
  slug: string
}

type AgentConfig = {
  machineId: string
  tenantId?: string | null
  companySlug?: string | null
  companyName?: string | null
  machineEmail?: string | null
  collaboratorEmail?: string | null
  collaboratorName?: string | null
  accessRole: "collaborator" | "manager"
  assignedUserId?: string | null
  assignedUserEmail?: string | null
  assignedUserName?: string | null
  apiBaseUrl: string
  appUrl: string
  createdAt: number
  lastSyncedAt?: number | null
  expiresAt?: number | null
  heartbeatIntervalSec?: number | null
}

declare global {
  interface ImportMetaEnv {
    readonly VITE_APP_URL?: string
    readonly VITE_API_BASE_URL?: string
  }
  interface ImportMeta { readonly env: ImportMetaEnv }
}

const STORE_FILENAME = "machine-agent.json"
const DEFAULT_APP_URL = import.meta.env.MODE === "production" ? "https://tickets.esdrasrenan.com.br" : "http://localhost:3000"
const DEFAULT_TENANT_ID = "tenant-atlas"

function normalizeUrl(value?: string | null, fallback = DEFAULT_APP_URL) {
  const trimmed = (value ?? fallback).trim()
  if (!trimmed.startsWith("http")) return fallback
  return trimmed.replace(/\/+$/, "")
}

const appUrl = normalizeUrl(import.meta.env.VITE_APP_URL, DEFAULT_APP_URL)
const apiBaseUrl = normalizeUrl(import.meta.env.VITE_API_BASE_URL, appUrl)

async function loadStore(): Promise<Store> {
  const dir = await appLocalDataDir()
  return await Store.load(STORE_FILENAME, { dir })
}

async function readToken(store: Store): Promise<string | null> {
  return (await store.get<string>("token")) ?? null
}

async function writeToken(store: Store, token: string): Promise<void> {
  await store.set("token", token)
  await store.save()
}

async function readConfig(store: Store): Promise<AgentConfig | null> {
  return (await store.get<AgentConfig>("config")) ?? null
}

async function writeConfig(store: Store, cfg: AgentConfig): Promise<void> {
  await store.set("config", cfg)
  await store.save()
}

function bytes(n?: number) {
  if (!n || !Number.isFinite(n)) return "—"
  const u = ["B","KB","MB","GB","TB"]
  let v = n; let i = 0
  while (v >= 1024 && i < u.length - 1) { v/=1024; i++ }
  return `${v.toFixed(v>=10||i===0?0:1)} ${u[i]}`
}

function pct(p?: number) { return !p && p !== 0 ? "—" : `${p.toFixed(0)}%` }

function App() {
  const [store, setStore] = useState<Store | null>(null)
  const [token, setToken] = useState<string | null>(null)
  const [config, setConfig] = useState<AgentConfig | null>(null)
  const [profile, setProfile] = useState<MachineProfile | null>(null)
  const [error, setError] = useState<string | null>(null)
  const [busy, setBusy] = useState(false)
  const [status, setStatus] = useState<string | null>(null)
  const [showSecret, setShowSecret] = useState(false)
  const [isLaunchingSystem, setIsLaunchingSystem] = useState(false)

  const [provisioningSecret, setProvisioningSecret] = useState("")
  const [tenantId, setTenantId] = useState("")
  const [company, setCompany] = useState("")
  const [collabEmail, setCollabEmail] = useState("")
  const [collabName, setCollabName] = useState("")
  const [accessRole, setAccessRole] = useState<"collaborator" | "manager">("collaborator")
  const [companyOptions, setCompanyOptions] = useState<CompanyOption[]>([])
  const [selectedCompany, setSelectedCompany] = useState<CompanyOption | null>(null)
  const [companyLookupPending, setCompanyLookupPending] = useState(false)
  const [updating, setUpdating] = useState(false)
  const [updateInfo, setUpdateInfo] = useState<{ message: string; tone: "info" | "success" | "error" } | null>({
    message: "Atualizações automáticas são verificadas a cada inicialização.",
    tone: "info",
  })
  const autoLaunchRef = useRef(false)
  const autoUpdateRef = useRef(false)

  useEffect(() => {
    (async () => {
      try {
        const s = await loadStore()
        setStore(s)
        const t = await readToken(s)
        setToken(t)
        const cfg = await readConfig(s)
        setConfig(cfg)
        setAccessRole(cfg?.accessRole ?? "collaborator")
        if (cfg?.collaboratorEmail) setCollabEmail(cfg.collaboratorEmail)
        if (cfg?.collaboratorName) setCollabName(cfg.collaboratorName)
        if (cfg?.companyName) setCompany(cfg.companyName)
        if (cfg?.tenantId) setTenantId(cfg.tenantId)
        if (!t) {
          const p = await invoke<MachineProfile>("collect_machine_profile")
          setProfile(p)
        }
        setStatus(t ? "online" : null)
      } catch {
        setError("Falha ao carregar estado do agente.")
      }
    })()
  }, [])

  useEffect(() => {
    if (!store || !config) return
    const email = collabEmail.trim()
    const name = collabName.trim()
    const normalizedEmail = email.length > 0 ? email : null
    const normalizedName = name.length > 0 ? name : null
    if (
      config.collaboratorEmail === normalizedEmail &&
      config.collaboratorName === normalizedName &&
      config.accessRole === accessRole
    ) {
      return
    }
    const nextConfig: AgentConfig = {
      ...config,
      collaboratorEmail: normalizedEmail,
      collaboratorName: normalizedName,
      accessRole,
    }
    setConfig(nextConfig)
    writeConfig(store, nextConfig).catch((err) => console.error("Falha ao atualizar colaborador", err))
  }, [store, config, config?.collaboratorEmail, config?.collaboratorName, config?.accessRole, collabEmail, collabName, accessRole])

  useEffect(() => {
    if (!store || !config) return
    const normalizedAppUrl = normalizeUrl(config.appUrl, appUrl)
    const normalizedApiUrl = normalizeUrl(config.apiBaseUrl, apiBaseUrl)
    const shouldForceRemote = import.meta.env.MODE === "production"
    const nextAppUrl = shouldForceRemote && normalizedAppUrl.includes("localhost") ? appUrl : normalizedAppUrl
    const nextApiUrl = shouldForceRemote && normalizedApiUrl.includes("localhost") ? apiBaseUrl : normalizedApiUrl
    if (nextAppUrl !== config.appUrl || nextApiUrl !== config.apiBaseUrl) {
      const updatedConfig = { ...config, appUrl: nextAppUrl, apiBaseUrl: nextApiUrl }
      setConfig(updatedConfig)
      writeConfig(store, updatedConfig).catch((err) => console.error("Falha ao atualizar configuração", err))
    }
  }, [store, config])

  const resolvedAppUrl = useMemo(() => {
    if (!config?.appUrl) return appUrl
    const normalized = normalizeUrl(config.appUrl, appUrl)
    if (import.meta.env.MODE === "production" && normalized.includes("localhost")) {
      return appUrl
    }
    return normalized
  }, [config?.appUrl])

  useEffect(() => {
    const trimmedSecret = provisioningSecret.trim()
    const query = company.trim()
    if (!trimmedSecret || query.length < 2) {
      setCompanyOptions([])
      setCompanyLookupPending(false)
      return
    }
    if (selectedCompany && selectedCompany.name.toLowerCase() === query.toLowerCase()) {
      setCompanyOptions([])
      setCompanyLookupPending(false)
      return
    }
    const controller = new AbortController()
    const timeout = setTimeout(async () => {
      setCompanyLookupPending(true)
      try {
        const params = new URLSearchParams()
        params.set("search", query)
        const tenant = tenantId.trim()
        if (tenant) params.set("tenantId", tenant)
        const res = await fetch(`${apiBaseUrl}/api/machines/companies?${params.toString()}`, {
          headers: {
            "X-Machine-Secret": trimmedSecret,
          },
          signal: controller.signal,
        })
        if (!res.ok) {
          setCompanyOptions([])
          return
        }
        const data = (await res.json()) as { companies?: CompanyOption[] }
        setCompanyOptions(data.companies ?? [])
      } catch (error) {
        if (error instanceof DOMException && error.name === "AbortError") return
        if (typeof error === "object" && error && "name" in error && (error as { name?: string }).name === "AbortError") return
        console.error("Falha ao buscar empresas", error)
      } finally {
        setCompanyLookupPending(false)
      }
    }, 200)
    return () => {
      clearTimeout(timeout)
      controller.abort()
      setCompanyLookupPending(false)
    }
  }, [company, tenantId, provisioningSecret, selectedCompany])

  function handleSelectCompany(option: CompanyOption) {
    setCompany(option.name)
    setSelectedCompany(option)
    setCompanyOptions([])
    if (!tenantId.trim()) {
      setTenantId(option.tenantId)
    }
  }

  function handleCompanyInputChange(value: string) {
    setCompany(value)
    setSelectedCompany((prev) => {
      if (!prev) return null
      return prev.name.toLowerCase() === value.trim().toLowerCase() ? prev : null
    })
  }

  async function register() {
    if (!profile) return
    if (!provisioningSecret.trim()) { setError("Informe o código de provisionamento."); return }
    const normalizedEmail = collabEmail.trim().toLowerCase()
    if (!normalizedEmail) {
      setError("Informe o e-mail do colaborador ou gestor para vincular esta máquina.")
      return
    }
    const normalizedName = collabName.trim()
    if (!normalizedName) {
      setError("Informe o nome completo do colaborador ou gestor.")
      return
    }
    setBusy(true); setError(null)
    try {
      const trimmedTenantId = tenantId.trim()
      const trimmedCompanyName = company.trim()
      let ensuredCompany: { name: string; slug: string } | null = null
      if (trimmedCompanyName) {
        if (selectedCompany && selectedCompany.name.toLowerCase() === trimmedCompanyName.toLowerCase()) {
          ensuredCompany = { name: selectedCompany.name, slug: selectedCompany.slug }
        } else {
          const ensureRes = await fetch(`${apiBaseUrl}/api/machines/companies`, {
            method: "POST",
            headers: {
              "Content-Type": "application/json",
              "X-Machine-Secret": provisioningSecret.trim(),
            },
            body: JSON.stringify({
              tenantId: trimmedTenantId || undefined,
              name: trimmedCompanyName,
            }),
          })
          if (!ensureRes.ok) {
            const text = await ensureRes.text()
            throw new Error(`Falha ao preparar empresa (${ensureRes.status}): ${text.slice(0, 300)}`)
          }
          const ensureData = (await ensureRes.json()) as { company?: { name: string; slug: string; tenantId?: string } }
          if (!ensureData.company?.slug) {
            throw new Error("Resposta inválida ao preparar empresa.")
          }
          ensuredCompany = { name: ensureData.company.name, slug: ensureData.company.slug }
          setSelectedCompany({
            id: ensureData.company.slug,
            name: ensureData.company.name,
            slug: ensureData.company.slug,
            tenantId: ensureData.company.tenantId ?? (trimmedTenantId || DEFAULT_TENANT_ID),
          })
          if (!trimmedTenantId && ensureData.company.tenantId) {
            setTenantId(ensureData.company.tenantId)
          }
        }
      }

      const collaboratorPayload = {
        email: normalizedEmail,
        name: normalizedName,
      }
      const collaboratorMetadata = collaboratorPayload
        ? { ...collaboratorPayload, role: accessRole }
        : undefined
      const metadataPayload: Record<string, unknown> = {
        inventory: profile.inventory,
        metrics: profile.metrics,
      }
      if (collaboratorMetadata) {
        metadataPayload.collaborator = collaboratorMetadata
      }
      const payload = {
        provisioningSecret: provisioningSecret.trim(),
        tenantId: trimmedTenantId || undefined,
        companySlug: ensuredCompany?.slug,
        hostname: profile.hostname,
        os: profile.os,
        macAddresses: profile.macAddresses,
        serialNumbers: profile.serialNumbers,
        metadata: metadataPayload,
        accessRole,
        collaborator: collaboratorPayload,
        registeredBy: "desktop-agent",
      }
      const res = await fetch(`${apiBaseUrl}/api/machines/register`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload) })
      if (!res.ok) {
        const text = await res.text()
        throw new Error(`Falha no registro (${res.status}): ${text.slice(0,300)}`)
      }
      const data = (await res.json()) as MachineRegisterResponse
      if (!store) throw new Error("Store ausente")
      await writeToken(store, data.machineToken)
      const cfg: AgentConfig = {
        machineId: data.machineId,
        tenantId: data.tenantId ?? null,
        companySlug: data.companySlug ?? ensuredCompany?.slug ?? null,
        companyName: ensuredCompany?.name ?? (trimmedCompanyName || null),
        machineEmail: data.machineEmail ?? null,
        collaboratorEmail: collaboratorPayload?.email ?? null,
        collaboratorName: collaboratorPayload?.name ?? null,
        accessRole,
        assignedUserId: data.assignedUserId ?? null,
        assignedUserEmail: data.collaborator?.email ?? collaboratorPayload?.email ?? null,
        assignedUserName: data.collaborator?.name ?? collaboratorPayload?.name ?? null,
        apiBaseUrl,
        appUrl,
        createdAt: Date.now(),
        lastSyncedAt: Date.now(),
        expiresAt: data.expiresAt ?? null,
      }
      await writeConfig(store, cfg)
      setConfig(cfg); setToken(data.machineToken)
      if (ensuredCompany?.name) {
        setCompany(ensuredCompany.name)
      }
      await invoke("start_machine_agent", { baseUrl: apiBaseUrl, token: data.machineToken, status: "online", intervalSeconds: 300 })
      setStatus("online")
    } catch (err) {
      setError(err instanceof Error ? err.message : String(err))
    } finally {
      setBusy(false)
    }
  }

  const openSystem = useCallback(() => {
    if (!token) return
    setIsLaunchingSystem(true)
    const persona = (config?.accessRole ?? accessRole) === "manager" ? "manager" : "collaborator"
    const redirectTarget = persona === "manager" ? "/dashboard" : "/portal"
    const url = `${resolvedAppUrl}/machines/handshake?token=${encodeURIComponent(token)}&redirect=${encodeURIComponent(redirectTarget)}`
    window.location.href = url
  }, [token, config?.accessRole, accessRole, resolvedAppUrl])

  async function reprovision() {
    if (!store) return
    await store.delete("token"); await store.delete("config"); await store.save()
    autoLaunchRef.current = false
    setToken(null); setConfig(null); setStatus(null); setAccessRole("collaborator")
    setCompany(""); setSelectedCompany(null); setCompanyOptions([])
    setIsLaunchingSystem(false)
    const p = await invoke<MachineProfile>("collect_machine_profile")
    setProfile(p)
  }

  async function sendInventoryNow() {
    if (!token || !profile) return
    setBusy(true); setError(null)
    try {
      const collaboratorPayload = collabEmail.trim()
        ? { email: collabEmail.trim(), name: collabName.trim() || undefined }
        : undefined
      const collaboratorInventory = collaboratorPayload
        ? { ...collaboratorPayload, role: accessRole }
        : undefined
      const inventoryPayload: Record<string, unknown> = { ...profile.inventory }
      if (collaboratorInventory) {
        inventoryPayload.collaborator = collaboratorInventory
      }
      const payload = {
        machineToken: token,
        hostname: profile.hostname,
        os: profile.os,
        metrics: profile.metrics,
        inventory: inventoryPayload,
      }
      const res = await fetch(`${apiBaseUrl}/api/machines/inventory`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      })
      if (!res.ok) {
        const text = await res.text()
        throw new Error(`Falha ao enviar inventário (${res.status}): ${text.slice(0, 200)}`)
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : String(err))
    } finally {
      setBusy(false)
    }
  }

  async function checkForUpdates(auto = false) {
    try {
      if (!auto) {
        setUpdating(true)
        setUpdateInfo({ tone: "info", message: "Procurando por atualizações..." })
      }
      const { check } = await import("@tauri-apps/plugin-updater")
      type UpdateResult = {
        available?: boolean
        version?: string
        downloadAndInstall?: () => Promise<void>
      }
      const update = (await check()) as UpdateResult | null
      if (update?.available) {
        setUpdateInfo({
          tone: "info",
          message: `Atualização ${update.version} disponível. Baixando e aplicando...`,
        })
        if (typeof update.downloadAndInstall === "function") {
          await update.downloadAndInstall()
          const { relaunch } = await import("@tauri-apps/plugin-process")
          await relaunch()
        }
      } else if (!auto) {
        setUpdateInfo({ tone: "info", message: "Nenhuma atualização disponível no momento." })
      }
    } catch (error) {
      console.error("Falha ao verificar atualizações", error)
      if (!auto) {
        setUpdateInfo({
          tone: "error",
          message: "Falha ao verificar atualizações. Tente novamente mais tarde.",
        })
      }
    } finally {
      if (!auto) setUpdating(false)
    }
  }

  useEffect(() => {
    if (import.meta.env.DEV) return
    if (autoUpdateRef.current) return
    autoUpdateRef.current = true
    checkForUpdates(true).catch((err: unknown) => {
      console.error("Falha ao executar atualização automática", err)
    })
  }, [])

  useEffect(() => {
    if (!token) return
    if (autoLaunchRef.current) return
    autoLaunchRef.current = true
    setIsLaunchingSystem(true)
    openSystem()
  }, [token, config?.accessRole, openSystem])

  if (isLaunchingSystem && token) {
    return (
      <div className="min-h-screen grid place-items-center bg-slate-50 p-6">
        <div className="flex flex-col items-center gap-3 rounded-2xl border border-slate-200 bg-white px-8 py-10 shadow-sm">
          <Loader2 className="size-6 animate-spin text-neutral-700" />
          <p className="text-sm font-medium text-neutral-800">Abrindo plataforma da Rever…</p>
          <p className="text-xs text-neutral-500">Aguarde só um instante.</p>
        </div>
      </div>
    )
  }

  return (
    <div className="min-h-screen grid place-items-center p-6">
      <div className="w-full max-w-[720px] rounded-2xl border border-slate-200 bg-white p-6 shadow-sm">
        <div className="mb-2 flex items-center justify-between gap-3">
          <div className="flex items-center gap-3">
            <span className="flex size-8 items-center justify-center rounded-lg bg-neutral-900 text-white"><GalleryVerticalEnd className="size-4" /></span>
            <div className="flex flex-col leading-tight">
              <span className="text-base font-semibold text-neutral-900">Raven</span>
              <span className="text-xs font-medium text-neutral-500">Portal do Cliente</span>
            </div>
          </div>
          <StatusBadge status={status} />
        </div>
        <h1 className="text-base font-semibold text-slate-800">Agente Desktop</h1>
        {error ? <p className="mt-3 rounded-md bg-rose-50 p-2 text-sm text-rose-700">{error}</p> : null}
        {!token ? (
          <div className="mt-4 space-y-3">
            <p className="text-sm text-slate-600">Informe os dados para registrar esta máquina.</p>
            <div className="grid gap-2">
              <label className="text-sm font-medium">Código de provisionamento</label>
              <div className="relative">
                <input className="w-full rounded-lg border border-slate-300 px-3 py-2 pr-9 text-sm" type={showSecret?"text":"password"} value={provisioningSecret} onChange={(e)=>setProvisioningSecret(e.target.value)} />
                <button className="absolute right-2 top-1/2 -translate-y-1/2 p-1 text-slate-600" onClick={()=>setShowSecret((v)=>!v)} aria-label="Mostrar/ocultar">
                  {showSecret ? <EyeOff className="size-4"/> : <Eye className="size-4"/>}
                </button>
              </div>
            </div>
            <div className="grid gap-2">
              <label className="text-sm font-medium">Empresa (nome ou slug, opcional)</label>
              <input
                className="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm"
                placeholder="ex.: Paulicon Contábil"
                value={company}
                onChange={(e) => handleCompanyInputChange(e.target.value)}
              />
              {companyLookupPending ? (
                <p className="text-xs text-slate-500">Buscando empresas...</p>
              ) : companyOptions.length > 0 ? (
                <div className="max-h-48 w-full overflow-y-auto rounded-md border border-slate-200 bg-white text-sm shadow-sm">
                  {companyOptions.map((option) => (
                    <button
                      key={option.id}
                      type="button"
                      className="flex w-full flex-col gap-0.5 px-3 py-2 text-left hover:bg-slate-100"
                      onClick={() => handleSelectCompany(option)}
                    >
                      <span className="font-medium text-slate-800">{option.name}</span>
                      <span className="text-xs text-slate-500">{option.slug}</span>
                    </button>
                  ))}
                </div>
              ) : company.trim().length >= 2 ? (
                <p className="text-xs text-slate-500">Empresa não encontrada — criaremos automaticamente ao registrar.</p>
              ) : (
                <p className="text-xs text-slate-500">Pode informar o nome completo que transformamos no slug registrado.</p>
              )}
            </div>
            <div className="grid gap-2">
              <label className="text-sm font-medium">Perfil de acesso</label>
              <select
                className="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm"
                value={accessRole}
                onChange={(e) => setAccessRole((e.target.value as "collaborator" | "manager") ?? "collaborator")}
              >
                <option value="collaborator">Colaborador (portal)</option>
                <option value="manager">Gestor (painel completo)</option>
              </select>
              <p className="text-xs text-slate-500">
                Colaboradores veem apenas seus chamados. Gestores acompanham todos os tickets da empresa.
              </p>
            </div>
            <div className="grid gap-2">
              <label className="text-sm font-medium">
                Colaborador (e-mail) <span className="text-rose-500">*</span>
              </label>
              <input className="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm" placeholder="colaborador@empresa.com" value={collabEmail} onChange={(e)=>setCollabEmail(e.target.value)} />
            </div>
            <div className="grid gap-2">
              <label className="text-sm font-medium">Nome do colaborador <span className="text-rose-500">*</span></label>
              <input className="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm" placeholder="Nome completo" value={collabName} onChange={(e)=>setCollabName(e.target.value)} />
            </div>
            <div className="grid gap-2">
              <label className="text-sm font-medium">Tenant (opcional)</label>
              <input className="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm" placeholder="tenant-atlas" value={tenantId} onChange={(e)=>setTenantId(e.target.value)} />
            </div>
            {profile ? (
              <div className="mt-2 grid grid-cols-2 gap-2 rounded-lg border border-slate-200 bg-slate-50 p-3 text-xs">
                <div>
                  <div className="text-slate-500">Hostname</div>
                  <div className="font-medium text-slate-900">{profile.hostname}</div>
                </div>
                <div>
                  <div className="text-slate-500">Sistema</div>
                  <div className="font-medium text-slate-900">{profile.os.name}</div>
                </div>
                <div>
                  <div className="text-slate-500">CPU</div>
                  <div className="font-medium text-slate-900">{pct(profile.metrics.cpuUsagePercent)}</div>
                </div>
                <div>
                  <div className="text-slate-500">Memória</div>
                  <div className="font-medium text-slate-900">{bytes(profile.metrics.memoryUsedBytes)} / {bytes(profile.metrics.memoryTotalBytes)}</div>
                </div>
              </div>
            ) : null}
            <div className="mt-2 flex gap-2">
              <button disabled={busy} onClick={register} className="rounded-lg border border-black bg-black px-3 py-2 text-sm font-semibold text-white hover:bg-black/90 disabled:opacity-60">Registrar máquina</button>
            </div>
          </div>
        ) : (
          <div className="mt-4">
            <Tabs defaultValue="resumo" className="w-full">
              <TabsList className="h-10">
                <TabsTrigger value="resumo" className="rounded-lg px-3">Resumo</TabsTrigger>
                <TabsTrigger value="inventario" className="rounded-lg px-3">Inventário</TabsTrigger>
                <TabsTrigger value="diagnostico" className="rounded-lg px-3">Diagnóstico</TabsTrigger>
                <TabsTrigger value="config" className="rounded-lg px-3">Configurações</TabsTrigger>
              </TabsList>
              <TabsContent value="resumo" className="mt-4">
                <div className="grid gap-3 sm:grid-cols-2">
                  <div className="stat-card">
                    <div className="text-xs text-slate-500">CPU</div>
                    <div className="text-sm font-semibold text-slate-900">{profile ? pct(profile.metrics.cpuUsagePercent) : "—"}</div>
                  </div>
                  <div className="stat-card">
                    <div className="text-xs text-slate-500">Memória</div>
                    <div className="text-sm font-semibold text-slate-900">{profile ? `${bytes(profile.metrics.memoryUsedBytes)} / ${bytes(profile.metrics.memoryTotalBytes)}` : "—"}</div>
                  </div>
                </div>
                <div className="mt-4 flex gap-2">
                  <button onClick={openSystem} className="btn btn-primary inline-flex items-center gap-2">
                    <ExternalLink className="size-4"/> Abrir sistema
                  </button>
                  <button onClick={reprovision} className="btn btn-outline">Reprovisionar</button>
                </div>
              </TabsContent>
              <TabsContent value="inventario" className="mt-4 space-y-3">
                <p className="text-sm text-slate-600">Inventário básico coletado localmente. Envie para sincronizar com o servidor.</p>
                <div className="grid gap-2 sm:grid-cols-2">
                  <div className="card">
                    <div className="text-xs text-slate-500">Hostname</div>
                    <div className="text-sm font-semibold text-slate-900">{profile?.hostname ?? "—"}</div>
                  </div>
                  <div className="card">
                    <div className="text-xs text-slate-500">Sistema</div>
                    <div className="text-sm font-semibold text-slate-900">{profile?.os?.name ?? "—"} {profile?.os?.version ?? ""}</div>
                  </div>
                </div>
                <div className="flex gap-2">
                  <button disabled={busy} onClick={sendInventoryNow} className={cn("btn btn-primary", busy && "opacity-60")}>Enviar inventário agora</button>
                  <button onClick={openSystem} className="btn btn-outline">Ver no sistema</button>
                </div>
              </TabsContent>
              <TabsContent value="diagnostico" className="mt-4 space-y-2">
                <div className="card">
                  <p className="text-sm text-slate-700">Token armazenado: <span className="font-mono break-all text-xs">{token?.slice(0, 6)}…{token?.slice(-6)}</span></p>
                  <p className="text-sm text-slate-700">Base URL: <span className="font-mono text-xs">{apiBaseUrl}</span></p>
                </div>
              </TabsContent>
              <TabsContent value="config" className="mt-4 space-y-3">
                <div className="grid gap-2">
              <label className="label">
                E-mail do colaborador <span className="text-rose-500">*</span>
              </label>
                  <input className="input" placeholder="colaborador@empresa.com" value={collabEmail} onChange={(e)=>setCollabEmail(e.target.value)} />
                </div>
                <div className="grid gap-2">
                  <label className="label">Nome do colaborador (opcional)</label>
                  <input className="input" placeholder="Nome completo" value={collabName} onChange={(e)=>setCollabName(e.target.value)} />
                </div>
                <div className="grid gap-2">
                  <label className="label">Atualizações</label>
                  <button
                    onClick={() => checkForUpdates(false)}
                    disabled={updating}
                    className={cn("btn btn-outline inline-flex items-center gap-2", updating && "opacity-60")}
                  >
                    <RefreshCw className={cn("size-4", updating && "animate-spin")} /> Verificar atualizações
                  </button>
                  {updateInfo ? (
                    <div
                      className={cn(
                        "rounded-lg border px-3 py-2 text-sm leading-snug",
                        updateInfo.tone === "success" && "border-emerald-200 bg-emerald-50 text-emerald-700",
                        updateInfo.tone === "error" && "border-rose-200 bg-rose-50 text-rose-700",
                        updateInfo.tone === "info" && "border-slate-200 bg-slate-50 text-slate-700"
                      )}
                    >
                      {updateInfo.message}
                    </div>
                  ) : null}
                </div>
              </TabsContent>
            </Tabs>
          </div>
        )}
      </div>
      <div className="mt-6 flex justify-center">
        <img src={`${appUrl}/raven.png`} alt="Logotipo Raven" width={110} height={110} className="h-[3.45rem] w-auto" />
      </div>
    </div>
  )
}

function StatusBadge({ status }: { status: string | null }) {
  const s = (status ?? "").toLowerCase()
  const label = s === "online" ? "Online" : s === "offline" ? "Offline" : s === "maintenance" ? "Manutenção" : "Sem status"
  const dot = s === "online" ? "bg-emerald-500" : s === "offline" ? "bg-rose-500" : s === "maintenance" ? "bg-amber-500" : "bg-slate-400"
  const ring = s === "online" ? "bg-emerald-400/30" : s === "offline" ? "bg-rose-400/30" : s === "maintenance" ? "bg-amber-400/30" : "bg-slate-300/30"
  const isOnline = s === "online"
  return (
    <span className="inline-flex h-8 items-center gap-4 rounded-full border border-slate-200 px-3 text-sm font-semibold">
      <span className="relative inline-flex items-center">
        <span className={cn("size-2 rounded-full", dot)} />
        {isOnline ? <span className={cn("absolute left-1/2 top-1/2 size-4 -translate-x-1/2 -translate-y-1/2 rounded-full animate-ping [animation-duration:2s]", ring)} /> : null}
      </span>
      {label}
    </span>
  )
}

const root = document.getElementById("root") || (() => { const el = document.createElement("div"); el.id = "root"; document.body.appendChild(el); return el })()
createRoot(root).render(<App />)
  // DevTools shortcut (F12 / Ctrl+Shift+I) and context menu with modifier
  useEffect(() => {
    function onKeyDown(e: KeyboardEvent) {
      const key = (e.key || '').toLowerCase()
      if (key === 'f12' || (e.ctrlKey && e.shiftKey && key === 'i')) {
        invoke('open_devtools').catch(() => {})
        e.preventDefault()
      }
    }
    function onContextMenu(e: MouseEvent) {
      // Evita abrir sempre: use Ctrl ou Shift + botão direito para abrir DevTools
      if (e.ctrlKey || e.shiftKey) {
        invoke('open_devtools').catch(() => {})
        e.preventDefault()
      }
    }
    window.addEventListener('keydown', onKeyDown)
    window.addEventListener('contextmenu', onContextMenu)
    return () => {
      window.removeEventListener('keydown', onKeyDown)
      window.removeEventListener('contextmenu', onContextMenu)
    }
  }, [])
