/* global React, ReactDOM */

const TWEAK_DEFAULTS = {
  "theme": "light",
  "accent": "plum",
  "density": "cozy",
  "gridLayout": "days-cols",
  "showTeacher": true,
  "showRoom": true,
  "showType": true,
};

const ACCENT_MAP = {
  plum:   { a: "#6b2d5c", h: "#54234a", soft: "#f3e8ef" },
  ink:    { a: "#1a1815", h: "#000000", soft: "#ebe6db" },
  forest: { a: "#2f6a4a", h: "#24533a", soft: "#e6efe8" },
  ochre:  { a: "#b88729", h: "#9a6e17", soft: "#f5ecd7" },
};

function App() {
  const [screen, setScreen] = useState(() => localStorage.getItem("sched_screen") || "dashboard");
  const [loggedIn, setLoggedIn] = useState(false);
  const [tweaks, setTweaks] = useState(TWEAK_DEFAULTS);
  const [tweaksVisible, setTweaksVisible] = useState(false);
  const [appLoading, setAppLoading] = useState(true);
  const [loginError, setLoginError] = useState("");
  const [dataVersion, setDataVersion] = useState(0);

  useEffect(() => { localStorage.setItem("sched_screen", screen); }, [screen]);

  useEffect(() => {
    document.body.className = `theme-${tweaks.theme} density-${tweaks.density}`;
    const accent = ACCENT_MAP[tweaks.accent] || ACCENT_MAP.plum;
    document.documentElement.style.setProperty("--accent", accent.a);
    document.documentElement.style.setProperty("--accent-h", accent.h);
    document.documentElement.style.setProperty("--accent-soft", accent.soft);
  }, [tweaks]);

  useEffect(() => {
    const handler = (e) => {
      if (!e.data || typeof e.data !== "object") return;
      if (e.data.type === "__activate_edit_mode") setTweaksVisible(true);
      if (e.data.type === "__deactivate_edit_mode") setTweaksVisible(false);
    };
    window.addEventListener("message", handler);
    window.parent.postMessage({ type: "__edit_mode_available" }, "*");
    return () => window.removeEventListener("message", handler);
  }, []);

  useEffect(() => {
    if (tweaksVisible) {
      window.parent.postMessage({ type: "__edit_mode_set_keys", edits: tweaks }, "*");
    }
  }, [tweaks, tweaksVisible]);

  // Auto-login from stored token
  useEffect(() => {
    const token = localStorage.getItem("sched_token");
    if (token) {
      window.API_TOKEN = token;
      window.API.loadData()
        .then(() => { setLoggedIn(true); setAppLoading(false); })
        .catch(() => {
          localStorage.removeItem("sched_token");
          localStorage.removeItem("sched_user");
          window.API_TOKEN = null;
          setAppLoading(false);
        });
    } else {
      setAppLoading(false);
    }
  }, []);

  async function handleLogin(username, password) {
    setLoginError("");
    try {
      const data = await window.API.post("/api/auth/login", { username, password });
      window.API_TOKEN = data.access_token;
      localStorage.setItem("sched_token", data.access_token);
      localStorage.setItem("sched_user", data.user.username);
      await window.API.loadData();
      setLoggedIn(true);
      return null;
    } catch (err) {
      const raw = err.message || "";
      let msg = "Ошибка входа. Проверьте, что сервер запущен.";
      if (raw.includes("401") || raw.toLowerCase().includes("invalid")) {
        msg = "Неверный логин или пароль.";
      } else if (raw.includes("Failed to fetch") || raw.includes("NetworkError")) {
        msg = "Нет подключения к серверу (localhost:8000).";
      }
      setLoginError(msg);
      return msg;
    }
  }

  function handleLogout() {
    localStorage.removeItem("sched_token");
    localStorage.removeItem("sched_user");
    window.API_TOKEN = null;
    setLoggedIn(false);
  }

  async function reloadData() {
    await window.API.loadData();
    setDataVersion(v => v + 1);
  }

  function refresh() {
    setDataVersion(v => v + 1);
  }

  if (appLoading) {
    return (
      <div style={{
        display: "grid", placeItems: "center", minHeight: "100vh",
        background: "var(--canvas)", fontFamily: "var(--font-serif)",
        color: "var(--ink-3)", fontSize: 32, fontStyle: "italic",
      }}>
        Загрузка…
      </div>
    );
  }

  if (!loggedIn) {
    return <LoginScreen onLogin={handleLogin} error={loginError} />;
  }

  const STATS = window.SCHED_DATA.STATS;
  const username = localStorage.getItem("sched_user") || "administrator";

  return (
    <div className="appShell" data-screen-label={screen}>
      <Header
        tab={screen}
        onTab={setScreen}
        user={username}
        onLogout={handleLogout}
        conflicts={STATS.conflicts}
      />
      <StatusBar stats={STATS} hasPending={window.SCHED_DATA.isPending} />
      <div className="appMain" data-screen-label={`${screen}${window.SCHED_DATA.isPending ? "-edit" : ""}`}>
        {screen === "dashboard" && (
          <Dashboard
            key={dataVersion}
            onTab={setScreen}
            onStartGenerate={() => setScreen("schedule")}
            onReload={reloadData}
          />
        )}
        {screen === "schedule" && (
          <ScheduleScreen
            tweaks={tweaks}
            onReload={reloadData}
            onRefresh={refresh}
          />
        )}
        {screen === "settings" && <SettingsScreen />}
        {screen === "help" && <HelpScreen />}
      </div>
      {tweaksVisible && <TweaksPanel tweaks={tweaks} setTweaks={setTweaks} />}
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
