(() => {
  const { useState, useEffect, useRef, useCallback, apiFetch, setDateTimeConfig, ROLE_LABEL, ROLE_COLOR } = window.DC;
  const { DashboardView, LoginPage, ServersView, DeployView, ActionsView, MonitorView, HistoryView, NocView, OpsView, SettingsView, SchedulesView, DocsView } = window.DCViews;

  function App() {
    const [currentUser, setCurrentUser] = useState(null);
    const [loading, setLoading] = useState(true);
    const [dateTimeVersion, setDateTimeVersion] = useState(0);
    const [view, setView] = useState("dashboard");
    const [servers, setServers] = useState([]);
    const [toast, setToast] = useState(null);
    const navTabsRef = useRef(null);

    const showToast = (msg, type = "ok") => {
      setToast({ msg, type });
      setTimeout(() => setToast(null), 3000);
    };

    useEffect(() => {
      const token = localStorage.getItem("dc_token");
      if (!token) {
        setLoading(false);
        return;
      }

      apiFetch("/auth/me")
        .then((user) => {
          if (user?.id) setCurrentUser(user);
          else localStorage.removeItem("dc_token");
          setLoading(false);
        })
        .catch(() => setLoading(false));
    }, []);

    useEffect(() => {
      if (!currentUser) return;
      apiFetch("/settings/datetime").then((config) => {
        if (!config?.error) setDateTimeConfig(config);
      });
    }, [currentUser]);

    useEffect(() => {
      const syncDateTime = () => setDateTimeVersion((prev) => prev + 1);
      window.addEventListener("dc:datetime-config-updated", syncDateTime);
      return () => window.removeEventListener("dc:datetime-config-updated", syncDateTime);
    }, []);

    const loadServers = useCallback(async () => {
      const data = await apiFetch("/servers");
      setServers(Array.isArray(data) ? data : []);
    }, []);

    useEffect(() => {
      if (currentUser) loadServers();
    }, [currentUser, loadServers]);

    useEffect(() => {
      const tabsNode = navTabsRef.current;
      if (!tabsNode || typeof window === "undefined") return;
      if (!window.matchMedia("(max-width: 899px)").matches) return;

      const activeTab = tabsNode.querySelector(".nav-tab.active");
      if (!activeTab) return;

      const tabsRect = tabsNode.getBoundingClientRect();
      const activeRect = activeTab.getBoundingClientRect();
      const currentScroll = tabsNode.scrollLeft;
      const targetScroll = currentScroll + (activeRect.left - tabsRect.left) - ((tabsRect.width - activeRect.width) / 2);
      const maxScroll = Math.max(0, tabsNode.scrollWidth - tabsNode.clientWidth);
      const nextScroll = Math.max(0, Math.min(targetScroll, maxScroll));

      window.requestAnimationFrame(() => {
        tabsNode.scrollTo({ left: nextScroll, behavior: "smooth" });
      });
    }, [view, currentUser]);

    const logout = () => {
      localStorage.removeItem("dc_token");
      setCurrentUser(null);
    };

    const isViewer = currentUser?.role === "viewer";
    const views = [
      ["dashboard", "📈 Dashboard"],
      ["servers", "⬡ Servidores"],
      ["deploy", "🚀 Deploy"],
      ["actions", "⚡ Acciones"],
      ["monitor", "📊 Monitor"],
      ["noc", "🛡 NOC"],
      ["ops", "🛟 Ops"],
      ["schedules", "🗓 Programados"],
      ["history", "📋 Historial"],
      ["docs", "📚 Docs"],
      ["settings", "⚙ Config"],
    ].filter(([key]) => {
      if ((key === "deploy" || key === "actions") && isViewer) return false;
      if ((key === "noc" || key === "ops") && currentUser?.role !== "superadmin") return false;
      if (key === "schedules" && isViewer) return false;
      return true;
    });

    if (loading) {
      return (
        <div style={{ minHeight: "100vh", display: "flex", alignItems: "center", justifyContent: "center", color: "#64748b", fontSize: 13 }}>
          Cargando...
        </div>
      );
    }

    if (!currentUser) {
      return <LoginPage onLogin={(user) => setCurrentUser(user)} />;
    }

    const parseNavLabel = (label) => {
      const [icon = "", ...parts] = String(label).split(" ");
      return {
        icon,
        text: parts.join(" ") || label,
      };
    };

    return (
      <>
        <nav className="app-nav">
          <div className="nav-topbar">
            <div className="nav-logo">
              <div className="nav-logo-icon">⚡</div>
              <div>
                <div className="nav-logo-text">DataCole</div>
                <div className="nav-logo-sub">DEPLOY MANAGER</div>
              </div>
            </div>
            <div className="nav-user">
              <span
                className="tag"
                style={{
                  borderColor: `${ROLE_COLOR[currentUser.role]}44`,
                  color: ROLE_COLOR[currentUser.role],
                  background: `${ROLE_COLOR[currentUser.role]}15`,
                  fontSize: 9,
                }}
              >
                {ROLE_LABEL[currentUser.role]}
              </span>
              <span className="nav-user-name">{currentUser.username}</span>
              <button onClick={logout} className="nav-logout" title="Salir">
                ↩
              </button>
            </div>
          </div>
          <div className="nav-tabs-wrap">
            <div className="nav-tabs" ref={navTabsRef}>
              {views.map(([key, label]) => {
                const { icon, text } = parseNavLabel(label);
                return (
                  <button
                    key={key}
                    onClick={() => setView(key)}
                    className={`nav-tab${view === key ? " active" : ""}`}
                    title={text}
                  >
                    <span className="nav-tab-icon" aria-hidden="true">{icon}</span>
                    <span className="nav-tab-text">{text}</span>
                  </button>
                );
              })}
            </div>
          </div>
        </nav>

        <div key={dateTimeVersion} className={`app-content${["dashboard", "monitor", "noc", "ops"].includes(view) ? " app-content-wide" : ""}`}>
          {view === "dashboard" && <DashboardView toast={showToast} currentUser={currentUser} />}
          {view === "servers" && <ServersView servers={servers} reload={loadServers} toast={showToast} currentUser={currentUser} />}
          {view === "deploy" && <DeployView servers={servers} toast={showToast} reloadHistory={() => {}} />}
          {view === "actions" && <ActionsView servers={servers} toast={showToast} currentUser={currentUser} />}
          {view === "monitor" && <MonitorView servers={servers} toast={showToast} currentUser={currentUser} />}
          {view === "noc" && <NocView toast={showToast} currentUser={currentUser} />}
          {view === "ops" && <OpsView toast={showToast} currentUser={currentUser} />}
          {view === "schedules" && <SchedulesView toast={showToast} currentUser={currentUser} />}
          {view === "history" && <HistoryView currentUser={currentUser} />}
          {view === "docs" && <DocsView currentUser={currentUser} />}
          {view === "settings" && <SettingsView currentUser={currentUser} toast={showToast} />}
        </div>

        {toast && (
          <div
            style={{
              position: "fixed",
              bottom: 20,
              left: "50%",
              transform: "translateX(-50%)",
              background: toast.type === "ok" ? "#22d3a5" : "#f43f5e",
              color: "#000",
              padding: "10px 20px",
              borderRadius: 10,
              fontWeight: 700,
              fontSize: 13,
              zIndex: 999,
              animation: "fadeIn .2s ease",
              boxShadow: "0 8px 24px rgba(0,0,0,.4)",
              whiteSpace: "nowrap",
            }}
          >
            {toast.type === "ok" ? "✓" : "✗"} {toast.msg}
          </div>
        )}
      </>
    );
  }

  ReactDOM.createRoot(document.getElementById("root")).render(React.createElement(App));
})();
