import type { StoreSiteHoursEntry, StorefrontShell } from "@alqove/api-client";

/** `day` is 0 = Sunday, matching JavaScript's `Date#getDay()`. */
export const DAY_NAMES = [
  "Sunday",
  "Monday",
  "Tuesday",
  "Wednesday",
  "Thursday",
  "Friday",
  "Saturday",
] as const;

export interface NormalizedHoursRow {
  day: number;
  name: string;
  closed: boolean;
  label: string;
}

function formatTime(value: string | null | undefined): string | null {
  if (!value) return null;
  const [h, m] = value.split(":");
  const hour = Number(h);
  const minute = Number(m);
  if (Number.isNaN(hour) || Number.isNaN(minute)) return null;

  const suffix = hour >= 12 ? "PM" : "AM";
  const display = hour % 12 === 0 ? 12 : hour % 12;
  return minute === 0
    ? `${display} ${suffix}`
    : `${display}:${String(minute).padStart(2, "0")} ${suffix}`;
}

/**
 * Fill in every weekday so the table never has gaps, and order it Monday-first
 * — which is how opening hours are read, even though `day` is 0 = Sunday.
 */
export function normalizeHours(
  hours: StoreSiteHoursEntry[] | null | undefined,
): NormalizedHoursRow[] {
  const byDay = new Map<number, StoreSiteHoursEntry>();
  for (const entry of hours ?? []) {
    if (typeof entry?.day === "number") byDay.set(entry.day, entry);
  }

  const order = [1, 2, 3, 4, 5, 6, 0];

  return order.map((day) => {
    const entry = byDay.get(day);
    const open = formatTime(entry?.open);
    const close = formatTime(entry?.close);
    const closed = entry?.closed !== false || !open || !close;

    return {
      day,
      name: DAY_NAMES[day],
      closed,
      label: closed ? "Closed" : `${open} – ${close}`,
    };
  });
}

/** Single-line street address, or null when the store hasn't set one. */
export function formatAddress(store: StorefrontShell["store"]): string | null {
  const parts = [
    store?.street1,
    store?.street2,
    [store?.city, store?.state].filter(Boolean).join(", "),
    store?.zip,
  ].filter((p): p is string => Boolean(p && p.trim()));

  return parts.length > 0 ? parts.join(", ") : null;
}

/**
 * Maps link that works without an API key — the provider picks the right app
 * on mobile. Falls back to the store name when there is no address on file.
 */
export function directionsUrl(store: StorefrontShell["store"], override?: string | null): string {
  const query = override?.trim() || formatAddress(store) || store?.name || "";
  return `https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(query)}`;
}
