import { ComponentChildren } from "preact";
import Search from "@islands/Search.tsx";
import { GenericResource } from "@lib/marka/schema.ts";

export type Props = {
  children: ComponentChildren;
  title?: string;
  name?: string;
  url: URL | string;
  description?: string;
  context?: { type: string };
  searchResults?: GenericResource[];
};

function getQFromUrl(u: string | URL): string | null {
  try {
    const _u = typeof u === "string" ? new URL(u) : u;
    return _u?.searchParams.get("q");
  } catch (_e) {
    return null;
  }
}

export const MainLayout = (
  { children, url, context, searchResults }: Props,
) => {
  const q = getQFromUrl(url);

  if (typeof q === "string") {
    return (
      <Search
        {...context}
        q={q}
        results={searchResults}
      />
    );
  }

  return children;
};
