import type { BuilderScreen } from "@/lib/admin/builder/types";
import type { ScreenDefinition } from "@/lib/funnel/types";
import type { BuilderState } from "./types";
import { buildInfoDefaults } from "./defaults/info";
import { buildListDefaults } from "./defaults/list";
import { buildFormDefaults } from "./defaults/form";
import { buildDateDefaults } from "./defaults/date";
import { buildCouponDefaults } from "./defaults/coupon";
import { buildEmailDefaults } from "./defaults/email";
import { buildLoadersDefaults } from "./defaults/loaders";
import { buildSoulmateDefaults } from "./defaults/soulmate";
import { buildTrialPaymentDefaults } from "./defaults/trialPayment";
import { buildSpecialOfferDefaults } from "./defaults/specialOffer";
import { buildTrialChoiceDefaults } from "./defaults/trialChoice";

/**
 * Marks the state as dirty if it has changed
 */
export function withDirty(
  state: BuilderState,
  next: BuilderState
): BuilderState {
  if (next === state) {
    return state;
  }
  return { ...next, isDirty: true };
}

/**
 * Generates a unique screen ID
 */
export function generateScreenId(existing: string[]): string {
  let index = existing.length + 1;
  let attempt = `screen-${index}`;
  while (existing.includes(attempt)) {
    index += 1;
    attempt = `screen-${index}`;
  }
  return attempt;
}

/**
 * Creates a new screen based on template with sensible defaults
 */
export function createScreenByTemplate(
  template: ScreenDefinition["template"],
  id: string
): BuilderScreen {
  switch (template) {
    case "info":
      return buildInfoDefaults(id);
    case "list":
      return buildListDefaults(id);
    case "form":
      return buildFormDefaults(id);
    case "date":
      return buildDateDefaults(id);
    case "coupon":
      return buildCouponDefaults(id);
    case "email":
      return buildEmailDefaults(id);
    case "loaders":
      return buildLoadersDefaults(id);
    case "soulmate":
      return buildSoulmateDefaults(id);
    case "trialPayment":
      return buildTrialPaymentDefaults(id);
    case "specialOffer":
      return buildSpecialOfferDefaults(id);
    case "trialChoice":
      return buildTrialChoiceDefaults(id);
    default:
      throw new Error(`Unknown template: ${template}`);
  }
}
