import { create } from "zustand";

type RecordingStatus = "idle" | "recording" | "reviewing" | "uploading" | "error";
type RecordingMode = "video" | "audio";

const RECORDING_MODE_KEY = "llink:recording-mode";

function loadRecordingMode(): RecordingMode {
  const stored = localStorage.getItem(RECORDING_MODE_KEY);
  return stored === "audio" ? "audio" : "video";
}

interface RecordingState {
  status: RecordingStatus;
  error: string | null;
  mediaStream: MediaStream | null;
  recordingMode: RecordingMode;
  reviewBlob: Blob | null;
  reviewDurationMs: number;

  setStatus: (status: RecordingStatus) => void;
  setError: (error: string) => void;
  setMediaStream: (stream: MediaStream | null) => void;
  setRecordingMode: (mode: RecordingMode) => void;
  setReviewBlob: (blob: Blob, durationMs: number) => void;
  reset: () => void;
}

export const useRecordingStore = create<RecordingState>((set) => ({
  status: "idle",
  error: null,
  mediaStream: null,
  recordingMode: loadRecordingMode(),
  reviewBlob: null,
  reviewDurationMs: 0,

  setStatus: (status) => set({ status, error: null }),
  setError: (error) => set({ status: "error", error }),
  setMediaStream: (mediaStream) => set({ mediaStream }),
  setRecordingMode: (recordingMode) => {
    localStorage.setItem(RECORDING_MODE_KEY, recordingMode);
    set({ recordingMode });
  },
  setReviewBlob: (reviewBlob, reviewDurationMs) =>
    set({ status: "reviewing", reviewBlob, reviewDurationMs }),
  reset: () =>
    set({
      status: "idle",
      error: null,
      mediaStream: null,
      reviewBlob: null,
      reviewDurationMs: 0,
    }),
}));
