// school-demo-api.ts
export type SchoolDemoStatus =
  | "New"
  | "Contacted"
  | "Demo Scheduled"
  | "Demo Completed"
  | "Follow-up Required"
  | "Converted"
  | "Not Interested"

export type InstitutionType = "School (K-12)" | "College / University"

export type SchoolDemoFormData = {
  // Institution Type
  institutionType: string // "School (K-12)" | "College / University"

  // Institution Information
  schoolName: string
  cityArea: string
  boardCurriculum?: string
  otherBoard?: string
  universityAffiliation?: string
  otherUniversity?: string
  programsOffered?: string[]
  schoolAddress?: string
  numberOfStudents?: string
  numberOfTeachers?: string
  smartBoardsAvailable: string
  numberOfSmartBoards?: string

  // Management Details
  fullName: string
  designation?: string
  mobileWhatsApp: string
  officialEmail: string
  roleInApproval?: string

  // Areas of Interest
  areasOfInterest?: string[]
  schoolPriority?: string

  // Demo Preferences
  preferredDemo?: string
  preferredDate: string
  preferredTime: string
  consideringSolution?: string
  othersInDemo?: string

  // Tracking
  source?: string
}

export type SchoolDemoRegistration = SchoolDemoFormData & {
  _id: string
  status: SchoolDemoStatus
  followUpNotes?: string
  assignedTo?: string
  nextFollowUpDate?: string
  createdAt?: string
  updatedAt?: string
}

export function getBackendUrl() {
  if (process.env.NEXT_PUBLIC_BACKEND_URL) {
    return process.env.NEXT_PUBLIC_BACKEND_URL.replace(/\/$/, "")
  }
  if (typeof window !== "undefined") {
    if (window.location.hostname === "localhost" || window.location.hostname === "127.0.0.1") {
      return "http://localhost:8080"
    }
    return ""
  }
  return process.env.NEXT_PUBLIC_APP_URL || "http://localhost:8080"
}

export async function readApiMessage(response: Response) {
  const data = await response.json().catch(() => null)
  return data?.message || data?.error || "Request failed. Please try again."
}

export async function submitSchoolDemoRegistration(formData: SchoolDemoFormData) {
  const response = await fetch(`${getBackendUrl()}/api/school-demo-registrations`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify(formData),
  })

  const data = await response.json().catch(() => ({}))

  if (!response.ok || data?.success === false || data?.status === -1) {
    throw new Error(data?.message || data?.error || "Failed to submit registration")
  }

  return data
}