import React from "react";
import { useState, useEffect, useContext } from "react";

import type { TabSlug,} from "../types";
import { getTabSlugFromUrl } from "../utils";

import { tabsData } from "../XTabs";



type DashboardContextType = {
  tabSlug: TabSlug;
  setTabSlug: React.Dispatch<React.SetStateAction<TabSlug>>;
};

const DashboardContext = React.createContext<DashboardContextType | undefined>(undefined);

// helpers 
export function useDashboardContext() {
  const ctx = useContext(DashboardContext);
  if (!ctx) throw new Error("DashboardContext missing");
  return ctx;
}


export default function DashboardContextProvider({
  children,

}: {
  children: React.ReactNode,
}) {

  /**
   * SLUGS
   *  - Tab slug        http://ssq.local/wp-admin/admin.php?page=scrollsequence-dashboard&tab={tabSlug}
   *      defaults to 'getting-started'
   *  - Media Tool slug http://ssq.local/wp-admin/admin.php?page=scrollsequence-dashboard&tab={tabSlug}&mediaTool={mediaToolSlug}
   *     defaults to 'img2img'
   *   
   */
  // Tab Slug 
  const [tabSlug, setTabSlug] = useState<TabSlug>(getTabSlugFromUrl());
  // Update URL when tab changes ---
  useEffect(() => {
      const url = new URL(window.location.href);

      // Always set tab param, default to first tab if missing
      if (!tabSlug || tabSlug === tabsData[0].slug) {
          url.searchParams.delete('tab');
      } else {
          url.searchParams.set('tab', tabSlug);
      }

      window.history.replaceState({}, '', url.toString());
  }, [tabSlug]);

  return (
    <DashboardContext.Provider
      value={{
        tabSlug, setTabSlug,
      }}
    >
      {children}
    </DashboardContext.Provider>
  );
}


