const NEW_CHAT_DRAFT_KEY = "codexRemote.newChatDraft";
const EMPTY_DRAFT = Object.freeze({ search: "", newProject: false, name: "" });

export function loadNewChatDraft(storage = globalThis.localStorage) {
  try {
    const raw = storage?.getItem(NEW_CHAT_DRAFT_KEY);
    if (!raw) return { ...EMPTY_DRAFT };
    const draft = JSON.parse(raw);
    return {
      search: cleanString(draft.search, 200),
      newProject: draft.newProject === true,
      name: cleanString(draft.name, 80)
    };
  } catch {
    return { ...EMPTY_DRAFT };
  }
}

export function saveNewChatDraft(storage = globalThis.localStorage, draft = EMPTY_DRAFT) {
  try {
    storage?.setItem(NEW_CHAT_DRAFT_KEY, JSON.stringify({
      search: cleanString(draft.search, 200),
      newProject: draft.newProject === true,
      name: cleanString(draft.name, 80)
    }));
  } catch {
    // Storage may be unavailable in private or restricted browsing contexts.
  }
}

export function clearNewChatDraft(storage = globalThis.localStorage) {
  try {
    storage?.removeItem(NEW_CHAT_DRAFT_KEY);
  } catch {
    // Storage may be unavailable in private or restricted browsing contexts.
  }
}

function cleanString(value, maxLength) {
  return typeof value === "string" ? value.slice(0, maxLength) : "";
}
