import Container from "@/components/Container/Container";
import Section from "@/components/Section/Section";
import Thumbnail from "@/components/Thumbnail/Thumbnail";
import { getCachedMedia } from "@/services/wp";

const resolveImageUrl = async (
  image?: string | number | { url?: string; source_url?: string },
) => {
  if (!image) return undefined;

  if (typeof image === "object") {
    return image.url ?? image.source_url;
  }

  const mediaId = Number(image);
  if (Number.isFinite(mediaId) && mediaId > 0 && /^\d+$/.test(String(image).trim())) {
    const media = await getCachedMedia(mediaId);
    return media?.source_url;
  }

  return String(image);
};

const Quote = async (props: { [rest: string]: any }) => {
  if (!props.quote) return <></>;

  const imageUrl = await resolveImageUrl(props.image ?? props.thumbnail);

  return (
    <Container bgColor="quinary" id={props.anchor}>
      <Section gridArea="thin">
        <div className="flex flex-col md:flex-row gap-sm md:gap-md items-start py-sm md:py-md">
          {imageUrl && (
            <div className="w-full md:w-[15%] flex-shrink-0 max-w-[160px] md:max-w-none">
              <Thumbnail
                width={160}
                height={160}
                imageUrl={imageUrl}
                alt={props.name ?? ""}
              />
            </div>
          )}
          <div className="flex-1 min-w-0">
            <p className="h2 m-none mb-sm text-white normal-case">
              <strong>&quot;</strong>
              {props.quote}
              <strong>&quot;</strong>
            </p>
            {props.name && (
              <p className="text-green m-none normal-case text-[clamp(22px,4vw,26px)] font-bold">
                {props.name}
              </p>
            )}
            {props.role && (
              <p className="text-green h4 m-none uppercase">{props.role}</p>
            )}
          </div>
        </div>
      </Section>
    </Container>
  );
};

export default Quote;
