import { useEffect } from "react";
import { AppProvider } from "@shopify/polaris";
import { NavMenu } from "@shopify/app-bridge-react";
import polarisTranslations from "@shopify/polaris/locales/en.json";
import OverviewDashboard, { loader as appIndexLoader, action as appIndexAction } from "./app._index";

export const headers = () => {
  return {
    "X-Frame-Options": "ALLOWALL",
    "Content-Security-Policy": "frame-ancestors https://admin.shopify.com https://*.myshopify.com;",
  };
};

export const loader = appIndexLoader;
export const action = appIndexAction;

export default function RootIndex() {
  useEffect(() => {
    if (typeof window === "undefined") return;
    const shopifyGlobal = (window as any).shopify;
    if (shopifyGlobal && typeof shopifyGlobal.idToken === "function") {
      shopifyGlobal
        .idToken()
        .then((token: string) => {
          if (token) {
            fetch("/api/auth/session", {
              method: "POST",
              headers: {
                Authorization: `Bearer ${token}`,
                "Content-Type": "application/json",
              },
            }).catch(() => {});
          }
        })
        .catch(() => {});
    }
  }, []);

  return (
    <AppProvider i18n={polarisTranslations}>
      <NavMenu>
        <a href="/app" rel="home">Dashboard</a>
        <a href="/app/billing">Plans &amp; Billing</a>
        <a href="/app/notifications">Notifications</a>
      </NavMenu>
      <OverviewDashboard />
    </AppProvider>
  );
}
