"use client";

import {
  useSyncExternalStore,
  type ComponentProps,
  type ReactNode,
} from "react";

type PublicStudioLinkProps = {
  slug: string;
  href: string;
  children: ReactNode;
} & Omit<ComponentProps<"a">, "href" | "children">;

function isLanHost(host: string): boolean {
  const bare = host.split(":")[0] ?? host;
  return /^\d{1,3}(?:\.\d{1,3}){3}$/.test(bare);
}

function subscribe() {
  return () => {};
}

function getClientHost() {
  return window.location.host;
}

function getServerHost() {
  return "";
}

function resolveStudioHref(slug: string, fallbackHref: string, host: string) {
  if (!host || !isLanHost(host)) return fallbackHref;
  const path = `/studio/${slug.trim().toLowerCase()}`;
  return `${window.location.protocol}//${host}${path}`;
}

function resolveStudioLabel(slug: string, fallbackLabel: string, host: string) {
  if (!host || !isLanHost(host)) return fallbackLabel;
  return `${host}/studio/${slug.trim().toLowerCase()}`;
}

/**
 * Ensures public studio links stay on the browser's current host when that
 * host is a LAN IP. Server-rendered fallbacks can still point at
 * `{slug}.localhost` when Host detection falls through to APP_URL.
 */
export function PublicStudioLink({
  slug,
  href,
  children,
  ...rest
}: PublicStudioLinkProps) {
  const host = useSyncExternalStore(subscribe, getClientHost, getServerHost);
  const resolvedHref =
    typeof window === "undefined"
      ? href
      : resolveStudioHref(slug, href, host);

  return (
    <a href={resolvedHref} {...rest}>
      {children}
    </a>
  );
}

type PublicStudioHostLabelProps = {
  slug: string;
  label: string;
  className?: string;
};

export function PublicStudioHostLabel({
  slug,
  label,
  className,
}: PublicStudioHostLabelProps) {
  const host = useSyncExternalStore(subscribe, getClientHost, getServerHost);
  const resolved =
    typeof window === "undefined"
      ? label
      : resolveStudioLabel(slug, label, host);

  return <span className={className}>{resolved}</span>;
}
