// CHANGE TO YOUR API DESTINATION
export const API_BASE_URL = "http://localhost:8321/api.php";

import { atom, useAtom } from "jotai";
import { atomWithStorage } from "jotai/utils";
import { useEffect } from "react";
import { lazy } from "react";
import { DengiCaching } from "./trash/dengiCashingSystem";
import { ifstyle } from "./trash/helpers";
import { LoginPage } from "./pages/LoginPage";
import { DX4App } from "./pages/DX4AppPage";

const classIDAtom = atomWithStorage("class-id", "");
const adminAtom = atomWithStorage("admin-id", "");

const pickmeModeAtom = atomWithStorage("pickmeMode", false);

const EditorPage = lazy(() => import("./pages/editor"));
const AdminProfilePage = lazy(() => import("./pages/AdminProfile"));
const ClassProfilePage = lazy(() => import("./pages/ClassProfile"));

const dengi_cash = new DengiCaching();

// KATAMAZ DENGI ROUTER 4 PRO MAX ULTIMATE
// 💀💀
// PROS - vrode raboatat,
//        too simple, lightweight, stupidly fast
//             (beacause you basicly download entire site, lol)
// CONS - shit
function firstPathSegment(path) {
  const m = path.match(/^\/?([^/]+)/);
  return m ? m[1] : "";
}
const secondPathSegment = (p) => p.replace(/^\/?[^/]+/, "").replace(/^\/+/, "");

const routeAtom = atom("/");
const basePageProps = {
  // atoms
  classIDAtom,
  adminAtom,
  routeAtom,

  // fucntions
  setsetRoute,
  secondPathSegment,
  ifstyle,

  // constants
  API_BASE_URL,

  // caching
  dengi_cash,

  // etc
  pickmeModeAtom, // <3
};
const pages = {
  "/": <LoginPage {...basePageProps} />,
  "/app": <DX4App {...basePageProps} />,
  "/exit": <ExitPage {...basePageProps} />,
  "/editor": <EditorPage {...basePageProps} />,
  "/adminprofile": <AdminProfilePage {...basePageProps} />,
  "/classprofile": <ClassProfilePage {...basePageProps} />,
};

let changeAnchor = true;
let defaultAnchor = document.location.hash.substring(1);

// lol 💀
function setsetRoute(setRoute, path) {
  changeAnchor = true;
  setRoute(path);
  document.location.hash = path;
}

export default function DX4() {
  const [route, _setRoute] = useAtom(routeAtom);
  useEffect(() => {
    if (
      document.location.hash &&
      document.location.hash.substring(1) !== route
    ) {
      _setRoute(document.location.hash.substring(1));
    }
    window.addEventListener("load", () => {
      if (defaultAnchor == "" || defaultAnchor == "/") {
        document.location.hash = defaultAnchor;
      }
    });
  }, [route, _setRoute]);
  window.addEventListener("hashchange", () => {
    if (document.location.hash == "") {
      document.location.hash = "/";
    }
    if (changeAnchor) {
      changeAnchor = false;
      return;
    }
    _setRoute(document.location.hash.substring(1));
  });
  const page = Object.entries(pages).find(
    ([key]) => firstPathSegment(key) == firstPathSegment(route)
  );
  return (
    (page ? page[1] : false) || <ERROR404 /> || <div>some shit happened</div>
  );
}

export function ERROR404() {
  const route = useAtom(routeAtom)[0];
  return (
    <div className="flex items-center justify-center min-h-screen flex-col gap-10">
      <div className="text-6xl font-black bg-gradient-to-r from-red-400 to-pink-300 bg-clip-text text-transparent">
        404((((
      </div>
      <div>{route}</div>
    </div>
  );
}
export function ExitPage() {
  const [_userId, setUserId] = useAtom(classIDAtom);
  const setRoute = useAtom(routeAtom)[1];
  return (
    <div className="w-screen h-screen flex items-center justify-center">
      <button
        className="w-20 h-20 bg-red-500 rounded-full text-white"
        onClick={() => {
          setUserId("");
          setsetRoute(setRoute, "/");
        }}
      >
        viyti
      </button>
    </div>
  );
}
