import { Accessor, JSXElement, createSignal } from "solid-js";
import { createContext } from "solid-js";

import { Navbar } from "./Navbar";
import { Primary } from "./Primary";
import { LoginModal } from "./LoginModal";

// Representing the state of varoious modals.
// So far we only have one modal, but we can add more later
// by adding more fields to this interface, or maybe an enum
interface ModalContextType {
  loginModalOpen: Accessor<boolean>;
  setLoginModalOpen: (value: boolean) => void;
}

interface LoginContextType {
  token: Accessor<string>;
  setToken: (value: string) => void;
  username: Accessor<string>;
  setUsername: (value: string) => void;
}

// It is unclear to me if this is the idiomatic way to do this in Solid
export const ModalContext = createContext<ModalContextType>();
export const LoginContext = createContext<LoginContextType>();

function Root(): JSXElement {
  // All of these are passed into context providers
  const [loginModalOpen, setLoginModalOpen] = createSignal(false);
  const [token, setToken] = createSignal("");
  const [username, setUsername] = createSignal("");

  // This may not be the best place to do this.
  localStorage.getItem("token") && setToken(localStorage.getItem("token")!);
  localStorage.getItem("username") &&
    setUsername(localStorage.getItem("username")!);

  return (
    <>
      <ModalContext.Provider value={{ loginModalOpen, setLoginModalOpen }}>
        <LoginContext.Provider
          value={{ token, setToken, username, setUsername }}
        >
          <div class="flex flex-col items-center">
            <Navbar />
            <LoginModal />
            <div class="flex flex-col items-center w-full md:max-w-3xl px-2 space-y-2">
              <Primary />
            </div>
          </div>
        </LoginContext.Provider>
      </ModalContext.Provider>
    </>
  );
}

export default Root;
