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

// TYPE: url/dx4/
export const CLIENT_FRONTEND_URL = "http://localhost:5173/";

import { atom, useAtom } from "jotai";
import { atomWithStorage } from "jotai/utils";
import { useEffect } from "react";
import LoginPage from "./pages/LoginPage";
import DashPage from "./pages/DashPage";
import ClassProfilePage from "./pages/ClassProfile";
const passAtom = atomWithStorage("DX4DASH_pass", "");

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

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

  // fucntions
  setsetRoute,
  secondPathSegment,

  // constants
  API_BASE_URL,
};

const pages = {
  "/": <LoginPage {...basePageProps} />,
  "/dash": <DashPage {...basePageProps} />,
  "/class": <ClassProfilePage {...basePageProps} />,
};

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

// lol 💀
function setsetRoute(setRoute: (s: string) => void, path: string) {
  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-linear-to-r from-red-400 to-pink-300 bg-clip-text text-transparent">
        404((((
      </div>
      <div>{route}</div>
    </div>
  );
}
