/* global React, ReactDOM, SEQ_LANDING, SEQ_DASH, SEQ_PROPOSTA */

const ROUTES = {
  "/landing": { id: "view-landing", comp: () => window.SEQ_LANDING, public: true, fullscreen: true },
  "/login": { id: "view-login", comp: () => window.SEQ_LOGIN, public: true, fullscreen: true },
  "/home": { id: "view-home", comp: () => window.SEQ_HOME },
  "/propostas": { id: "view-propostas", comp: () => window.SEQ_DASH },
  "/proposta": { id: "view-proposta", comp: () => window.SEQ_PROPOSTA },
  "/editor": { id: "view-editor", comp: () => window.SEQ_EDITOR },
  "/publica": { id: "view-publica", comp: () => window.SEQ_PUBLICA, public: true },
  "/checkout": { id: "view-checkout", comp: () => window.SEQ_CHECKOUT },
  "/checkout-builder": { id: "view-checkout-builder", comp: () => window.SEQ_CKBUILDER },
  "/pagamentos": { id: "view-pagamentos", comp: () => window.SEQ_PAGAMENTOS },
  "/produtos": { id: "view-produtos", comp: () => window.SEQ_PRODUTOS },
  "/assinantes": { id: "view-assinantes", comp: () => window.SEQ_ASSINANTES },
  "/clientes": { id: "view-clientes", comp: () => window.SEQ_CLIENTES },
  "/cliente": { id: "view-cliente", comp: () => window.SEQ_CLIENTE },
  "/saldo": { id: "view-saldo", comp: () => window.SEQ_SALDO },
  "/checkout-public": { id: "view-checkout-public", comp: () => window.SEQ_CKPUBLIC, public: true },
  "/portal": { id: "view-portal", comp: () => window.SEQ_PORTAL, public: true },
  "/afiliados": { id: "view-afiliados", comp: () => window.SEQ_AFILIADOS },
  "/integracoes": { id: "view-integracoes", comp: () => window.SEQ_INTEGRACOES },
  "/onboarding": { id: "view-onboarding", comp: () => window.SEQ_ONBOARDING },
  "/configuracoes": { id: "view-configuracoes", comp: () => window.SEQ_CONFIG },
  "/relatorios": { id: "view-relatorios", comp: () => window.SEQ_RELATORIOS },
};

let authState = { authenticated: false, ready: false };

function getRoute() {
  const raw = window.location.hash.replace(/^#/, "") || "/landing";
  const h = raw.split("?")[0] || "/landing";
  return ROUTES[h] ? h : "/landing";
}

const mounted = {};

function navigate() {
  const route = getRoute();
  const target = ROUTES[route];

  // Auth guard: rotas privadas precisam de cookie
  if (authState.ready && !authState.authenticated && target && !target.public) {
    window.location.hash = "/landing";
    return;
  }
  // Se logado e tentando acessar landing/login, manda pra home
  if (authState.ready && authState.authenticated && (route === "/landing" || route === "/login")) {
    window.location.hash = "/home";
    return;
  }

  // Sidebar: esconder em rotas fullscreen (landing, login)
  const sidebar = document.getElementById("sidebar");
  const mobileBar = document.querySelector(".sb-mobile-bar");
  const main = document.getElementById("app-main");
  if (target?.fullscreen) {
    if (sidebar) sidebar.style.display = "none";
    if (mobileBar) mobileBar.style.display = "none";
    if (main) main.style.padding = "0";
    document.body.style.paddingLeft = "0";
    document.body.style.paddingTop = "0";
  } else {
    if (sidebar) sidebar.style.display = "";
    if (mobileBar) mobileBar.style.display = "";
    if (main) main.style.padding = "";
    document.body.style.paddingLeft = "";
    document.body.style.paddingTop = "";
  }

  Object.entries(ROUTES).forEach(([k, v]) => {
    const el = document.getElementById(v.id);
    if (!el) return;
    el.hidden = k !== route;
  });

  if (target && !mounted[route]) {
    const Comp = target.comp();
    if (!Comp) return;
    const el = document.getElementById(target.id);
    ReactDOM.createRoot(el).render(React.createElement(Comp));
    mounted[route] = true;
  }
  window.scrollTo(0, 0);
}

function mountSidebar() {
  if (!window.SEQ_SIDEBAR) return;
  const el = document.getElementById("sidebar");
  if (el && !el.dataset.mounted) {
    ReactDOM.createRoot(el).render(React.createElement(window.SEQ_SIDEBAR));
    el.dataset.mounted = "1";
  }
  const tog = document.getElementById("sb-toggle");
  if (tog && !tog.dataset.bound) {
    tog.addEventListener("click", () => el.classList.toggle("is-open"));
    tog.dataset.bound = "1";
  }
}

async function bootstrap() {
  // Verifica auth antes de renderizar
  try {
    const me = await window.SEQ_API.me();
    authState = { authenticated: !!me.authenticated, ready: true };
  } catch {
    authState = { authenticated: false, ready: true };
  }

  // Se sem hash inicial e não autenticado: landing. Se autenticado: home.
  if (!window.location.hash) {
    window.location.hash = authState.authenticated ? "/home" : "/landing";
  }

  mountSidebar();
  navigate();
}

window.addEventListener("hashchange", navigate);
window.addEventListener("DOMContentLoaded", () => setTimeout(bootstrap, 0));
if (document.readyState !== "loading") setTimeout(bootstrap, 50);
