import { BRAND_VOICES } from "@/lib/constants";
import { DEFAULT_ACCOUNTS } from "@/lib/project/defaults";
import type { BrandProfile, PostingContextData } from "@/types/workflow";
import type { useProjectsStore } from "./projects-store";

type ProjectsState = ReturnType<typeof useProjectsStore.getState>;

const defaultBrand: BrandProfile = {
  companyName: "",
  tagline: "",
  industry: "",
  brandVoice: BRAND_VOICES[0],
  logoDataUrl: null,
  logoFileName: null,
  contactPhone: "",
  contactEmail: "",
};

const emptyContext: PostingContextData = {
  name: "Content Sequence",
  posts: [],
  saved: false,
};

/** Returns a stable reference — never allocate inside this selector. */
export function selectActiveAccounts(state: ProjectsState) {
  const id = state.activeProjectId;
  if (!id) return DEFAULT_ACCOUNTS;
  const accounts = state.dataByProjectId[id]?.accounts;
  return Array.isArray(accounts) ? accounts : DEFAULT_ACCOUNTS;
}

export function selectActiveBrand(state: ProjectsState) {
  const id = state.activeProjectId;
  if (!id) return defaultBrand;
  return state.dataByProjectId[id]?.brand ?? defaultBrand;
}

export function selectActiveContext(state: ProjectsState) {
  const id = state.activeProjectId;
  if (!id) return emptyContext;
  const ctx = state.dataByProjectId[id]?.context ?? emptyContext;
  if (!Array.isArray(ctx.posts)) {
    return { ...ctx, posts: [] };
  }
  return ctx;
}

export function selectActiveSelectedPostId(state: ProjectsState) {
  const id = state.activeProjectId;
  if (!id) return null;
  return state.dataByProjectId[id]?.selectedPostId ?? null;
}

export function selectActiveProjectRecord(state: ProjectsState) {
  if (!state.activeProjectId) return null;
  return state.projects.find((p) => p.id === state.activeProjectId) ?? null;
}
