import { planScheduleSlots, parseProjectTimezone } from "./plan-times";

/** Stable seed when schedule not saved yet — same times per project until Save Schedule. */
export function stableScheduleSeed(projectId: string): number {
  let hash = 0;
  for (let i = 0; i < projectId.length; i++) {
    hash = (hash * 31 + projectId.charCodeAt(i)) % 997;
  }
  return hash || 42;
}

export function resolveScheduleSeed(projectId: string, scheduleSeed?: number): number {
  if (typeof scheduleSeed === "number" && scheduleSeed > 0) return scheduleSeed;
  return stableScheduleSeed(projectId);
}

export function formatTimezoneShort(timezone: string, now = new Date()): string {
  const tz = parseProjectTimezone(timezone);
  try {
    const part = new Intl.DateTimeFormat("en-US", {
      timeZone: tz,
      timeZoneName: "short",
    })
      .formatToParts(now)
      .find((p) => p.type === "timeZoneName");
    return part?.value ?? tz;
  } catch {
    return tz;
  }
}

export interface PlannedScheduleView {
  timezone: string;
  timezoneLabel: string;
  scheduleSeed: number;
  postsPerDay: 1 | 2;
  slots: ReturnType<typeof planScheduleSlots>;
  slotTimes: string[];
  summary: string;
}

export function buildPlannedScheduleView(input: {
  projectId: string;
  timezone: string;
  postsPerDay: 1 | 2;
  scheduleSeed?: number;
}): PlannedScheduleView {
  const seed = resolveScheduleSeed(input.projectId, input.scheduleSeed);
  const tz = parseProjectTimezone(input.timezone);
  const tzLabel = formatTimezoneShort(tz);
  const slots = planScheduleSlots(input.postsPerDay, seed);
  const slotTimes = slots.map((s) => `${s.display} ${tzLabel}`);
  const summary =
    input.postsPerDay === 2
      ? `Morning & evening (${tzLabel}) · ${slotTimes.join(" · ")}`
      : `${slotTimes[0] ?? "Not set"}`;

  return {
    timezone: tz,
    timezoneLabel: tzLabel,
    scheduleSeed: seed,
    postsPerDay: input.postsPerDay,
    slots,
    slotTimes,
    summary,
  };
}
