import { http, HttpResponse } from "msw";
import preview from "../../.storybook/preview.tsx";
import { sleep } from "../sleep.ts";
import { SafariCheck } from "./SafariCheck.tsx";

function Content() {
  return (
    <div>
      <h1>Safari Check passed</h1>
      <button
        onClick={() => {
          localStorage.clear();
          window.location.reload();
        }}
      >
        Clear local storage
      </button>
    </div>
  );
}

function userAgentResponse(params: { browserName: string }) {
  return http.get("http://mock.api/ua", async () => {
    await sleep(1500);
    return HttpResponse.json({
      browser: { name: params.browserName },
      device: params.browserName.includes("Mobile") ? { type: "mobile" } : {},
    });
  });
}

const meta = preview.meta({
  title: "Components/SafariCheck",
  component: SafariCheck,
  tags: ["autodocs"],
  decorators: [
    (Story) => (
      <div style={{ height: "100svh", display: "grid" }}>
        <Story />
      </div>
    ),
  ],
  parameters: {
    msw: {
      handlers: {
        ua: userAgentResponse({ browserName: "Safari" }),
      },
    },
  },
});

export const SafariDesktop = meta.story({
  args: {
    children: <Content />,
  },
  parameters: {
    msw: {
      handlers: {
        ua: userAgentResponse({ browserName: "Safari" }),
      },
    },
  },
});

export const SafariMobile = meta.story({
  args: {
    children: <Content />,
  },
  parameters: {
    msw: {
      handlers: {
        ua: userAgentResponse({ browserName: "Safari Mobile" }),
      },
    },
  },
});

export const OtherBrowser = meta.story({
  args: {
    children: <Content />,
  },
  parameters: {
    msw: {
      handlers: {
        ua: userAgentResponse({ browserName: "Chrome" }),
      },
    },
  },
});

/**
 * The check behaviour has been disabled.
 */
export const Disabled = meta.story({
  args: {
    children: <Content />,
    performCheck: false,
  },
});
