'use client';

// Top-level Zustand store. Holds timeline-shaped state plus media/UI flags
// and delegates action implementation to the slices in `./editor/*`.
//
// To keep this file under our maintenance budget, action creators are
// colocated by domain (clips, silence, history). Selectors live alongside.

import { create } from 'zustand';
import { createMediaActions } from './editor/clips';
import { createSilenceActions } from './editor/silence';
import { createHistoryActions } from './editor/history';
import { createProjectActions } from './editor/project';
import {
  defaultExportSettings,
  EditorActions,
  initialTracks,
  StateSlice,
} from './editor/types';
import { DEFAULT_SUBTITLE_STYLE } from '@/types';

const initialProjectId = `p-${Date.now().toString(36)}`;
const initialProjectName = 'โปรเจกต์ใหม่';

export type EditorState = StateSlice & EditorActions;

export const useEditor = create<EditorState>((set, get) => ({
  // ---- State ----
  assets: [],
  tracks: initialTracks,
  clips: [],
  subtitles: [],
  textOverlays: [],
  silenceSegments: [],
  selection: {},
  playing: false,
  currentTime: 0,
  zoom: 80,
  history: [],
  historyIndex: -1,
  exportSettings: defaultExportSettings,
  toast: null,
  subtitleStyle: DEFAULT_SUBTITLE_STYLE,
  projectId: initialProjectId,
  projectName: initialProjectName,
  projectCreatedAt: Date.now(),

  // ---- Trivial setters (kept inline for ergonomics) ----
  setSelection: (sel) => set({ selection: sel }),
  setPlaying: (p) => set({ playing: p }),
  setCurrentTime: (t) => set({ currentTime: Math.max(0, t) }),
  setZoom: (z) => set({ zoom: Math.max(20, Math.min(400, z)) }),
  setSubtitles: (subs) => set({ subtitles: subs }),
  setExportSettings: (patch) =>
    set((s) => ({ exportSettings: { ...s.exportSettings, ...patch } })),
  setToast: (t) => set({ toast: t }),
  setSubtitleStyle: (patch) =>
    set((s) => ({ subtitleStyle: { ...s.subtitleStyle, ...patch } })),

  // ---- Domain actions (delegated) ----
  ...createMediaActions(set, get),
  ...createSilenceActions(set, get),
  ...createHistoryActions(set, get),
  ...createProjectActions(set, get),

  // ---- Reset ----
  reset: () =>
    set({
      assets: [],
      tracks: initialTracks,
      clips: [],
      subtitles: [],
      textOverlays: [],
      silenceSegments: [],
      selection: {},
      currentTime: 0,
      playing: false,
      history: [],
      historyIndex: -1,
      toast: null,
      subtitleStyle: DEFAULT_SUBTITLE_STYLE,
      projectId: initialProjectId,
      projectName: initialProjectName,
      projectCreatedAt: Date.now(),
    }),
}));

// Re-export selectors so callers can keep a single import path.
export { selectTimelineDuration, selectActiveSubtitle } from './editor/selectors';

// Re-export uid so legacy import sites still compile.
export { uid } from './editor/types';