import type { ReactNode } from "react";
import Link from "next/link";
import { cn } from "@/lib/utils";
import type { Block } from "@/lib/blocks/schema";

// Every block is drawn by this one shell. Its colours, fonts and buttons come from CSS variables that Site Settings > Design
// (and the website's theme) set on the site root; the .blk-* rules live in designCss (site-frame.tsx).
const BG: Record<Block["style"]["background"], string> = { none: "", muted: "blk-bg-muted", primary: "blk-bg-primary", dark: "blk-bg-dark" };
const PAD: Record<Block["style"]["paddingY"], string> = { sm: "blk-py-sm", md: "blk-py-md", lg: "blk-py-lg" };

export function Section({ style, children, id, label }: { style: Block["style"]; children: ReactNode; id?: string; label?: string }) {
  return (
    <section id={id} aria-label={label} className={cn("blk", BG[style.background], PAD[style.paddingY])}>
      <div className="mx-auto w-full max-w-6xl px-4 sm:px-6">{children}</div>
    </section>
  );
}

export function Heading({ children, level = 2 }: { children: ReactNode; level?: 1 | 2 | 3 }) {
  if (!children) return null;
  const cls = "site-heading blk-title mb-6 text-2xl font-bold tracking-tight sm:text-3xl";
  return level === 1 ? <h1 className={cls}>{children}</h1> : level === 3 ? <h3 className={cls}>{children}</h3> : <h2 className={cls}>{children}</h2>;
}

/** Link whose href was validated by the block schema (path, https, mailto, tel). */
export function SafeLink({ href, className, children }: { href: string; className?: string; children: ReactNode }) {
  if (!href) return null;
  if (href.startsWith("/")) return <Link href={href} className={className}>{children}</Link>;
  const external = href.startsWith("https://");
  return (
    <a href={href} className={className} {...(external ? { target: "_blank", rel: "noopener noreferrer" } : {})}>
      {children}
    </a>
  );
}

export const buttonCls = "site-block-btn blk-btn";
export const buttonOnPrimaryCls = "site-block-btn blk-btn blk-btn-inverse";
