import { useCallback, useRef, useState } from 'react';
import { ArrowUpRight, MapPin } from '@/site/components/ui/icons';
import { useOnEnter } from '@/site/hooks/use-in-view';
import { useT } from '@/site/i18n';

type ContactMapProps = {
    /** Address of the embeddable Google Maps frame. */
    src: string;
    /** The address as text (shown until the map loads, and without JavaScript). */
    address: string;
    /** Link that opens the place in the maps application, if set. */
    href: string | null;
};

/**
 * Google Maps frame with the clinic's address.
 *
 * The frame is third-party content (it talks to Google and may set cookies),
 * so nothing is requested until the visitor actually scrolls to it. Until
 * then — and when JavaScript is off — the address and a link to the map are
 * shown in its place.
 */
export function ContactMap({ src, address, href }: ContactMapProps) {
    const t = useT();
    const ref = useRef<HTMLDivElement>(null);
    const [shown, setShown] = useState(false);

    const show = useCallback(() => setShown(true), []);

    useOnEnter(ref, show, '0px 0px 15% 0px');

    return (
        <div
            ref={ref}
            className="border-line bg-stage-3 relative isolate aspect-[4/3] overflow-hidden rounded-xl border sm:aspect-[16/9] lg:aspect-[21/9]"
        >
            <div className="absolute inset-0 -z-10 grid place-items-center p-6 text-center">
                <div>
                    <MapPin className="text-accent-fg mx-auto size-8" />
                    <p className="mt-4 max-w-xs text-lg">{address}</p>
                    {href ? (
                        <a
                            href={href}
                            target="_blank"
                            rel="noopener noreferrer"
                            className="text-accent-fg mt-3 inline-flex items-center gap-1.5 text-sm font-medium underline underline-offset-4"
                        >
                            {t.contact.info.map}
                            <ArrowUpRight className="size-4" />
                            <span className="sr-only">({t.common.newTab})</span>
                        </a>
                    ) : null}
                </div>
            </div>

            {shown ? (
                <iframe
                    src={src}
                    title={t.contact.mapTitle}
                    loading="lazy"
                    referrerPolicy="no-referrer-when-downgrade"
                    allowFullScreen
                    className="absolute inset-0 size-full border-0"
                />
            ) : null}
        </div>
    );
}
