import {
  PortableText,
  type PortableTextComponents,
} from "@portabletext/react";
import { SanityImage } from "./sanity-image";

const components: PortableTextComponents = {
  block: {
    h2: ({ children }) => <h2 className="mt-10 mb-3 text-2xl">{children}</h2>,
    h3: ({ children }) => <h3 className="mt-8 mb-2 text-xl">{children}</h3>,
    blockquote: ({ children }) => (
      <blockquote className="my-7 border-l-2 border-brand pl-5 font-display text-xl italic text-ink-soft">
        {children}
      </blockquote>
    ),
    normal: ({ children }) => (
      <p className="my-4 leading-relaxed text-ink-soft">{children}</p>
    ),
  },
  list: {
    bullet: ({ children }) => (
      <ul className="my-4 list-disc space-y-1 pl-6 text-ink-soft">{children}</ul>
    ),
    number: ({ children }) => (
      <ol className="my-4 list-decimal space-y-1 pl-6 text-ink-soft">
        {children}
      </ol>
    ),
  },
  marks: {
    strong: ({ children }) => (
      <strong className="font-semibold text-ink">{children}</strong>
    ),
    em: ({ children }) => <em>{children}</em>,
    link: ({ value, children }) => (
      <a
        href={value?.href}
        target="_blank"
        rel="noopener noreferrer"
        className="font-medium text-brand-bright underline underline-offset-2 hover:text-brand"
      >
        {children}
      </a>
    ),
  },
  types: {
    image: ({ value }) => (
      <figure className="my-8">
        <SanityImage
          image={value}
          alt={value?.alt || ""}
          className="w-full rounded-2xl"
          sizes="(min-width: 768px) 48rem, 100vw"
        />
      </figure>
    ),
  },
};

export function RichText({ value }: { value: unknown }) {
  if (!value) return null;
  return (
    <div className="text-[1.05rem]">
      <PortableText value={value as never} components={components} />
    </div>
  );
}
