import { create } from "zustand";

import type { DefaultLayerStyleId, StyleConfig } from "@components/olmap/core/Controls/styleEditorTypes";

/* ------------------------------------------------------------------ */
/*  Chat Tool Action Store                                            */
/*  Decouples chat tool calls from map/panel execution.               */
/*  Chat dispatches actions → map/panel components subscribe & react. */
/* ------------------------------------------------------------------ */

export type ChatToolAction =
  | {
      type: "locate_features";
      ids: string[];
      layer: string;
      geometryKind: "point" | "line";
    }
  | {
      type: "zoom_to_map";
      coordinate: [number, number];
      sourceCrs?: "EPSG:3857" | "EPSG:4326";
      zoom?: number;
      durationMs?: number;
    }
  | {
      type: "view_history";
      featureInfos: [string, string][];
      dataType: "realtime" | "scheme" | "none";
      startTime?: string;
      endTime?: string;
    }
  | {
      type: "view_scada";
      featureInfos: [string, string][];
      startTime?: string;
      endTime?: string;
    }
  | {
      type: "show_chart";
      title?: string;
      chartType?: "line" | "bar" | "pie";
      xData?: string[];
      series?: Array<{ name: string; data: number[]; type?: "line" | "bar" }>;
      xAxisName?: string;
      yAxisName?: string;
    }
  | {
      type: "render_junctions";
      renderRef: string;
      sessionId?: string;
    }
  | {
      type: "apply_layer_style";
      layerId: DefaultLayerStyleId;
      resetToDefault: boolean;
      styleConfig?: Partial<StyleConfig>;
    };

interface ChatToolState {
  /** Most recent dispatched action (null until first dispatch). */
  lastAction: ChatToolAction | null;
  /** Monotonically increasing counter – lets subscribers detect new actions. */
  actionSeq: number;
  /** Timestamp of the most recent action dispatch. */
  lastActionAt: number;
  /** Dispatch a tool action from the chat. */
  dispatch: (action: ChatToolAction) => void;
}

export const useChatToolStore = create<ChatToolState>((set) => ({
  lastAction: null,
  actionSeq: 0,
  lastActionAt: 0,
  dispatch: (action) =>
    set((state) => ({
      lastAction: action,
      actionSeq: state.actionSeq + 1,
      lastActionAt: Date.now(),
    })),
}));
