import { usePage } from '@inertiajs/react';
import { useEffect, useId, useRef, useState } from 'react';
import { CrmForm } from '@/site/components/sections/crm-form';
import { WhatsAppForm } from '@/site/components/sections/whatsapp-form';
import { Close, WhatsApp } from '@/site/components/ui/icons';
import { useShared } from '@/site/hooks/use-shared';
import { useT } from '@/site/i18n';
import { cx } from '@/site/lib/cx';
import { onWhatsAppFormRequest } from '@/site/lib/whatsapp-form';
import type { CrmForms, WhatsAppFormConfig } from '@/site/types';

const corner =
    'fixed end-[max(1rem,env(safe-area-inset-right))] bottom-[max(1rem,env(safe-area-inset-bottom))] z-40';

const bubble =
    'bg-whatsapp text-ink grid size-15 place-items-center rounded-full md:size-16 shadow-[0_12px_32px_-10px_rgb(0_0_0/0.55)] transition-transform duration-300 group-hover:scale-105';

const label =
    'floating-whatsapp-label bg-ink text-bone border-line pointer-events-none absolute end-full top-1/2 me-3 rounded-full border px-4 py-2 text-sm font-medium whitespace-nowrap';

/**
 * WhatsApp button fixed to the bottom corner of every page.
 *
 * It never links to a WhatsApp number: it opens a small panel with a short
 * form — the visitor leaves a name and a phone number first and is then
 * taken to the chat (docs/DECISIONS.md K39). The form is the CRM's while
 * the CRM forms are on (K34), otherwise the site's own. It is left out
 * while WhatsApp is not offered (CRM forms off and no number in Admin →
 * Site ayarları → İletişim).
 */
export function FloatingContact() {
    const { site } = useShared();
    const { url } = usePage();

    if (!site.whatsapp) {
        return null;
    }

    // A new page starts with the panel closed (and a fresh form).
    return <WhatsAppPanel key={url} crm={site.crm} form={site.whatsapp} />;
}

/**
 * The button and its form panel. The form is set up the first time the
 * panel opens (the CRM's form page is requested only then) and stays while
 * the page is open, so what was typed survives closing the panel. Escape
 * closes it and returns focus to the button. Other buttons can ask it to
 * open (lib/whatsapp-form.ts). Without JavaScript the button could do
 * nothing, so it is not shown.
 */
function WhatsAppPanel({
    crm,
    form,
}: {
    crm: CrmForms | null;
    form: WhatsAppFormConfig;
}) {
    const t = useT();
    const id = useId();
    const button = useRef<HTMLButtonElement>(null);
    const panel = useRef<HTMLDivElement>(null);
    const [open, setOpen] = useState(false);
    const [opened, setOpened] = useState(false);

    const toggle = () => {
        setOpen((value) => !value);
        setOpened(true);
    };

    // Other "write on WhatsApp" buttons of the page open this panel too.
    useEffect(
        () =>
            onWhatsAppFormRequest(() => {
                setOpen(true);
                setOpened(true);
            }),
        [],
    );

    useEffect(() => {
        if (!open) {
            return;
        }

        panel.current?.focus({ preventScroll: true });

        const onKey = (event: KeyboardEvent) => {
            if (event.key === 'Escape') {
                setOpen(false);
                button.current?.focus();
            }
        };

        addEventListener('keydown', onKey);

        return () => removeEventListener('keydown', onKey);
    }, [open]);

    return (
        <div className={cx('needs-js', corner)}>
            <div
                ref={panel}
                id={id}
                role="dialog"
                aria-labelledby={`${id}-title`}
                tabIndex={-1}
                hidden={!open}
                className="whatsapp-panel stage-light bg-stage-2 border-line absolute end-0 bottom-full mb-3 w-[min(22.5rem,calc(100vw-2rem))] rounded-lg border p-5 shadow-[0_24px_64px_-24px_rgb(0_0_0/0.6)] outline-none"
            >
                <div className="flex items-start justify-between gap-4">
                    <p
                        id={`${id}-title`}
                        className="font-display text-xl leading-tight font-[440]"
                    >
                        {t.common.whatsapp}
                    </p>
                    <button
                        type="button"
                        onClick={() => {
                            setOpen(false);
                            button.current?.focus();
                        }}
                        aria-label={t.home.whatsapp.panelClose}
                        className="text-soft hover:text-fg -m-2 grid size-9 shrink-0 place-items-center rounded-full transition-colors"
                    >
                        <Close className="size-5" />
                    </button>
                </div>
                <p className="text-soft mt-1.5 text-sm">
                    {t.home.whatsapp.lead}
                </p>
                {opened ? (
                    crm ? (
                        <CrmForm
                            config={crm}
                            kind="whatsapp"
                            load="now"
                            className="mt-4"
                        />
                    ) : (
                        <WhatsAppForm config={form} className="mt-4" />
                    )
                ) : null}
            </div>

            <button
                ref={button}
                type="button"
                onClick={toggle}
                aria-expanded={open}
                aria-controls={id}
                className="group floating-whatsapp relative block"
            >
                <span className={bubble}>
                    {/* A size up since 2026-11-17: the clinic found the mark too small (K46). */}
                    <WhatsApp className="size-9 md:size-10" />
                </span>
                {open ? null : (
                    <span aria-hidden="true" className={label}>
                        {t.common.whatsapp}
                    </span>
                )}
                <span className="sr-only">{t.common.whatsapp}</span>
            </button>
        </div>
    );
}
