import {
  createContext,
  useContext,
  useId,
  useSyncExternalStore,
  type ReactNode,
} from "react";
import {
  currentSignOutDeviceFacts,
} from "./sign-out-device";

/**
 * The column of a Settings or Account view: its {@link SettingsCardGroup}s
 * and notes stacked with `space-y-6` (the view's frame provides the page
 * background and the centred column).
 */
export function SettingsPage({
  children,
  className = "",
}: {
  children: ReactNode;
  className?: string;
}) {
  return <div className={`flex flex-col space-y-6 ${className}`.trim()}>{children}</div>;
}

/**
 * One card of settings rows in the enode screen look: an optional
 * `heading-section` `header` above, a bordered `bg-surface-base` card around
 * `children`, an optional quiet `footer` below (may contain a link).
 * When `header` is set the card is `aria-labelledby` that header.
 * `findId` is exposed as `data-find` on the group root.
 */
export function SettingsCardGroup({
  header,
  footer,
  children,
  findId,
  className = "",
}: {
  header?: ReactNode;
  footer?: ReactNode;
  children: ReactNode;
  findId?: string;
  className?: string;
}) {
  const headerId = useId();
  const hasHeader = header != null && header !== false;
  const hasFooter = footer != null && footer !== false;
  return (
    <section className={className || undefined} data-find={findId}>
      {hasHeader && (
        <h3 id={headerId} className="heading-section mb-2 px-1">
          {header}
        </h3>
      )}
      <div
        role="group"
        aria-labelledby={hasHeader ? headerId : undefined}
        className="overflow-hidden rounded-2xl border border-surface-stroke bg-surface-base"
      >
        {children}
      </div>
      {hasFooter && (
        <p className="body-small mt-2 px-1 text-foreground-muted">{footer}</p>
      )}
    </section>
  );
}

const DEVICE_ICON = (
  <>
    <rect x="2" y="5" width="14" height="10" rx="1.5" />
    <path d="M1 19h16" />
    <rect x="18" y="8" width="5" height="11" rx="1" />
  </>
);

const THIS_DEVICE_ICON = (
  <>
    <rect x="6" y="3" width="12" height="18" rx="2" />
    <path d="M10 18h4" />
  </>
);

const BROWSER_ICON = (
  <>
    <rect x="2.5" y="4" width="19" height="16" rx="2.5" />
    <path d="M2.5 8.5h19M6 6.25h.01M8.5 6.25h.01" />
  </>
);

const TABLET_ICON = (
  <>
    <rect x="4" y="2.5" width="16" height="19" rx="2" />
    <path d="M10.5 18.5h3" />
  </>
);

const noSubscription = () => () => {};

/** Which glyph "Only on this device" gets: browser, tablet or phone. */
function thisDeviceKind(): "browser" | "tablet" | "phone" {
  const f = currentSignOutDeviceFacts();
  if (f.platform === "web") return "browser";
  const tablet =
    f.deviceType.toLowerCase() === "tablet" ||
    (f.userAgent ?? "").toLowerCase().startsWith("ipados/");
  return tablet ? "tablet" : "phone";
}

/**
 * True while Settings pages render as sections of the one Settings screen.
 * There the screen states "On all your devices" once at the top, so each
 * section's "everywhere" {@link ScopeBand} is left out; "device" bands stay.
 */
export const SettingsInlineContext = createContext(false);

/**
 * One quiet line above a set of settings groups saying where they apply:
 * `variant="device"` shows a glyph of this device (browser, tablet or phone),
 * `"everywhere"` a monitor+phone glyph. Copy comes from the caller (via
 * `t()`), e.g. device: label "Only on this device", caption "Nothing here
 * follows you to other devices."; everywhere: label "On all your devices",
 * caption "Follows your account to all your devices and the portal."
 * Inside {@link SettingsInlineContext} the "everywhere" band renders nothing.
 */
export function ScopeBand({
  variant,
  label,
  caption,
  className = "",
}: {
  variant: "device" | "everywhere";
  label: string;
  caption: string;
  className?: string;
}) {
  const inline = useContext(SettingsInlineContext);
  const kind = useSyncExternalStore(
    noSubscription,
    thisDeviceKind,
    () => "browser" as const,
  );
  const thisDeviceIcon =
    kind === "browser"
      ? BROWSER_ICON
      : kind === "tablet"
        ? TABLET_ICON
        : THIS_DEVICE_ICON;
  if (inline && variant === "everywhere") return null;
  return (
    <p
      role="note"
      data-scope={variant}
      className={`body-small flex items-start gap-1.5 px-1 text-foreground-muted ${className}`.trim()}
    >
      <svg
        viewBox="0 0 24 24"
        fill="none"
        stroke="currentColor"
        strokeWidth="2"
        strokeLinecap="round"
        strokeLinejoin="round"
        className="mt-px size-3.5 shrink-0"
        aria-hidden="true"
      >
        {variant === "device" ? thisDeviceIcon : DEVICE_ICON}
      </svg>
      <span>
        <span className="text-foreground-default">{label}</span> · {caption}
      </span>
    </p>
  );
}
