"use client";

import { create } from "zustand";

export type ViewName =
  | "home"
  | "movies"
  | "series"
  | "detail"
  | "watch"
  | "live"
  | "music"
  | "search"
  | "subscription"
  | "profile"
  | "favorites"
  | "history"
  | "admin"
  | "ai-center"
  | "support";

export interface ViewState {
  view: ViewName;
  // payload for detail/watch views
  contentType?: "movie" | "series";
  contentSlug?: string;
  // search query
  searchQuery?: string;
  // admin tab
  adminTab?: string;
}

interface AppStore extends ViewState {
  navigate: (view: ViewName, params?: Partial<ViewState>) => void;
  openDetail: (contentType: "movie" | "series", slug: string) => void;
  openWatch: (contentType: "movie" | "series", slug: string) => void;
  search: (query: string) => void;
  reset: () => void;
}

const initialState: ViewState = {
  view: "home",
  contentType: undefined,
  contentSlug: undefined,
  searchQuery: undefined,
  adminTab: undefined,
};

export const useAppStore = create<AppStore>((set) => ({
  ...initialState,
  navigate: (view, params = {}) =>
    set({ ...initialState, view, ...params }),
  openDetail: (contentType, contentSlug) =>
    set({ view: "detail", contentType, contentSlug, searchQuery: undefined }),
  openWatch: (contentType, contentSlug) =>
    set({ view: "watch", contentType, contentSlug, searchQuery: undefined }),
  search: (query) =>
    set({ view: "search", searchQuery: query, contentType: undefined, contentSlug: undefined }),
  reset: () => set(initialState),
}));

// UI store for global UI state (player, modals, toasts, etc.)
interface UIStore {
  playerOpen: boolean;
  playerContent: { type: "movie" | "series"; slug: string; title: string; poster?: string } | null;
  adminSidebarOpen: boolean;
  setPlayerOpen: (open: boolean, content?: UIStore["playerContent"]) => void;
  toggleAdminSidebar: () => void;
  setAdminSidebar: (open: boolean) => void;
}

export const useUIStore = create<UIStore>((set) => ({
  playerOpen: false,
  playerContent: null,
  adminSidebarOpen: true,
  setPlayerOpen: (open, content) =>
    set((s) => ({
      playerOpen: open,
      playerContent: content ?? s.playerContent,
    })),
  toggleAdminSidebar: () => set((s) => ({ adminSidebarOpen: !s.adminSidebarOpen })),
  setAdminSidebar: (open) => set({ adminSidebarOpen: open }),
}));

// Auth store (client-side mock for demo; real auth via /api/auth)
interface User {
  id: string;
  name: string;
  email: string;
  plan: string;
  avatar?: string;
  isAdmin: boolean;
}

interface AuthStore {
  user: User | null;
  setUser: (user: User | null) => void;
  logout: () => void;
}

export const useAuthStore = create<AuthStore>((set) => ({
  user: null,
  setUser: (user) => set({ user }),
  logout: () => set({ user: null }),
}));
