import type { StoreSiteBlock } from "@alqove/api-client";
import { blockData, bool, paragraphs, str } from "../block-data";
import { marketplaceUrl, type StorefrontRenderContext } from "../links";
import { SectionHeading, StorefrontSection } from "../section";

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

export function ContactBlock({ block, ctx }: ContactBlockProps) {
  const data = blockData(block);
  const heading = str(data, "heading") ?? "Get in touch";
  const body = paragraphs(str(data, "body"));

  const email = bool(data, "show_email", true) ? ctx.shell.contact_email : null;
  const phone = bool(data, "show_phone", true) ? ctx.shell.contact_phone : null;
  const showMessageLink = bool(data, "show_message_link", true);
  const storeId = ctx.shell.store?.id;

  if (!email && !phone && !showMessageLink && body.length === 0) return null;

  return (
    <StorefrontSection surface>
      <div className="max-w-xl">
        <SectionHeading>{heading}</SectionHeading>
        {body.map((paragraph, i) => (
          <p key={i} className="mb-4 text-base leading-relaxed" style={{ color: "var(--sf-muted)" }}>
            {paragraph}
          </p>
        ))}

        <ul className="space-y-2 text-base">
          {email && (
            <li>
              <a href={`mailto:${email}`} className="underline underline-offset-4">
                {email}
              </a>
            </li>
          )}
          {phone && (
            <li>
              <a href={`tel:${phone.replace(/[^\d+]/g, "")}`} className="underline underline-offset-4">
                {phone}
              </a>
            </li>
          )}
        </ul>

        {showMessageLink && storeId && (
          <a
            href={marketplaceUrl(ctx.shell, `/stores/${storeId}`)}
            className="mt-5 inline-flex items-center px-5 py-2.5 text-sm font-semibold transition-opacity hover:opacity-90"
            style={{
              backgroundColor: "var(--sf-primary)",
              color: "var(--sf-on-primary)",
              borderRadius: "var(--sf-radius)",
            }}
          >
            Visit our Alqove store
          </a>
        )}
      </div>
    </StorefrontSection>
  );
}
