/**
 * The pure half of "add to calendar": ICS formatting, the schedule resolution
 * and the two destination builders.
 *
 * Separated from the button so the date arithmetic and the escaping can be
 * tested. Both have rules that are easy to get wrong and invisible when wrong:
 * an all-day `DTEND` is **exclusive**, and an unescaped comma truncates an ICS
 * line.
 */

/** Every field is nullable — the API omits times and locations freely. */
export interface CalendarPayload {
  title_en?: string | null;
  title_ar?: string | null;
  location_en?: string | null;
  location_ar?: string | null;
  start_date?: string | null;
  end_date?: string | null;
  start_time?: string | null;
  end_time?: string | null;
  /**
   * Deep link back to the item, put in the Google entry's description.
   * Defaults to the current page, resolved at click time so there is no
   * server/client difference to reconcile.
   */
  details_url?: string | null;
}

export const formatICSDate = (date: Date) =>
  date.toISOString().replace(/[-:]/g, "").split(".")[0] + "Z";

/** `2026-08-13` → `20260813`, the ICS form of a date-only value. */
export const formatICSDateOnly = (isoDate: string) => isoDate.replace(/-/g, "");

/**
 * An all-day `DTEND` is exclusive, so a one-day event ends on the next day.
 * The arithmetic is done in UTC to keep it away from timezone drift — these
 * are calendar dates, not instants.
 */
export const nextDay = (isoDate: string) => {
  const [year, month, day] = isoDate.split("-").map(Number);
  const date = new Date(Date.UTC(year, month - 1, day));
  date.setUTCDate(date.getUTCDate() + 1);
  return date.toISOString().slice(0, 10);
};

/**
 * Backslashes, commas and newlines are delimiters in an ICS property value —
 * an unescaped comma in a location ("Kuwait City, Kuwait") truncates the line.
 */
export const escapeICSText = (value?: string | null) =>
  // `?? ""` rather than a default parameter: the API sends null, not undefined,
  // and a default only fills in for undefined.
  (value ?? "")
    .replace(/\\/g, "\\\\")
    .replace(/\n/g, "\\n")
    .replace(/,/g, "\\,");

/** Normalises `HH:mm` to the `HH:mm:ss` both `Date` and ICS expect. */
export const withSeconds = (time?: string | null) => {
  const value = time || "";
  return value.split(":").length === 2 ? `${value}:00` : value;
};

export interface ResolvedSchedule {
  /** Null when the item has no usable start/end date. */
  startDay: string;
  endDay: string;
  /** Both null for an all-day entry. */
  start: Date | null;
  end: Date | null;
}

/**
 * Times are optional on both events and opportunities — the API returns null
 * for them. Those become all-day entries rather than an error, which is what
 * the old `new Date("2026-08-13T")` produced.
 */
export const resolveSchedule = (payload: CalendarPayload): ResolvedSchedule | null => {
  const startDay = payload.start_date;
  const endDay = payload.end_date || payload.start_date;
  if (!startDay || !endDay) return null;

  const startTime = withSeconds(payload.start_time);
  const endTime = withSeconds(payload.end_time);

  if (!startTime || !endTime) {
    return { startDay, endDay, start: null, end: null };
  }

  const start = new Date(`${startDay}T${startTime}+03:00`);
  const end = new Date(`${endDay}T${endTime}+03:00`);
  if (Number.isNaN(start.getTime()) || Number.isNaN(end.getTime())) {
    return null;
  }

  // A late-night session can finish after midnight on the following day.
  if (startDay === endDay && end < start) end.setUTCDate(end.getUTCDate() + 1);
  if (end <= start) return null;

  return { startDay, endDay, start, end };
};

/**
 * Google's "add event" template link. `dates` is either two UTC instants or,
 * for an all-day entry, two plain dates whose end is exclusive — the same rule
 * ICS uses, which is why both paths share `nextDay()`.
 */
export const buildGoogleCalendarUrl = (
  schedule: ResolvedSchedule,
  title: string,
  location: string,
  detailsUrl?: string | null
) => {
  const dates =
    schedule.start && schedule.end
      ? `${formatICSDate(schedule.start)}/${formatICSDate(schedule.end)}`
      : `${formatICSDateOnly(schedule.startDay)}/${formatICSDateOnly(
          nextDay(schedule.endDay)
        )}`;

  const params = new URLSearchParams({
    action: "TEMPLATE",
    text: title,
    dates,
  });
  if (location) params.set("location", location);
  if (detailsUrl) params.set("details", detailsUrl);

  return `https://calendar.google.com/calendar/render?${params.toString()}`;
};

export const buildIcsContent = (
  schedule: ResolvedSchedule,
  title: string,
  location: string
) => {
  const dtStart =
    schedule.start && schedule.end
      ? `DTSTART:${formatICSDate(schedule.start)}`
      : `DTSTART;VALUE=DATE:${formatICSDateOnly(schedule.startDay)}`;
  const dtEnd =
    schedule.start && schedule.end
      ? `DTEND:${formatICSDate(schedule.end)}`
      : `DTEND;VALUE=DATE:${formatICSDateOnly(nextDay(schedule.endDay))}`;

  return `
BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//MyApp//EN
CALSCALE:GREGORIAN
BEGIN:VEVENT
SUMMARY:${escapeICSText(title)}
LOCATION:${escapeICSText(location)}
${dtStart}
${dtEnd}
END:VEVENT
END:VCALENDAR
`.trim();
};
