/* 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 { listen } from "@tauri-apps/api/event"
import { Store } from "@tauri-apps/plugin-store"
import { appLocalDataDir, join } from "@tauri-apps/api/path"
import { ExternalLink, Eye, EyeOff, Loader2, RefreshCw } from "lucide-react"
import { ConvexReactClient } from "convex/react"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "./components/ui/tabs"
import { cn } from "./lib/utils"
import { ChatApp } from "./chat"
import { DeactivationScreen } from "./components/DeactivationScreen"
import { MachineStateMonitor } from "./components/MachineStateMonitor"
import { api } from "./convex/_generated/api"
import type { Id } from "./convex/_generated/dataModel"
import type { SessionStartedEvent, UnreadUpdateEvent, NewMessageEvent, SessionEndedEvent } from "./chat/types"

// URL do Convex para subscription em tempo real
const CONVEX_URL = import.meta.env.MODE === "production"
  ? "https://convex.esdrasrenan.com.br"
  : (import.meta.env.VITE_CONVEX_URL ?? "https://convex.esdrasrenan.com.br")

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 AgentConfig = {
  machineId: string
  tenantId?: string | null
  companySlug?: string | null
  companyName?: string | null
  machineEmail?: string | null
  collaboratorEmail?: string | null
  collaboratorName?: string | null
  provisioningCode?: 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
}

type RustdeskProvisioningResult = {
  id: string
  password: string
  installedVersion?: string | null
  updated: boolean
  lastProvisionedAt: number
}

type RustdeskInfo = RustdeskProvisioningResult & {
  lastSyncedAt?: number | null
  lastError?: string | null
}

const RUSTDESK_STORE_KEY = "rustdesk"

declare global {
  interface ImportMetaEnv {
    readonly VITE_APP_URL?: string
    readonly VITE_API_BASE_URL?: string
    readonly VITE_RUSTDESK_CONFIG_STRING?: string
    readonly VITE_RUSTDESK_DEFAULT_PASSWORD?: 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"

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)
const RUSTDESK_CONFIG_STRING = import.meta.env.VITE_RUSTDESK_CONFIG_STRING?.trim() || null
const RUSTDESK_DEFAULT_PASSWORD = import.meta.env.VITE_RUSTDESK_DEFAULT_PASSWORD?.trim() || null

const TOKEN_SELF_HEAL_DEBOUNCE_MS = 30 * 1000

function sanitizeEmail(value: string | null | undefined) {
  const trimmed = (value ?? "").trim().toLowerCase()
  return trimmed || null
}

function isTokenRevokedMessage(input: string) {
  const normalized = input.toLowerCase()
  return (
    normalized.includes("token de dispositivo revogado") ||
    normalized.includes("token de dispositivo inválido") ||
    normalized.includes("token de dispositivo expirado")
  )
}

function formatApiError(responseText: string, statusCode: number): string {
  try {
    const json = JSON.parse(responseText)
    if (json.error === "Payload invalido" || json.error === "Payload inválido") {
      const details = typeof json.details === "string" ? JSON.parse(json.details) : json.details
      if (Array.isArray(details) && details.length > 0) {
        const fieldLabels: Record<string, string> = {
          "collaborator.email": "E-mail",
          "collaborator.name": "Nome",
          email: "E-mail",
          name: "Nome",
          provisioningCode: "Código de ativação",
          hostname: "Nome do computador",
        }
        const messages: string[] = []
        for (const err of details) {
          const path = Array.isArray(err.path) ? err.path.join(".") : String(err.path ?? "")
          const fieldLabel = fieldLabels[path] || path || "Campo"
          if (err.code === "invalid_format" && err.format === "email") {
            messages.push(`${fieldLabel}: formato de e-mail inválido`)
          } else if (err.code === "invalid_format") {
            messages.push(`${fieldLabel}: formato inválido`)
          } else if (err.code === "too_small" || err.code === "too_short") {
            messages.push(`${fieldLabel}: muito curto`)
          } else if (err.code === "too_big" || err.code === "too_long") {
            messages.push(`${fieldLabel}: muito longo`)
          } else if (err.code === "invalid_type") {
            messages.push(`${fieldLabel}: valor inválido`)
          } else if (err.message) {
            messages.push(`${fieldLabel}: ${err.message}`)
          } else {
            messages.push(`${fieldLabel}: erro de validação`)
          }
        }
        if (messages.length > 0) {
          return messages.join("\n")
        }
      }
    }
    if (json.error) {
      return json.error
    }
  } catch {
    // Não é JSON, retorna o texto original
  }
  return `Erro no servidor (${statusCode})`
}

function buildRemoteAccessPayload(info: RustdeskInfo | null) {
  if (!info) return null
  const payload: Record<string, string | undefined> = {
    provider: "RustDesk",
    identifier: info.id,
    url: `rustdesk://${info.id}`,
    password: info.password,
  }
  if (info.installedVersion) {
    payload.notes = `RustDesk ${info.installedVersion}`
  }
  return payload
}

function buildRemoteAccessSnapshot(info: RustdeskInfo | null) {
  const payload = buildRemoteAccessPayload(info)
  if (!payload) return null
  return {
    ...payload,
    lastVerifiedAt: Date.now(),
    metadata: {
      source: "raven-desktop",
      version: info?.installedVersion ?? null,
    },
  }
}

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

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()
}

async function readRustdeskInfo(store: Store): Promise<RustdeskInfo | null> {
  return (await store.get<RustdeskInfo>(RUSTDESK_STORE_KEY)) ?? null
}

async function writeRustdeskInfo(store: Store, info: RustdeskInfo): Promise<void> {
  await store.set(RUSTDESK_STORE_KEY, info)
  await store.save()
}

function logDesktop(message: string, data?: Record<string, unknown>) {
  const enriched = data ? `${message} ${JSON.stringify(data)}` : message
  const line = `[raven] ${enriched}`
  console.log(line)
  // Persiste em arquivo local para facilitar debugging fora do console
  invoke("log_app_event", { message: line }).catch(() => {})
}

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)}%` }

type MachineStatePayload = {
  isActive?: boolean | null
  metadata?: Record<string, unknown> | null
}

function extractActiveFromMetadata(metadata: unknown): boolean {
  if (!metadata || typeof metadata !== "object") return true
  const record = metadata as Record<string, unknown>
  const direct = record["isActive"]
  if (typeof direct === "boolean") return direct
  const state = record["state"]
  if (state && typeof state === "object") {
    const nested = state as Record<string, unknown>
    const active = nested["isActive"] ?? nested["active"] ?? nested["enabled"]
    if (typeof active === "boolean") return active
  }
  const flags = record["flags"]
  if (flags && typeof flags === "object") {
    const nested = flags as Record<string, unknown>
    const active = nested["isActive"] ?? nested["active"]
    if (typeof active === "boolean") return active
  }
  const status = record["status"]
  if (typeof status === "string") {
    const normalized = status.trim().toLowerCase()
    if (["deactivated", "desativada", "desativado", "inactive", "inativo", "disabled"].includes(normalized)) {
      return false
    }
  }
  return true
}

function resolveMachineActive(machine?: MachineStatePayload | null): boolean {
  if (!machine) return true
  if (typeof machine.isActive === "boolean") return machine.isActive
  return extractActiveFromMetadata(machine.metadata)
}

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 [logoSrc, setLogoSrc] = useState<string>("/logo-raven.png")
  const [error, setError] = useState<string | null>(null)
  const [busy, setBusy] = useState(false)
  const [status, setStatus] = useState<string | null>(null)
  const [isMachineActive, setIsMachineActive] = useState(true)
  const [showSecret, setShowSecret] = useState(false)
  const [isLaunchingSystem, setIsLaunchingSystem] = useState(false)
  const [tokenValidationTick, setTokenValidationTick] = useState(0)
  const [, setIsValidatingToken] = useState(false)
  const tokenVerifiedRef = useRef(false)
  const [rustdeskInfo, setRustdeskInfo] = useState<RustdeskInfo | null>(null)
  const [isRustdeskProvisioning, setIsRustdeskProvisioning] = useState(false)
  const rustdeskBootstrapRef = useRef(false)
  const rustdeskInfoRef = useRef<RustdeskInfo | null>(null)
  const selfHealPromiseRef = useRef<Promise<boolean> | null>(null)
  const lastHealAtRef = useRef(0)

  // Cliente Convex para monitoramento em tempo real do estado da maquina
  const [convexClient, setConvexClient] = useState<ConvexReactClient | null>(null)

  const [provisioningCode, setProvisioningCode] = useState("")
  const [validatedCompany, setValidatedCompany] = useState<{ id: string; name: string; slug: string; tenantId: string } | null>(null)
  const [companyName, setCompanyName] = useState("")
  const [isValidatingCode, setIsValidatingCode] = useState(false)
  const [codeStatus, setCodeStatus] = useState<{ tone: "success" | "error"; message: string } | null>(null)
  const [collabEmail, setCollabEmail] = useState("")
  const [collabName, setCollabName] = useState("")
  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)
  const logoFallbackRef = useRef(false)
  const emailRegex = useRef(/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/i)
  const isEmailValid = useMemo(() => emailRegex.current.test(collabEmail.trim()), [collabEmail])


  const ensureProfile = useCallback(async () => {
    if (profile) return profile
    const fresh = await invoke<MachineProfile>("collect_machine_profile")
    setProfile(fresh)
    return fresh
  }, [profile])

  const persistRegistration = useCallback(
    async (
      data: MachineRegisterResponse,
      opts: {
        collaborator: { email: string; name?: string | null }
        provisioningCode: string
        company?: { name?: string | null; slug?: string | null; tenantId?: string | null }
      }
    ) => {
      if (!store) throw new Error("Store não carregado")
      const resolvedEmail = sanitizeEmail(opts.collaborator.email)
      if (!resolvedEmail) {
        throw new Error("Informe o e-mail do colaborador para concluir o registro")
      }
      const collaboratorNameNormalized = opts.collaborator.name?.trim() || null
      const companyCtx = opts.company ?? {
        name: config?.companyName ?? null,
        slug: config?.companySlug ?? null,
        tenantId: config?.tenantId ?? null,
      }
      await writeToken(store, data.machineToken)
      setToken(data.machineToken)

      const nextConfig: AgentConfig = {
        machineId: data.machineId,
        tenantId: data.tenantId ?? companyCtx?.tenantId ?? config?.tenantId ?? null,
        companySlug: data.companySlug ?? companyCtx?.slug ?? config?.companySlug ?? null,
        companyName: companyCtx?.name ?? config?.companyName ?? companyName ?? null,
        machineEmail: data.machineEmail ?? null,
        collaboratorEmail: resolvedEmail,
        collaboratorName: collaboratorNameNormalized,
        provisioningCode: opts.provisioningCode,
        accessRole: (data.persona ?? config?.accessRole ?? "collaborator").toLowerCase() === "manager" ? "manager" : "collaborator",
        assignedUserId: data.assignedUserId ?? null,
        assignedUserEmail: data.collaborator?.email ?? resolvedEmail,
        assignedUserName: data.collaborator?.name ?? collaboratorNameNormalized,
        apiBaseUrl,
        appUrl,
        createdAt: config?.createdAt ?? Date.now(),
        lastSyncedAt: Date.now(),
        expiresAt: data.expiresAt ?? null,
        heartbeatIntervalSec: config?.heartbeatIntervalSec ?? null,
      }

      setConfig(nextConfig)
      setCompanyName(nextConfig.companyName ?? "")
      setCollabEmail(resolvedEmail)
      setCollabName(collaboratorNameNormalized ?? "")
      setProvisioningCode(opts.provisioningCode)
      await writeConfig(store, nextConfig)

      tokenVerifiedRef.current = true
      setStatus("online")
      setIsMachineActive(true)
      setTokenValidationTick((tick) => tick + 1)

      try {
        await invoke("start_machine_agent", {
          baseUrl: apiBaseUrl,
          token: data.machineToken,
          status: "online",
          intervalSeconds: nextConfig.heartbeatIntervalSec ?? 300,
        })
        // Iniciar sistema de chat apos o agente
        await invoke("start_chat_polling", {
          base_url: apiBaseUrl,
          convex_url: "https://convex.esdrasrenan.com.br",
          token: data.machineToken,
        })
        logDesktop("chat:started")
      } catch (err) {
        console.error("Falha ao reiniciar heartbeat/chat", err)
      }

      return nextConfig
    },
    [store, config, companyName]
  )

  const reRegisterMachine = useCallback(
    async (context: string) => {
      if (!store) return false
      const storedCode = (config?.provisioningCode ?? provisioningCode).trim().toLowerCase()
      if (!storedCode) {
        console.warn("[self-heal] Provisioning code absent; manual intervention required")
        setError("Código de provisionamento ausente. Informe-o novamente para concluir o processo.")
        return false
      }

      const collaboratorEmail = sanitizeEmail(collabEmail) ?? config?.collaboratorEmail ?? config?.assignedUserEmail ?? null
      if (!collaboratorEmail) {
        console.warn("[self-heal] Collaborator email missing")
        setError("Informe o e-mail do colaborador vinculado a esta dispositivo para continuar.")
        return false
      }
      const collaboratorName = collabName.trim() || config?.collaboratorName || config?.assignedUserName || null

      let machineProfile: MachineProfile
      try {
        machineProfile = await ensureProfile()
      } catch (profileError) {
        console.error("[self-heal] Falha ao coletar perfil", profileError)
        setError("Não foi possível coletar os dados da dispositivo para reprovisionar. Reabra o app como administrador.")
        return false
      }

      const metadataPayload: Record<string, unknown> = {
        inventory: machineProfile.inventory,
        metrics: machineProfile.metrics,
        collaborator: {
          email: collaboratorEmail,
          name: collaboratorName,
          role: config?.accessRole ?? "collaborator",
        },
      }
      const snapshot = buildRemoteAccessSnapshot(rustdeskInfoRef.current)
      if (snapshot) {
        metadataPayload.remoteAccessSnapshot = snapshot
      }

      const body = {
        provisioningCode: storedCode,
        hostname: machineProfile.hostname,
        os: machineProfile.os,
        macAddresses: machineProfile.macAddresses,
        serialNumbers: machineProfile.serialNumbers,
        metadata: metadataPayload,
        collaborator: {
          email: collaboratorEmail,
          name: collaboratorName ?? undefined,
        },
        registeredBy: "desktop-agent",
      }

      try {
        const res = await fetch(`${apiBaseUrl}/api/machines/register`, {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(body),
        })
        if (!res.ok) {
          const text = await res.text()
          console.error(`[self-heal] Reprovision failed (${context})`, text)
          setError("Falha ao reprovisionar automaticamente. Revise o código e tente novamente.")
          return false
        }
        const data = (await res.json()) as MachineRegisterResponse
        await persistRegistration(data, {
          collaborator: { email: collaboratorEmail, name: collaboratorName },
          provisioningCode: storedCode,
          company: {
            name: config?.companyName ?? validatedCompany?.name ?? null,
            slug: config?.companySlug ?? validatedCompany?.slug ?? null,
            tenantId: config?.tenantId ?? validatedCompany?.tenantId ?? null,
          },
        })
        console.info(`[self-heal] Token regenerado (${context})`)
        return true
      } catch (error) {
        console.error(`[self-heal] Erro inesperado (${context})`, error)
        setError("Não foi possível reprovisionar automaticamente. Verifique a conexão e tente novamente.")
        return false
      }
    },
    [store, config, provisioningCode, collabEmail, collabName, ensureProfile, persistRegistration, validatedCompany]
  )

  const attemptSelfHeal = useCallback(
    async (context: string) => {
      if (!store) return false
      if (selfHealPromiseRef.current) {
        return selfHealPromiseRef.current
      }
      const elapsed = Date.now() - lastHealAtRef.current
      if (elapsed < TOKEN_SELF_HEAL_DEBOUNCE_MS && lastHealAtRef.current !== 0) {
        return false
      }
      const promise = reRegisterMachine(context).finally(() => {
        selfHealPromiseRef.current = null
        lastHealAtRef.current = Date.now()
      })
      selfHealPromiseRef.current = promise
      return promise
    },
    [store, reRegisterMachine]
  )

  useEffect(() => {
    (async () => {
      try {
        const s = await loadStore()
        setStore(s)
        const t = await readToken(s)
        setToken(t)
        const cfg = await readConfig(s)
        setConfig(cfg)
        const existingRustdesk = await readRustdeskInfo(s)
        setRustdeskInfo(existingRustdesk)
        if (cfg?.collaboratorEmail) setCollabEmail(cfg.collaboratorEmail)
        if (cfg?.collaboratorName) setCollabName(cfg.collaboratorName)
        if (cfg?.companyName) setCompanyName(cfg.companyName)
        if (!t) {
          const p = await invoke<MachineProfile>("collect_machine_profile")
          setProfile(p)
        }
        // Não assume online sem validar; valida abaixo em outro efeito
      } catch {
        setError("Falha ao carregar estado do agente.")
        logDesktop("store-load:error")
      }
    })()
  }, [])

  // Valida token existente ao iniciar o app. Se inválido/expirado, limpa e volta ao onboarding.
  useEffect(() => {
    if (!store || !token) return
    let cancelled = false
    ;(async () => {
      setIsValidatingToken(true)
      try {
        const snapshot = buildRemoteAccessSnapshot(rustdeskInfoRef.current)
        const heartbeatPayload: Record<string, unknown> = {
          machineToken: token,
          status: "online",
        }
        if (snapshot) {
          heartbeatPayload.metadata = { remoteAccessSnapshot: snapshot }
        }
        const res = await fetch(`${apiBaseUrl}/api/machines/heartbeat`, {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(heartbeatPayload),
        })
        logDesktop("heartbeat:sent", { ok: res.ok, status: res.status })
        if (cancelled) return
        if (res.ok) {
          tokenVerifiedRef.current = true
          setStatus("online")
          setTokenValidationTick((tick) => tick + 1)
          try {
            await invoke("start_machine_agent", {
              baseUrl: apiBaseUrl,
              token,
              status: "online",
              intervalSeconds: 300,
            })
            // Iniciar sistema de chat apos o agente
            await invoke("start_chat_polling", {
              base_url: apiBaseUrl,
              convex_url: "https://convex.esdrasrenan.com.br",
              token,
            })
            logDesktop("chat:started:validation")
          } catch (err) {
            console.error("Falha ao iniciar heartbeat/chat em segundo plano", err)
          }
          const payload = await res.clone().json().catch(() => null)
          if (payload && typeof payload === "object" && "machine" in payload) {
            const machineData = (payload as { machine?: MachineStatePayload }).machine
            if (machineData) {
              const currentActive = resolveMachineActive(machineData)
              setIsMachineActive(currentActive)
            }
          }
          return
        }
        const text = await res.text()
        const msg = text.toLowerCase()
        const isInvalid =
          msg.includes("token de dispositivo inválido") ||
          msg.includes("token de dispositivo revogado") ||
          msg.includes("token de dispositivo expirado")
        if (isInvalid) {
          const healed = await attemptSelfHeal("heartbeat")
          if (cancelled) return
          if (healed) {
            logDesktop("heartbeat:selfheal:success")
            setStatus("online")
            return
          }
          try {
            await store.delete("token"); await store.delete("config"); await store.save()
          } catch {}
          autoLaunchRef.current = false
          tokenVerifiedRef.current = false
          setToken(null)
          setConfig(null)
          setStatus(null)
          setIsMachineActive(true)
          setError("Este dispositivo precisa ser reprovisionado. Informe o código de provisionamento.")
          try {
            const p = await invoke<MachineProfile>("collect_machine_profile")
            if (!cancelled) setProfile(p)
          } catch {}
        } else {
          // Não limpa token em falhas genéricas (ex.: rede); apenas informa
          setError("Falha ao validar sessão da dispositivo. Tente novamente.")
          tokenVerifiedRef.current = true
          setTokenValidationTick((tick) => tick + 1)
        }
      } catch (err) {
        if (!cancelled) {
          console.error("Falha ao validar token (rede)", err)
          logDesktop("heartbeat:error", { message: err instanceof Error ? err.message : String(err) })
          tokenVerifiedRef.current = true
          setTokenValidationTick((tick) => tick + 1)
        }
      } finally {
        if (!cancelled) setIsValidatingToken(false)
      }
    })()
    return () => {
      cancelled = true
    }
  }, [store, token, attemptSelfHeal])

useEffect(() => {
  if (!import.meta.env.DEV) return

    function onKeyDown(event: KeyboardEvent) {
      const key = (event.key || "").toLowerCase()
      if (key === "f12" || (event.ctrlKey && event.shiftKey && key === "i")) {
        invoke("open_devtools").catch(() => {})
        event.preventDefault()
      }
    }

    function onContextMenu(event: MouseEvent) {
      if (event.ctrlKey || event.shiftKey) {
        invoke("open_devtools").catch(() => {})
        event.preventDefault()
      }
    }

    window.addEventListener("keydown", onKeyDown)
    window.addEventListener("contextmenu", onContextMenu)
    return () => {
      window.removeEventListener("keydown", onKeyDown)
      window.removeEventListener("contextmenu", onContextMenu)
    }
}, [])

useEffect(() => {
  rustdeskInfoRef.current = rustdeskInfo
}, [rustdeskInfo])

// Cria/destrói cliente Convex quando o token muda
useEffect(() => {
  if (!token) {
    if (convexClient) {
      convexClient.close()
      setConvexClient(null)
    }
    return
  }

  // Cria novo cliente Convex para monitoramento em tempo real
  const client = new ConvexReactClient(CONVEX_URL, {
    unsavedChangesWarning: false,
  })
  setConvexClient(client)

  return () => {
    client.close()
  }
}, [token]) // eslint-disable-line react-hooks/exhaustive-deps

// Callbacks para quando a máquina for desativada, resetada ou reativada
const handleMachineDeactivated = useCallback(() => {
  console.log("[App] Máquina foi desativada - mostrando tela de bloqueio")
  setIsMachineActive(false)
}, [])

const handleMachineReactivated = useCallback(() => {
  console.log("[App] Máquina foi reativada - liberando acesso")
  setIsMachineActive(true)
}, [])

// Callback para o botão "Verificar novamente" na tela de desativação
// Usa o convexClient diretamente para fazer uma query manual
const handleRetryCheck = useCallback(async () => {
  if (!convexClient || !config?.machineId) return
  console.log("[App] Verificando estado da máquina manualmente...")
  try {
    const state = await convexClient.query(api.machines.getMachineState, {
      machineId: config.machineId as Id<"machines">,
    })
    console.log("[App] Estado da máquina:", state)
    if (state?.isActive) {
      console.log("[App] Máquina ativa - liberando acesso")
      setIsMachineActive(true)
    }
  } catch (err) {
    console.error("[App] Erro ao verificar estado:", err)
  }
}, [convexClient, config?.machineId])

const handleTokenRevoked = useCallback(async () => {
  console.log("[App] Token foi revogado - voltando para tela de registro")
  if (store) {
    try {
      await store.delete("token")
      await store.delete("config")
      await store.save()
    } catch (err) {
      console.error("Falha ao limpar store", err)
    }
  }
  tokenVerifiedRef.current = false
  autoLaunchRef.current = false
  setToken(null)
  setConfig(null)
  setStatus(null)
  setIsMachineActive(true)
  setError("Este dispositivo foi resetado. Informe o código de provisionamento para reconectar.")
  try {
    const p = await invoke<MachineProfile>("collect_machine_profile")
    setProfile(p)
  } catch {}
}, [store])

  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
    ) {
      return
    }
    const nextConfig: AgentConfig = {
      ...config,
      collaboratorEmail: normalizedEmail,
      collaboratorName: normalizedName,
    }
    setConfig(nextConfig)
    writeConfig(store, nextConfig)
      .then(() => logDesktop("config:update:collaborator", { email: normalizedEmail }))
      .catch((err) => console.error("Falha ao atualizar colaborador", err))
  }, [store, config, config?.collaboratorEmail, config?.collaboratorName, collabEmail, collabName])

  useEffect(() => {
    if (!config?.provisioningCode) return
    if (provisioningCode.trim()) return
    setProvisioningCode(config.provisioningCode)
  }, [config?.provisioningCode, provisioningCode])

  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)
        .then(() => logDesktop("config:update:url"))
        .catch((err) => console.error("Falha ao atualizar configuração", err))
    }
  }, [store, config])

  useEffect(() => {
    const trimmed = provisioningCode.trim()
    if (trimmed.length < 32) {
      setValidatedCompany(null)
      setCodeStatus(null)
      setCompanyName("")
      return
    }
    let cancelled = false
    const controller = new AbortController()
    const timeout = setTimeout(async () => {
      setIsValidatingCode(true)
      try {
        const res = await fetch(`${apiBaseUrl}/api/machines/provisioning`, {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ provisioningCode: trimmed }),
          signal: controller.signal,
        })
        if (!res.ok) {
          const message = res.status === 404 ? "Código não encontrado" : "Falha ao validar código"
          if (!cancelled) {
            setValidatedCompany(null)
            setCompanyName("")
            setCodeStatus({ tone: "error", message })
          }
          return
        }
        const data = (await res.json()) as { company: { id: string; name: string; slug: string; tenantId: string } }
        if (!cancelled) {
          setValidatedCompany(data.company)
          setCompanyName(data.company.name)
          setCodeStatus({ tone: "success", message: `Empresa encontrada: ${data.company.name}` })
        }
      } catch (error) {
        if (!cancelled) {
          console.error("Falha ao validar código de provisionamento", error)
          setValidatedCompany(null)
          setCompanyName("")
          setCodeStatus({ tone: "error", message: "Não foi possível validar o código agora" })
        }
      } finally {
        if (!cancelled) setIsValidatingCode(false)
      }
    }, 400)
    return () => {
      cancelled = true
      clearTimeout(timeout)
      controller.abort()
      setIsValidatingCode(false)
    }
  }, [provisioningCode])

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])

  // Funcao simplificada de sync - sempre le do disco para evitar race conditions
  const syncRemoteAccessDirect = useCallback(
    async (info: RustdeskInfo, allowRetry = true): Promise<boolean> => {
      try {
        // Sempre le do disco para evitar race conditions com state React
        const freshStore = await loadStore()
        const freshConfig = await readConfig(freshStore)
        const freshToken = await readToken(freshStore)

        if (!freshConfig?.machineId || !freshToken) {
          logDesktop("remoteAccess:sync:skip", {
            hasMachineId: !!freshConfig?.machineId,
            hasToken: !!freshToken,
          })
          return false
        }

        const payload = buildRemoteAccessPayload(info)
        if (!payload) return false

        logDesktop("remoteAccess:sync:start", { id: info.id })

        const response = await fetch(`${apiBaseUrl}/api/machines/remote-access`, {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            "Idempotency-Key": `${freshConfig.machineId}:RustDesk:${info.id}`,
          },
          body: JSON.stringify({ machineToken: freshToken, ...payload }),
        })

        if (response.ok) {
          const nextInfo: RustdeskInfo = { ...info, lastSyncedAt: Date.now(), lastError: null }
          await writeRustdeskInfo(freshStore, nextInfo)
          setRustdeskInfo(nextInfo)
          logDesktop("remoteAccess:sync:success", { id: info.id })
          return true
        }

        const errorText = await response.text()
        logDesktop("remoteAccess:sync:error", { status: response.status, error: errorText.slice(0, 200) })

        // Se token invalido, tenta self-heal uma vez
        if (allowRetry && (response.status === 401 || isTokenRevokedMessage(errorText))) {
          const healed = await attemptSelfHeal("remote-access")
          if (healed) {
            return syncRemoteAccessDirect(info, false)
          }
        }

        // Salva erro no store
        const failedInfo: RustdeskInfo = { ...info, lastError: errorText.slice(0, 200) }
        await writeRustdeskInfo(freshStore, failedInfo)
        setRustdeskInfo(failedInfo)
        return false
      } catch (error) {
        const message = error instanceof Error ? error.message : String(error)
        logDesktop("remoteAccess:sync:exception", { error: message })
        return false
      }
    },
    [attemptSelfHeal]
  )

  const handleRustdeskProvision = useCallback(
    async (payload: RustdeskProvisioningResult) => {
      logDesktop("rustdesk:provision:start", { id: payload.id, hasStore: !!store })
      if (!store) {
        logDesktop("rustdesk:provision:skip:no-store")
        return
      }
      const normalized: RustdeskInfo = {
        ...payload,
        installedVersion: payload.installedVersion ?? null,
        lastSyncedAt: rustdeskInfoRef.current?.lastSyncedAt ?? null,
        lastError: null,
      }
      try {
        await writeRustdeskInfo(store, normalized)
        logDesktop("rustdesk:provision:saved", { id: normalized.id })
      } catch (error) {
        logDesktop("rustdesk:provision:save-error", { error: String(error) })
        throw error
      }
      setRustdeskInfo(normalized)

      // Recarrega o config diretamente do store para garantir que temos o machineId mais recente
      // (evita race condition quando register() chama ensureRustdesk antes do state React atualizar)
      const freshStore = await loadStore()
      const freshConfig = await readConfig(freshStore)
      const freshToken = await readToken(freshStore)
      if (!freshConfig?.machineId) {
        logDesktop("rustdesk:provision:sync-skipped", { reason: "no-machineId-in-store" })
        return
      }
      if (!freshToken) {
        logDesktop("rustdesk:provision:sync-skipped", { reason: "no-token-in-store" })
        return
      }

      // Faz o sync diretamente com os dados frescos do store
      try {
        const syncPayload = buildRemoteAccessPayload(normalized)
        if (!syncPayload) {
          logDesktop("rustdesk:provision:sync-skipped", { reason: "invalid-payload" })
          return
        }
        const response = await fetch(`${apiBaseUrl}/api/machines/remote-access`, {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            "Idempotency-Key": `${freshConfig.machineId}:RustDesk:${normalized.id}`,
          },
          body: JSON.stringify({ machineToken: freshToken, ...syncPayload }),
        })
        if (response.ok) {
          const nextInfo: RustdeskInfo = { ...normalized, lastSyncedAt: Date.now(), lastError: null }
          await writeRustdeskInfo(freshStore, nextInfo)
          setRustdeskInfo(nextInfo)
          logDesktop("rustdesk:provision:synced", { id: normalized.id })
        } else {
          const errorText = await response.text().catch(() => "")
          logDesktop("rustdesk:provision:sync-error", { status: response.status, error: errorText.slice(0, 200) })
        }
      } catch (error) {
        logDesktop("rustdesk:provision:sync-error", { error: String(error) })
      }
    },
    [store]
  )

  const ensureRustdesk = useCallback(async () => {
    logDesktop("rustdesk:ensure:start", { hasStore: !!store, machineId: config?.machineId ?? null })
    if (!store) {
      logDesktop("rustdesk:ensure:skip:no-store")
      return null
    }
    if (!config?.machineId) {
      logDesktop("rustdesk:skip:no-machine-id")
      return null
    }
    setIsRustdeskProvisioning(true)
    try {
      logDesktop("rustdesk:ensure:invoking", { machineId: config.machineId })
      const payload = await invoke<RustdeskProvisioningResult>("ensure_rustdesk_and_emit", {
        configString: RUSTDESK_CONFIG_STRING || null,
        password: RUSTDESK_DEFAULT_PASSWORD || null,
        machineId: config.machineId,
      })
      logDesktop("rustdesk:ensure:invoked", { id: payload.id, version: payload.installedVersion })
      await handleRustdeskProvision(payload)
      logDesktop("rustdesk:ensure:complete", { id: payload.id })
      return payload
    } catch (error) {
      const message = error instanceof Error ? error.message : String(error)
      if (message.toLowerCase().includes("apenas no windows")) {
        console.info("Provisionamento do RustDesk ignorado (plataforma não suportada)")
      } else {
        logDesktop("rustdesk:ensure:error", { error: message })
        console.error("Falha ao provisionar RustDesk", error)
      }
      return null
    } finally {
      setIsRustdeskProvisioning(false)
    }
  }, [store, config?.machineId, handleRustdeskProvision])

  useEffect(() => {
    if (!store) return
    let disposed = false
    let unsubscribe: (() => void) | null = null

    listen<RustdeskProvisioningResult>("raven://remote-access/provisioned", async (event) => {
      try {
        await handleRustdeskProvision(event.payload)
      } catch (error) {
        console.error("Falha ao processar evento de provisioning do RustDesk", error)
      }
    })
      .then((unlisten) => {
        if (disposed) {
          unlisten()
        } else {
          unsubscribe = unlisten
        }
      })
      .catch((error) => console.error("Falha ao registrar listener do RustDesk", error))

    return () => {
      disposed = true
      if (unsubscribe) unsubscribe()
    }
  }, [store, handleRustdeskProvision])

  // Bootstrap do RustDesk + retry simplificado (60s)
  useEffect(() => {
    if (!store || !config?.machineId) return

    let disposed = false

    async function bootstrap() {
      // Se nao tem rustdeskInfo, provisiona primeiro
      if (!rustdeskInfo && !isRustdeskProvisioning && !rustdeskBootstrapRef.current) {
        rustdeskBootstrapRef.current = true
        try {
          await ensureRustdesk()
        } finally {
          rustdeskBootstrapRef.current = false
        }
        return // handleRustdeskProvision fara o sync
      }

      // Se ja tem rustdeskInfo mas nunca sincronizou, tenta sync
      if (rustdeskInfo && !rustdeskInfo.lastSyncedAt) {
        logDesktop("remoteAccess:sync:bootstrap", { id: rustdeskInfo.id })
        await syncRemoteAccessDirect(rustdeskInfo)
      }
    }

    bootstrap()

    // Retry a cada 30s se nunca sincronizou (o Rust faz o sync automaticamente)
    const interval = setInterval(async () => {
      if (disposed) return
      try {
        const freshStore = await loadStore()
        const freshRustdesk = await readRustdeskInfo(freshStore)
        if (freshRustdesk && !freshRustdesk.lastSyncedAt) {
          logDesktop("remoteAccess:sync:retry:fallback", { id: freshRustdesk.id })
          // Re-invoca o Rust para tentar sync novamente
          await invoke("ensure_rustdesk_and_emit", {
            configString: RUSTDESK_CONFIG_STRING || null,
            password: RUSTDESK_DEFAULT_PASSWORD || null,
            machineId: config?.machineId,
          })
        }
      } catch (err) {
        logDesktop("remoteAccess:sync:retry:error", { error: String(err) })
      }
    }, 30_000)

    return () => {
      disposed = true
      clearInterval(interval)
    }
  }, [store, config?.machineId, rustdeskInfo, isRustdeskProvisioning, ensureRustdesk, syncRemoteAccessDirect])

  // Listeners de eventos do chat (apenas para logging - a janela nativa e gerenciada pelo Rust)
  useEffect(() => {
    if (!token) return

    let disposed = false
    const unlisteners: Array<() => void> = []

    // Listener para nova sessao de chat
    listen<SessionStartedEvent>("raven://chat/session-started", (event) => {
      if (disposed) return
      logDesktop("chat:session-started", { ticketId: event.payload.session.ticketId, sessionId: event.payload.session.sessionId })
    }).then(unlisten => {
      if (disposed) unlisten()
      else unlisteners.push(unlisten)
    }).catch(err => console.error("Falha ao registrar listener session-started:", err))

    // Listener para sessao encerrada
    listen<SessionEndedEvent>("raven://chat/session-ended", (event) => {
      if (disposed) return
      logDesktop("chat:session-ended", { ticketId: event.payload.ticketId, sessionId: event.payload.sessionId })
    }).then(unlisten => {
      if (disposed) unlisten()
      else unlisteners.push(unlisten)
    }).catch(err => console.error("Falha ao registrar listener session-ended:", err))

    // Listener para atualizacao de mensagens nao lidas
    listen<UnreadUpdateEvent>("raven://chat/unread-update", (event) => {
      if (disposed) return
      logDesktop("chat:unread-update", { totalUnread: event.payload.totalUnread, sessionsCount: event.payload.sessions?.length ?? 0 })
    }).then(unlisten => {
      if (disposed) unlisten()
      else unlisteners.push(unlisten)
    }).catch(err => console.error("Falha ao registrar listener unread-update:", err))

    // Listener para nova mensagem (a janela de chat nativa e aberta automaticamente pelo Rust)
    listen<NewMessageEvent>("raven://chat/new-message", (event) => {
      if (disposed) return
      logDesktop("chat:new-message", { totalUnread: event.payload.totalUnread, newCount: event.payload.newCount })
    }).then(unlisten => {
      if (disposed) unlisten()
      else unlisteners.push(unlisten)
    }).catch(err => console.error("Falha ao registrar listener new-message:", err))

    return () => {
      disposed = true
      unlisteners.forEach(unlisten => unlisten())
    }
  }, [token])

  /* Assinatura direta no Convex para abrir/minimizar chat quando houver novas mensagens
   * (desativada: o Rust ja gerencia realtime via WS e eventos Tauri)
  useEffect(() => {
    if (!token) return

    let prevUnread = 0
    let unsub: (() => void) | null = null
    let disposed = false

    subscribeMachineUpdates(
      (payload) => {
        if (disposed || !payload) return
        const totalUnread = payload.totalUnread ?? 0
        const hasSessions = (payload.sessions ?? []).length > 0

        // Abre/minimiza chat quando aparecem novas não lidas
        if (hasSessions && totalUnread > prevUnread) {
          const session = payload.sessions[0]
          invoke("open_chat_window", { ticketId: session.ticketId, ticketRef: session.ticketRef }).catch(console.error)
          // Minimiza para não ser intrusivo
          invoke("set_chat_minimized", { ticketId: session.ticketId, minimized: true }).catch(console.error)
        }

        prevUnread = totalUnread
      },
      (err) => {
        if (disposed) return
        console.error("chat updates (Convex) erro:", err)
        const msg = (err?.message || "").toLowerCase()
        if (msg.includes("token de máquina") || msg.includes("revogado") || msg.includes("expirado") || msg.includes("inválido")) {
          // Token inválido/expirado no Convex → tenta autoregistrar de novo
          attemptSelfHeal("convex-subscribe").catch(console.error)
        }
      }
    ).then((u) => {
      // Se o effect já foi desmontado antes da Promise resolver, cancelar imediatamente
      if (disposed) {
        u()
      } else {
        unsub = u
      }
    })

    return () => {
      disposed = true
      unsub?.()
    }
  }, [token, attemptSelfHeal])
  */

  async function register() {
    if (!profile) return
    const trimmedCode = provisioningCode.trim().toLowerCase()
    if (trimmedCode.length < 32) {
      setError("Informe o código de provisionamento fornecido pela equipe.")
      return
    }
    if (!validatedCompany) {
      setError("Valide o código de provisionamento antes de registrar a dispositivo.")
      return
    }
    const normalizedEmail = collabEmail.trim().toLowerCase()
    if (!normalizedEmail) {
      setError("Informe o e-mail do colaborador vinculado a esta dispositivo.")
      return
    }
    if (!emailRegex.current.test(normalizedEmail)) {
      setError("Informe um e-mail válido (ex.: nome@empresa.com)")
      return
    }
    const normalizedName = collabName.trim()
    if (!normalizedName) {
      setError("Informe o nome completo do colaborador.")
      return
    }

    setBusy(true)
    setError(null)
    try {
      const collaboratorPayload = {
        email: normalizedEmail,
        name: normalizedName,
      }
      const metadataPayload: Record<string, unknown> = {
        inventory: profile.inventory,
        metrics: profile.metrics,
        collaborator: { email: normalizedEmail, name: normalizedName, role: "collaborator" },
      }
      const bootstrapSnapshot = buildRemoteAccessSnapshot(rustdeskInfoRef.current)
      if (bootstrapSnapshot) {
        metadataPayload.remoteAccessSnapshot = bootstrapSnapshot
      }

      const payload = {
        provisioningCode: trimmedCode,
        hostname: profile.hostname,
        os: profile.os,
        macAddresses: profile.macAddresses,
        serialNumbers: profile.serialNumbers,
        metadata: metadataPayload,
        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(formatApiError(text, res.status))
      }

      const data = (await res.json()) as MachineRegisterResponse
      await persistRegistration(data, {
        collaborator: collaboratorPayload,
        provisioningCode: trimmedCode,
        company: {
          name: validatedCompany.name,
          slug: validatedCompany.slug,
          tenantId: validatedCompany.tenantId,
        },
      })

      // Provisiona RustDesk em background (fire-and-forget)
      // O Rust faz o sync com o backend automaticamente, sem passar pelo CSP do webview
      logDesktop("register:rustdesk:start", { machineId: data.machineId })
      invoke<RustdeskProvisioningResult>("ensure_rustdesk_and_emit", {
        configString: RUSTDESK_CONFIG_STRING || null,
        password: RUSTDESK_DEFAULT_PASSWORD || null,
        machineId: data.machineId,
      }).then((result) => {
        logDesktop("register:rustdesk:done", { machineId: data.machineId, id: result.id })
      }).catch((err) => {
        const msg = err instanceof Error ? err.message : String(err)
        if (!msg.toLowerCase().includes("apenas no windows")) {
          logDesktop("register:rustdesk:error", { error: msg })
        }
      })

      // Redireciona imediatamente (nao espera RustDesk)
      try {
        await fetch(`${apiBaseUrl}/api/machines/sessions`, {
          method: "POST",
          credentials: "include",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ machineToken: data.machineToken, rememberMe: true }),
        })
      } catch {}
      const persona = (data.persona ?? "collaborator").toLowerCase() === "manager" ? "manager" : "collaborator"
      const redirectTarget = persona === "manager" ? "/dashboard" : "/portal/tickets"
      // Proteção extra: nunca usar localhost em produção
      const safeAppUrl = resolvedAppUrl.includes("localhost") ? "https://tickets.esdrasrenan.com.br" : resolvedAppUrl
      const url = `${safeAppUrl}/machines/handshake?token=${encodeURIComponent(data.machineToken)}&redirect=${encodeURIComponent(redirectTarget)}`
      logDesktop("register:redirect", { url: url.replace(/token=[^&]+/, "token=***") })
      window.location.href = url
    } catch (err) {
      setError(err instanceof Error ? err.message : String(err))
    } finally {
      setBusy(false)
    }
  }

  const openSystem = useCallback(async () => {
    if (!token) return
    if (!isMachineActive) {
      setIsLaunchingSystem(false)
      return
    }
    setIsLaunchingSystem(true)

    // Recarrega store do disco para pegar dados que o Rust salvou diretamente
    // e sincroniza RustDesk antes de redirecionar (fire-and-forget com timeout)
    try {
      if (store && config?.machineId) {
        const freshStore = await loadStore()
        const freshRustdesk = await readRustdeskInfo(freshStore)
        if (freshRustdesk && (!freshRustdesk.lastSyncedAt || Date.now() - freshRustdesk.lastSyncedAt > 60000)) {
          logDesktop("openSystem:rustdesk:sync:start", { id: freshRustdesk.id })
          const payload = buildRemoteAccessPayload(freshRustdesk)
          if (payload) {
            const syncPromise = fetch(`${apiBaseUrl}/api/machines/remote-access`, {
              method: "POST",
              headers: {
                "Content-Type": "application/json",
                "Idempotency-Key": `${config.machineId}:RustDesk:${freshRustdesk.id}`,
              },
              body: JSON.stringify({ machineToken: token, ...payload }),
            }).then(async (syncRes) => {
              if (syncRes.ok) {
                logDesktop("openSystem:rustdesk:sync:success", { id: freshRustdesk.id })
                const nextInfo: RustdeskInfo = { ...freshRustdesk, lastSyncedAt: Date.now(), lastError: null }
                await writeRustdeskInfo(freshStore, nextInfo)
                setRustdeskInfo(nextInfo)
              } else {
                logDesktop("openSystem:rustdesk:sync:error", { status: syncRes.status })
              }
            }).catch((err) => {
              logDesktop("openSystem:rustdesk:sync:failed", { error: String(err) })
            })
            // Espera no maximo 3s pelo sync, depois continua
            await Promise.race([syncPromise, new Promise((r) => setTimeout(r, 3000))])
          }
        }
      }
    } catch (syncErr) {
      logDesktop("openSystem:rustdesk:sync:exception", { error: String(syncErr) })
    }

    try {
      // Tenta criar a sessao via API (evita dependencia de redirecionamento + cookies em 3xx)
        const res = await fetch(`${apiBaseUrl}/api/machines/sessions`, {
          method: "POST",
          credentials: "include",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ machineToken: token, rememberMe: true }),
        })
      if (res.ok) {
        const payload = await res.clone().json().catch(() => null)
          if (payload && typeof payload === "object" && "machine" in payload) {
            const machineData = (payload as { machine?: MachineStatePayload }).machine
            if (machineData) {
              const currentActive = resolveMachineActive(machineData)
              setIsMachineActive(currentActive)
              if (currentActive) {
                setError(null)
              }
              if (!currentActive) {
                setIsLaunchingSystem(false)
                return
              }
            }
          }
      } else {
        if (res.status === 423) {
          setIsMachineActive(false)
          setIsLaunchingSystem(false)
          return
        }
        // Se sessão falhar, tenta identificar token inválido/expirado
        try {
          const hb = await fetch(`${apiBaseUrl}/api/machines/heartbeat`, {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ machineToken: token }),
          })
          if (!hb.ok) {
            const text = await hb.text()
            const low = text.toLowerCase()
            const invalid =
              low.includes("token de dispositivo inválido") ||
              low.includes("token de dispositivo revogado") ||
              low.includes("token de dispositivo expirado")
            if (invalid) {
              // Força onboarding
              await store?.delete("token"); await store?.delete("config"); await store?.save()
              autoLaunchRef.current = false
              tokenVerifiedRef.current = false
              setToken(null)
              setConfig(null)
              setStatus(null)
              setIsMachineActive(true)
              setError("Sessão expirada. Reprovisione a dispositivo para continuar.")
              setIsLaunchingSystem(false)
              const p = await invoke<MachineProfile>("collect_machine_profile")
              setProfile(p)
              return
            }
          }
        } catch {
          // ignora e segue para handshake
        }
      }
      // Independente do resultado do POST, seguimos para o handshake em
      // navegação de primeiro plano para garantir gravação de cookies.
    } catch {
      // ignoramos e seguimos para o handshake
    }
    const persona = (config?.accessRole ?? "collaborator") === "manager" ? "manager" : "collaborator"
    // Envia para a página inicial apropriada após autenticar cookies/sessão
    const redirectTarget = persona === "manager" ? "/dashboard" : "/portal/tickets"
    // Proteção extra: nunca usar localhost em produção
    const safeAppUrl = resolvedAppUrl.includes("localhost") ? "https://tickets.esdrasrenan.com.br" : resolvedAppUrl
    const url = `${safeAppUrl}/machines/handshake?token=${encodeURIComponent(token)}&redirect=${encodeURIComponent(redirectTarget)}`
    logDesktop("openSystem:redirect", { url: url.replace(/token=[^&]+/, "token=***") })
    window.location.href = url
  }, [token, config?.accessRole, config?.machineId, resolvedAppUrl, store, isMachineActive])

  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)
    setProvisioningCode("")
    setValidatedCompany(null)
    setCodeStatus(null)
    setCompanyName("")
    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: "collaborator" as const }
        : 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(formatApiError(text, res.status))
      }
    } 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
    if (!tokenVerifiedRef.current) return
    if (!isMachineActive) return // Não redireciona se a máquina estiver desativada
    autoLaunchRef.current = true
    setIsLaunchingSystem(true)
    openSystem()
  }, [token, status, config?.accessRole, openSystem, tokenValidationTick, isMachineActive])

  // Quando há token persistido (dispositivo já provisionado) e ainda não
  // disparamos o auto-launch, exibimos diretamente a tela de loading da
  // plataforma para evitar piscar o card de resumo/inventário.
  // IMPORTANTE: Sempre renderiza o MachineStateMonitor para detectar desativação em tempo real
  if (((token && !autoLaunchRef.current) || (isLaunchingSystem && token)) && isMachineActive) {
    return (
      <div className="min-h-screen grid place-items-center bg-slate-50 p-6">
        {/* Monitor de estado da máquina - deve rodar mesmo durante loading */}
        {token && config?.machineId && convexClient && (
          <MachineStateMonitor
            client={convexClient}
            machineId={config.machineId}
            onDeactivated={handleMachineDeactivated}
            onTokenRevoked={handleTokenRevoked}
          />
        )}
        <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>
    )
  }

  // Monitor sempre ativo quando há token e machineId
  const machineMonitor = token && config?.machineId && convexClient ? (
    <MachineStateMonitor
      client={convexClient}
      machineId={config.machineId}
      onDeactivated={handleMachineDeactivated}
      onTokenRevoked={handleTokenRevoked}
      onReactivated={handleMachineReactivated}
    />
  ) : null

  // Tela de desativação (renderizada separadamente para evitar container com fundo claro)
  if (token && !isMachineActive) {
    return (
      <>
        {machineMonitor}
        <DeactivationScreen companyName={companyName} onRetry={handleRetryCheck} />
      </>
    )
  }

  return (
    <div className="min-h-screen grid place-items-center bg-slate-50 p-6">
      {/* Monitor de estado da maquina em tempo real via Convex */}
      {machineMonitor}
      <div className="w-full max-w-[720px] rounded-2xl border border-slate-200 bg-white p-6 shadow-sm">
        <div className="mb-6 flex flex-col items-center gap-4 text-center">
          <img
            src={logoSrc}
            alt="Logotipo Raven"
            width={160}
            height={160}
            className="h-14 w-auto md:h-16"
            onError={() => {
              if (logoFallbackRef.current) return
              logoFallbackRef.current = true
              setLogoSrc(`${appUrl}/logo-raven.png`)
            }}
          />
          <div className="flex flex-col items-center gap-3">
            <span className="text-xs font-medium uppercase tracking-wide text-neutral-500">Raven</span>
            <span className="inline-flex items-center gap-2 rounded-full border border-slate-200 bg-slate-100/80 px-4 py-1.5 text-sm font-semibold text-neutral-700 shadow-sm">
              Sistema de chamados
            </span>
            <StatusBadge status={status} />
          </div>
        </div>
        {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 dispositivo.</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={provisioningCode}
                  onChange={(e) => {
                    const value = e.target.value
                    setProvisioningCode(value)
                    setValidatedCompany(null)
                    setCodeStatus(null)
                  }}
                />
                <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>
              {isValidatingCode ? (
                <p className="text-xs text-slate-500">Validando código...</p>
              ) : codeStatus ? (
                <p
                  className={`text-xs font-medium ${
                    codeStatus.tone === "success" ? "text-emerald-600" : "text-rose-600"
                  }`}
                >
                  {codeStatus.message}
                </p>
              ) : (
                <p className="text-xs text-slate-500">
                  Informe o código único fornecido pela equipe para vincular esta dispositivo a uma empresa.
                </p>
              )}
            </div>
            {validatedCompany ? (
              <div className="flex items-start gap-3 rounded-lg border border-emerald-200 bg-emerald-50 px-3 py-2 text-sm text-emerald-700">
                <span className="mt-1 inline-flex size-2 rounded-full bg-emerald-500" aria-hidden="true" />
                <div className="space-y-1">
                  <span className="block text-sm font-semibold text-emerald-800">{validatedCompany.name}</span>
                  <span className="text-xs text-emerald-700/80">
                    Código reconhecido. Esta dispositivo será vinculada automaticamente à empresa informada.
                  </span>
                </div>
              </div>
            ) : null}
            <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"
                type="email"
                placeholder="colaborador@empresa.com"
                value={collabEmail}
                onChange={(e) => setCollabEmail(e.target.value)}
              />
              {collabEmail && !isEmailValid ? (
                <p className="text-xs text-rose-600">Informe um e-mail válido (ex.: nome@empresa.com)</p>
              ) : null}
            </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>
            {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 || !validatedCompany || !isEmailValid || !collabName.trim() || provisioningCode.trim().length < 32}
                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 dispositivo
              </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="config" className="rounded-lg px-3">Configurações</TabsTrigger>
              </TabsList>
              <TabsContent value="resumo" className="mt-4">
                {companyName ? (
                  <div className="mb-3 rounded-lg border border-slate-200 bg-slate-50 px-3 py-2 text-sm text-neutral-700 shadow-sm">
                    <div className="text-sm font-semibold text-neutral-900">{companyName}</div>
                    {config?.collaboratorEmail ? (
                      <div className="text-xs text-neutral-500">
                        Vinculado a {config.collaboratorEmail}
                      </div>
                    ) : null}
                  </div>
                ) : null}
                <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="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>
  )
}

function StatusBadge({ status, className }: { status: string | null; className?: string }) {
  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={cn(
        "inline-flex h-8 items-center gap-3 rounded-full border border-slate-200 bg-white/80 px-3 text-sm font-medium text-neutral-600 shadow-sm",
        className
      )}
    >
      <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>
  )
}

// Roteamento simples baseado em query params (compativel com Tauri SPA)
function RootApp() {
  const params = new URLSearchParams(window.location.search)
  const view = params.get("view")

  // Janela de chat flutuante (view=chat ou path=/chat para compatibilidade)
  if (view === "chat" || window.location.pathname === "/chat") {
    return <ChatApp />
  }

  // Rota padrao - aplicacao principal
  return <App />
}

const root = document.getElementById("root") || (() => { const el = document.createElement("div"); el.id = "root"; document.body.appendChild(el); return el })()
createRoot(root).render(<RootApp />)
