import dayjs from "dayjs";

export const JO_CREATE_PLAN_START_KEY = "fpsms.jo.create.rememberPlanStart";

export type JoCreatePlanStartPrefs = {
  enabled: boolean;
  planStart: string | null;
};

const DEFAULT_PREFS: JoCreatePlanStartPrefs = { enabled: false, planStart: null };

function isValidInputDate(value: string | null | undefined): value is string {
  return Boolean(value && dayjs(value).isValid());
}

export function loadJoCreatePlanStartPrefs(): JoCreatePlanStartPrefs {
  if (typeof window === "undefined") {
    return DEFAULT_PREFS;
  }
  try {
    const raw = sessionStorage.getItem(JO_CREATE_PLAN_START_KEY);
    if (!raw) {
      return DEFAULT_PREFS;
    }
    const parsed = JSON.parse(raw) as JoCreatePlanStartPrefs;
    if (!parsed.enabled) {
      return { enabled: false, planStart: null };
    }
    if (isValidInputDate(parsed.planStart)) {
      return { enabled: true, planStart: parsed.planStart };
    }
  } catch {
    // ignore invalid storage
  }
  return DEFAULT_PREFS;
}

export function saveJoCreatePlanStartPrefs(prefs: JoCreatePlanStartPrefs): void {
  if (typeof window === "undefined") {
    return;
  }
  try {
    sessionStorage.setItem(JO_CREATE_PLAN_START_KEY, JSON.stringify(prefs));
  } catch {
    // ignore quota / private mode errors
  }
}
