// Shared types for the editor store and its slices.

import type {
  Clip,
  ExportSettings,
  MediaAsset,
  SilenceSegment,
  SubtitleCue,
  SubtitleStyle,
  TextOverlay,
  TimelineSnapshot,
  Track,
} from '@/types';

export type {
  TextOverlay,
  Clip,
  MediaAsset,
  Track,
  SubtitleCue,
  SilenceSegment,
  SubtitleStyle,
  ExportSettings,
};

export const uid = () =>
  `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 9)}`;

export type ToastLevel = 'info' | 'error' | 'success';
export interface Toast {
  message: string;
  level: ToastLevel;
}

// Mirror of Zustand's set/get types so slice creators stay strongly typed.
export type StateSlice = {
  assets: MediaAsset[];
  tracks: Track[];
  clips: Clip[];
  subtitles: SubtitleCue[];
  /** Floating text overlays rendered on top of video. */
  textOverlays: TextOverlay[];
  silenceSegments: SilenceSegment[];
  selection: { clipId?: string; trackId?: string; textOverlayId?: string };
  playing: boolean;
  currentTime: number;
  zoom: number;
  history: TimelineSnapshot[];
  historyIndex: number;
  exportSettings: ExportSettings;
  toast: Toast | null;
  /** Global subtitle style applied to cues without their own override. */
  subtitleStyle: SubtitleStyle;
  /** Current project id (uuid). Created on first save. */
  projectId: string;
  /** Display name for the current project. */
  projectName: string;
  /** When the project was first created. */
  projectCreatedAt: number;
};

// Zustand's `set` accepts either a partial or an updater function.
// We type it as a union so slice creators can use either form.
export type PartialSlice = Partial<StateSlice>;
export type UpdaterFn = (s: StateSlice) => PartialSlice;

export type Setter = (arg: PartialSlice | UpdaterFn) => void;
export type Getter = () => StateSlice & EditorActions;

export interface EditorActions {
  addAsset(asset: MediaAsset): void;
  removeAsset(id: string): void;

  addTrack(kind: 'video' | 'audio'): void;
  removeTrack(id: string): void;
  updateTrack(id: string, patch: Partial<Track>): void;

  addClip(clip: Omit<Clip, 'id'>): string;
  updateClip(id: string, patch: Partial<Clip>): void;
  removeClip(id: string): void;
  splitClipAtCurrent(): void;

  setSelection(sel: { clipId?: string; trackId?: string }): void;
  setPlaying(p: boolean): void;
  setCurrentTime(t: number): void;
  setZoom(z: number): void;

  setSubtitles(subs: SubtitleCue[]): void;

  addTextOverlay(overlay: Omit<TextOverlay, 'id'>): string;
  updateTextOverlay(id: string, patch: Partial<TextOverlay>): void;
  removeTextOverlay(id: string): void;

  setSilenceSegments(segs: SilenceSegment[]): void;
  removeSilenceSegment(id: string): void;
  clearSilence(): void;
  applySilenceRemoval(): void;

  setExportSettings(patch: Partial<ExportSettings>): void;
  setToast(t: Toast | null): void;
  setSubtitleStyle(patch: Partial<SubtitleStyle>): void;
  setProjectName(name: string): void;

  pushHistory(label: string): void;
  undo(): void;
  redo(): void;
  canUndo(): boolean;
  canRedo(): boolean;

  /** Load a different project from storage. Clears current state. */
  loadProjectById(id: string): Promise<void>;
  /** Save current state as a new project. */
  newProject(name: string): Promise<void>;
  /** Mark project as deleted + clear current state. */
  deleteCurrentProject(): Promise<void>;

  reset(): void;
}

export const initialTracks: Track[] = [
  { id: 'track-v1', kind: 'video', name: 'วิดีโอ 1', volume: 1, muted: false, background: { color: '#000000', blur: false }, videoPosition: 'full', videoScale: 1, videoOpacity: 1 },
  { id: 'track-v2', kind: 'video', name: 'วิดีโอ 2', volume: 1, muted: false, background: { color: '#000000', blur: false }, videoPosition: 'pip-br', videoScale: 0.3, videoOpacity: 1 },
  { id: 'track-v3', kind: 'video', name: 'วิดีโอ 3', volume: 1, muted: false, background: { color: '#000000', blur: false }, videoPosition: 'pip-tl', videoScale: 0.25, videoOpacity: 1 },
  { id: 'track-a1', kind: 'audio', name: 'เสียง 1', volume: 1, muted: false, noiseReduction: { enabled: false, amount: 0.5 } },
  { id: 'track-a2', kind: 'audio', name: 'เสียง 2', volume: 1, muted: false, noiseReduction: { enabled: false, amount: 0.5 } },
];

export const defaultExportSettings: ExportSettings = {
  removeSilence: false,
  silenceThresholdDb: -40,
  silenceMinDurationMs: 700,
  width: 1280,
  height: 720,
  fps: 30,
  videoBitrate: '4M',
  audioBitrate: '192k',
};