import type { StoreSiteBlock } from "@alqove/api-client";
import { blockData, safeHref, str } from "../block-data";
import { resolveAuthoredHref, type StorefrontRenderContext } from "../links";
import { readableTextOn } from "../theme";

interface CtaBlockProps {
  block: StoreSiteBlock;
  ctx: StorefrontRenderContext;
}

const HEX = /^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;

export function CtaBlock({ block, ctx }: CtaBlockProps) {
  const data = blockData(block);
  const headline = str(data, "headline");
  const body = str(data, "body");
  const label = str(data, "label");
  const href = resolveAuthoredHref(safeHref(str(data, "href")), ctx);

  if (!headline || !label || !href) return null;

  const rawBackground = str(data, "background");
  const background = rawBackground && HEX.test(rawBackground) ? rawBackground : null;

  // A seller-picked background needs its own contrast check; without one we
  // fall back to the theme's primary, which is already paired with --sf-on-primary.
  const foreground = background ? readableTextOn(background) : "var(--sf-on-primary)";

  return (
    <section
      className="px-6 py-16"
      style={{ backgroundColor: background ?? "var(--sf-primary)", color: foreground }}
    >
      <div className="mx-auto flex max-w-3xl flex-col items-center gap-4 text-center">
        <h2 className="text-3xl font-semibold tracking-tight">{headline}</h2>
        {body && (
          <p className="text-base opacity-90 whitespace-pre-line">{body}</p>
        )}
        <a
          href={href}
          className="mt-2 inline-flex items-center px-6 py-3 text-sm font-semibold transition-opacity hover:opacity-90"
          style={{
            backgroundColor: foreground,
            color: background ?? "var(--sf-primary)",
            borderRadius: "var(--sf-radius)",
          }}
        >
          {label}
        </a>
      </div>
    </section>
  );
}
