import type { ScoringRules } from "~/lib/scoring-types";

export const WIZARD_SS_KEY = "brackt_new_league_wizard";

export type WizardSnapshot = {
  leagueName: string;
  teamCount: number;
  joinAsPlayer: boolean;
  selectedTemplate: string;
  selectedSports: string[];
  draftRounds: number;
  draftDate: string;
  draftTime: string;
  autoStartDraft: boolean;
  timerMode: "chess_clock" | "standard";
  draftSpeed: string;
  overnightMode: "none" | "league" | "per_user";
  overnightStart: string;
  overnightEnd: string;
  overnightTimezone: string;
  scoringPreset: "brackt" | "omnifantasy" | "custom";
  scoringRules: ScoringRules;
  userTimezone: string;
};

type SS = { getItem(k: string): string | null; setItem(k: string, v: string): void; removeItem(k: string): void };

function ss(): SS | null {
  const g = globalThis as Record<string, unknown>;
  return (typeof g["sessionStorage"] !== "undefined" ? g["sessionStorage"] : null) as SS | null;
}

export function saveWizardState(snapshot: WizardSnapshot) {
  try { ss()?.setItem(WIZARD_SS_KEY, JSON.stringify(snapshot)); } catch {}
}

export function loadWizardState(): WizardSnapshot | null {
  try {
    const raw = ss()?.getItem(WIZARD_SS_KEY);
    if (!raw) return null;
    const parsed = JSON.parse(raw) as Partial<WizardSnapshot>;
    return { autoStartDraft: false, ...parsed } as WizardSnapshot;
  } catch { return null; }
}

export function clearWizardState() {
  try { ss()?.removeItem(WIZARD_SS_KEY); } catch {}
}

export function buildFormDataFromSnapshot(s: WizardSnapshot): FormData {
  const fd = new FormData();
  fd.append("name", s.leagueName);
  fd.append("teamCount", s.teamCount.toString());
  if (s.selectedTemplate && s.selectedTemplate !== "customize") {
    fd.append("templateId", s.selectedTemplate);
  }
  fd.append("draftRounds", s.draftRounds.toString());
  if (s.draftDate && s.draftTime) {
    fd.append("draftDateTime", new Date(`${s.draftDate}T${s.draftTime}`).toISOString());
  }
  if (s.autoStartDraft) fd.append("autoStartDraft", "on");
  fd.append("draftTimerMode", s.timerMode);
  fd.append("draftSpeed", s.draftSpeed);
  fd.append("overnightPauseMode", s.overnightMode);
  if (s.overnightMode !== "none") {
    fd.append("overnightPauseStart", s.overnightStart);
    fd.append("overnightPauseEnd", s.overnightEnd);
    fd.append("overnightPauseTimezone", s.overnightTimezone);
  }
  (["pointsFor1st", "pointsFor2nd", "pointsFor3rd", "pointsFor4th",
    "pointsFor5th", "pointsFor6th", "pointsFor7th", "pointsFor8th"] as const
  ).forEach((k) => fd.append(k, s.scoringRules[k].toString()));
  for (const id of s.selectedSports) fd.append("sportsSeasons", id);
  if (s.joinAsPlayer) fd.append("joinAsPlayer", "on");
  if (s.userTimezone) fd.append("userTimezone", s.userTimezone);
  return fd;
}
