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

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

/**
 * Address plus a directions hand-off. Deliberately no embedded map iframe —
 * that would need a per-deployment API key and would load a third-party
 * tracker onto every seller's domain.
 */
export function MapBlock({ block, ctx }: MapBlockProps) {
  const data = blockData(block);
  const store = ctx.shell.store;
  const heading = str(data, "heading") ?? "Find us";
  const override = str(data, "address_override");
  const note = str(data, "note") ?? ctx.shell.directions_note;
  const showLink = bool(data, "show_directions_link", true);

  const address = override ?? formatAddress(store);

  if (!address && !note) return null;

  return (
    <StorefrontSection>
      <div className="max-w-xl">
        <SectionHeading>{heading}</SectionHeading>
        {address && (
          <address className="not-italic text-base leading-relaxed">
            {address.split(", ").map((line, i) => (
              <span key={i} className="block">
                {line}
              </span>
            ))}
          </address>
        )}
        {note && (
          <p className="mt-4 whitespace-pre-line text-sm" style={{ color: "var(--sf-muted)" }}>
            {note}
          </p>
        )}
        {showLink && (
          <a
            href={directionsUrl(store, override)}
            target="_blank"
            rel="noopener noreferrer"
            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)",
            }}
          >
            Get directions
          </a>
        )}
      </div>
    </StorefrontSection>
  );
}
