'use client';

import {createContext, useContext, useMemo, useState} from 'react';

/**
 * Workspace-wide query scope: which store, and over what period.
 *
 * This lives ABOVE the route tree (mounted in app/providers.tsx) for the same
 * reason Loyaly AI does. A server-component page could not re-render from
 * these controls without a router navigation, and a navigation would remount
 * Loyaly AI. So scope is client state, and data panels read it.
 *
 * The controls that write it are NOT shell — they render in each page's own
 * header (@/components/scope). Keeping the state up here is what lets a store
 * or period chosen on the dashboard still be in force on Staff or LYTs, while
 * a page that ignores scope simply shows no control for it.
 */

export type RangeKey = '7d' | '30d' | '90d' | 'mtd' | 'ytd' | 'custom';

export const RANGE_LABELS: Record<RangeKey, string> = {
  '7d': 'Last 7 days',
  '30d': 'Last 30 days',
  '90d': 'Last 90 days',
  mtd: 'Month to date',
  ytd: 'Year to date',
  custom: 'Custom range',
};

export interface CustomDateRange {
  start: string;
  end: string;
}

export interface StoreOption {
  id: string;
  name: string;
}

/**
 * Store list for the switcher. Deliberately static: the switcher must render
 * before any data loads, and a spinner in a page header on every load reads
 * as jank. The authoritative list comes from /api/stores once Store lands.
 */
export const STORE_OPTIONS: StoreOption[] = [
  {id: 'blr-indiranagar', name: 'Indiranagar Flagship'},
  {id: 'blr-koramangala', name: 'Koramangala'},
  {id: 'blr-whitefield', name: 'Whitefield'},
  {id: 'che-anna-nagar', name: 'Anna Nagar'},
  {id: 'hyd-jubilee', name: 'Jubilee Hills'},
];

export type StoreScope = 'all' | (string & {});

interface WorkspaceValue {
  storeId: StoreScope;
  setStoreId: (id: StoreScope) => void;
  range: RangeKey;
  setRange: (r: RangeKey) => void;
  customRange: CustomDateRange | null;
  setCustomRange: (cr: CustomDateRange | null) => void;
  stores: StoreOption[];
}

const WorkspaceContext = createContext<WorkspaceValue | null>(null);

export function WorkspaceProvider({children}: {children: React.ReactNode}) {
  const [storeId, setStoreId] = useState<StoreScope>('all');
  const [range, setRange] = useState<RangeKey>('30d');
  const [customRange, setCustomRange] = useState<CustomDateRange | null>(null);

  const value = useMemo(
    () => ({
      storeId,
      setStoreId,
      range,
      setRange,
      customRange,
      setCustomRange,
      stores: STORE_OPTIONS,
    }),
    [storeId, range, customRange],
  );

  return <WorkspaceContext value={value}>{children}</WorkspaceContext>;
}

export function useWorkspace(): WorkspaceValue {
  const ctx = useContext(WorkspaceContext);
  if (!ctx) {
    throw new Error('useWorkspace must be used inside <WorkspaceProvider>');
  }
  return ctx;
}
