"use client";

import { createContext, useContext, type ReactNode } from "react";
import type { DashboardData } from "@/lib/dashboard-data";

// Shared by the (app) layout (provider) and every section page (consumer).
// The layout owns the single useDashboard() query plus the cross-cutting
// actions (toasts, add-vehicle modal, route navigation, logout); pages read
// what they need from here instead of receiving props, so each section can be
// its own route while still sharing one fetch and one shell.
export type DashboardContextValue = {
  data: DashboardData;
  onAction: (action: string) => void;
  name: string;
  email?: string;
  initials: string;
  loggingOut: boolean;
  onLogout: () => void;
};

const DashboardContext = createContext<DashboardContextValue | null>(null);

export function DashboardProvider({
  value,
  children,
}: {
  value: DashboardContextValue;
  children: ReactNode;
}) {
  return (
    <DashboardContext.Provider value={value}>
      {children}
    </DashboardContext.Provider>
  );
}

export function useDashboardCtx(): DashboardContextValue {
  const ctx = useContext(DashboardContext);
  if (!ctx) {
    throw new Error("useDashboardCtx must be used within the (app) dashboard layout");
  }
  return ctx;
}
