"use client";

import { createContext, useContext, useState, useEffect, ReactNode } from "react";
import { DEFAULT_TENANT_ID, TENANT_STORAGE_KEY } from "@/lib/constants";

type TenantContextType = {
  tenantId: string;
  setTenantId: (id: string) => void;
  isLoading: boolean;
};

const TenantContext = createContext<TenantContextType | undefined>(undefined);

export function TenantProvider({ children }: { children: ReactNode }) {
  const [tenantId, setTenantIdState] = useState("");
  const [isLoading, setIsLoading] = useState(true);

  // Load from localStorage on mount
  useEffect(() => {
    const saved = localStorage.getItem(TENANT_STORAGE_KEY);
    setTenantIdState(saved || DEFAULT_TENANT_ID);
    setIsLoading(false);
  }, []);

  const setTenantId = (id: string) => {
    const trimmed = id.trim();
    setTenantIdState(trimmed);
    if (trimmed) {
      localStorage.setItem(TENANT_STORAGE_KEY, trimmed);
    } else {
      localStorage.removeItem(TENANT_STORAGE_KEY);
    }
  };

  return (
    <TenantContext.Provider value={{ tenantId, setTenantId, isLoading }}>
      {children}
    </TenantContext.Provider>
  );
}

export function useTenant() {
  const context = useContext(TenantContext);
  if (!context) {
    throw new Error("useTenant must be used within TenantProvider");
  }
  return context;
}

