import { describe, expect, it } from "vitest";
import { directionsUrl, formatAddress, normalizeHours } from "../hours";

describe("normalizeHours", () => {
  it("returns all seven days, Monday first", () => {
    const rows = normalizeHours([]);
    expect(rows).toHaveLength(7);
    expect(rows.map((r) => r.day)).toEqual([1, 2, 3, 4, 5, 6, 0]);
    expect(rows[0].name).toBe("Monday");
    expect(rows[6].name).toBe("Sunday");
  });

  it("formats a day's times in 12-hour form", () => {
    const [monday] = normalizeHours([
      { day: 1, closed: false, open: "09:30", close: "17:00" },
    ]);
    expect(monday.label).toBe("9:30 AM – 5 PM");
    expect(monday.closed).toBe(false);
  });

  it("handles noon and midnight without saying 0", () => {
    const [monday] = normalizeHours([
      { day: 1, closed: false, open: "00:00", close: "12:00" },
    ]);
    expect(monday.label).toBe("12 AM – 12 PM");
  });

  it("labels closed days", () => {
    const rows = normalizeHours([{ day: 0, closed: true, open: null, close: null }]);
    const sunday = rows.find((r) => r.day === 0)!;
    expect(sunday.closed).toBe(true);
    expect(sunday.label).toBe("Closed");
  });

  it("treats a day with missing times as closed rather than rendering a broken range", () => {
    const [monday] = normalizeHours([{ day: 1, closed: false, open: "09:00", close: null }]);
    expect(monday.closed).toBe(true);
    expect(monday.label).toBe("Closed");
  });

  it("fills in days the seller never configured", () => {
    const rows = normalizeHours([{ day: 3, closed: false, open: "10:00", close: "18:00" }]);
    expect(rows.filter((r) => r.closed)).toHaveLength(6);
  });
});

describe("formatAddress", () => {
  it("joins the parts a store has filled in", () => {
    expect(
      formatAddress({
        street1: "12 Main St",
        street2: "Unit 3",
        city: "Portland",
        state: "OR",
        zip: "97201",
      }),
    ).toBe("12 Main St, Unit 3, Portland, OR, 97201");
  });

  it("returns null when nothing is set", () => {
    expect(formatAddress({})).toBeNull();
    expect(formatAddress({ street1: "  " })).toBeNull();
  });
});

describe("directionsUrl", () => {
  it("uses the store address", () => {
    const url = directionsUrl({ city: "Portland", state: "OR", name: "Vault" });
    expect(url).toContain("https://www.google.com/maps/search/?api=1&query=");
    expect(decodeURIComponent(url)).toContain("Portland, OR");
  });

  it("prefers a seller override", () => {
    const url = directionsUrl({ city: "Portland", state: "OR" }, "Pike Place Market");
    expect(decodeURIComponent(url)).toContain("Pike Place Market");
  });

  it("falls back to the store name when there is no address", () => {
    const url = directionsUrl({ name: "Vintage Vault" });
    expect(decodeURIComponent(url)).toContain("Vintage Vault");
  });
});
