import { getComponent } from '@symfony/ux-live-component';
import { Controller } from '@hotwired/stimulus';
import {
    type Action,
    type Answers,
    announceChoice,
    answersFor,
    type Category,
    type Choice,
    isGlobalPrivacyControl,
    needsRender,
    pushChoiceEvent,
    readChoice,
    recordsFor,
    type RecordArgs,
    serializeChoice,
    type SignalMap,
    signalRecord,
    SWITCHABLE,
    type Vendor,
    withdraw,
} from './cookie_consent.ts';

type Configuration = {
    cookieName: string;
    textVersion: string;
    days: number;
    signalMap: SignalMap;
    globalPrivacyControl: boolean;
    vendors: Vendor[];
};

const FOCUSABLE = 'a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';
const SETTINGS_OPENER = '[data-gophery-cookie-settings]';
/** The longest the page waits for the server to take a choice before it renders again; the choice already applies in the browser. */
const RECORD_WAIT_MS = 1500;

/**
 * The cookie dialog. The first question asks for a choice and cannot be dismissed: Escape is refused, and while there is no
 * stored choice a close the engine forces anyway opens the question again. The settings show one switch per category with the
 * necessary one on and disabled, restored from the stored choice. A choice is applied in the browser first (the cookie,
 * Consent Mode `update`, the `cookie_consent_update` event), then carried to the server's log by the Live recorder; a failure
 * is tried once more and then reported, the choice stands. The vendors' tags are in the head the server renders for the
 * choice, so a grant or a withdrawal that touches a vendor renders the page again. The rules are in cookie_consent.ts.
 */
export default class CookieConsentController extends Controller<HTMLElement> {
    static targets = ['question', 'settings', 'recorder'];
    static values = { configuration: Object };

    declare readonly questionTarget: HTMLDialogElement;
    declare readonly settingsTarget: HTMLDialogElement;
    declare readonly recorderTarget: HTMLElement;
    declare configurationValue: Configuration;

    /** Set once this document took an answer, so a browser that refuses the cookie is not asked again and again. */
    private answered = false;

    private readonly openSettingsFromLink = (event: Event): void => {
        if (event.target instanceof Element && null !== event.target.closest(SETTINGS_OPENER)) {
            event.preventDefault();
            this.openSettings();
        }
    };

    connect(): void {
        document.addEventListener('click', this.openSettingsFromLink);
        const stored = this.stored();
        this.restore(stored);
        if (null !== stored) {
            return;
        }
        if (isGlobalPrivacyControl(window, this.configurationValue.globalPrivacyControl)) {
            this.recordTheSignalOnce();
        }
        this.showQuestion();
    }

    disconnect(): void {
        document.removeEventListener('click', this.openSettingsFromLink);
        for (const dialog of [this.questionTarget, this.settingsTarget]) {
            if (dialog.open) {
                dialog.close();
            }
        }
    }

    acceptAll(): void {
        this.commit('acceptAll');
    }

    rejectAll(): void {
        this.commit('rejectAll');
    }

    save(): void {
        this.commit('save');
    }

    openSettings(): void {
        if (this.questionTarget.open) {
            this.questionTarget.close();
        }
        this.restore(this.stored());
        if (!this.settingsTarget.open) {
            this.settingsTarget.showModal();
        }
    }

    /** Escape on the question: the visitor has to choose. */
    refuseEscape(event: Event): void {
        event.preventDefault();
    }

    /** Escape on the settings: back to the question while there is no choice, closed otherwise. */
    closeSettings(event?: Event): void {
        event?.preventDefault();
        if (this.settingsTarget.open) {
            this.settingsTarget.close();
        }
        if (null === this.stored()) {
            this.showQuestion();
        }
    }

    /**
     * The invariant that outlives every engine's close semantics: while no choice is stored, one of the two dialogs is open.
     * `close` is queued as a task, so by the time this runs `openSettings()` has opened the settings, and `commit()` has stored
     * the choice, and neither re-opens anything.
     */
    guard(): void {
        if (this.answered || null !== this.stored() || this.questionTarget.open || this.settingsTarget.open) {
            return;
        }
        this.questionTarget.showModal();
    }

    /** The modal keeps focus natively, but WebKit lets it leak past the last control: Tab wraps first to last. */
    trap(event: KeyboardEvent): void {
        if ('Tab' !== event.key || !(event.currentTarget instanceof HTMLElement)) {
            return;
        }
        const focusable = [...event.currentTarget.querySelectorAll<HTMLElement>(FOCUSABLE)].filter((element) => element.offsetWidth > 0 || element.offsetHeight > 0 || element === document.activeElement);
        if (0 === focusable.length) {
            return;
        }
        const [first, last] = [focusable[0], focusable[focusable.length - 1]];
        if (event.shiftKey && (document.activeElement === first || !focusable.includes(document.activeElement as HTMLElement))) {
            event.preventDefault();
            last.focus();
        } else if (!event.shiftKey && document.activeElement === last) {
            event.preventDefault();
            first.focus();
        }
    }

    private commit(action: Action): void {
        this.answered = true;
        const configuration = this.configurationValue;
        const previous = this.stored();
        const gpc = isGlobalPrivacyControl(window, configuration.globalPrivacyControl);
        const next = answersFor(action, this.switches(), gpc);
        const from = this.settingsTarget.open ? 'settings' : 'banner';
        const before: Answers | null = null === previous ? null : { preferences: previous.preferences, statistics: previous.statistics, marketing: previous.marketing };

        document.cookie = serializeChoice({ name: configuration.cookieName, version: configuration.textVersion, answers: next, now: new Date(), days: configuration.days, secure: 'https:' === window.location.protocol });
        this.restore(this.stored());
        for (const dialog of [this.questionTarget, this.settingsTarget]) {
            if (dialog.open) {
                dialog.close();
            }
        }

        const taken = SWITCHABLE.filter((category: Category) => null !== before && before[category] && !next[category]);
        if (taken.length > 0) {
            // The withdrawal sends the `denied` update itself, first; the event follows it.
            withdraw(window, document, taken, next, configuration.vendors, configuration.signalMap);
            pushChoiceEvent(window);
        } else {
            announceChoice(window, next, configuration.signalMap);
        }

        const records = Promise.all(recordsFor(before, next, configuration.textVersion, gpc, from).map((record) => this.record(record)));
        if (needsRender(before, next, configuration.vendors)) {
            void this.renderAgain(records, taken.length > 0);
        }
    }

    /** Waits for the server to take the answers, for no longer than a moment, then renders the page again: the head carries the tags the choice allows. */
    private async renderAgain(records: Promise<unknown>, reload: boolean): Promise<void> {
        await Promise.race([records, new Promise((resolve) => window.setTimeout(resolve, RECORD_WAIT_MS))]);
        const turbo = (window as unknown as { Turbo?: { visit(url: string, options: { action: string }): void } }).Turbo;
        if (!reload && undefined !== turbo) {
            turbo.visit(window.location.href, { action: 'replace' });

            return;
        }
        window.location.reload();
    }

    /** One try and one more; the choice stands in the browser whatever the server says. */
    private async record(record: RecordArgs): Promise<void> {
        for (let attempt = 1; attempt <= 2; attempt++) {
            try {
                const component = await getComponent(this.recorderTarget);
                const result = (await component.action('record', { ...record })) as { response?: { ok?: boolean } } | undefined;
                if (false === result?.response?.ok) {
                    throw new Error(`The recorder answered ${String((result.response as { status?: number }).status ?? 'with an error')}.`);
                }

                return;
            } catch (failure) {
                if (2 === attempt) {
                    console.error('The cookie choice could not be recorded on the server; it still applies in this browser.', failure);
                    this.dispatch('record-failed', { detail: { source: record.source }, prefix: 'cookie-consent' });
                }
            }
        }
    }

    private recordTheSignalOnce(): void {
        const flag = `gophery_cookie_consent_gpc_${this.configurationValue.textVersion}`;
        try {
            if (null !== window.sessionStorage.getItem(flag)) {
                return;
            }
            window.sessionStorage.setItem(flag, '1');
        } catch {
            // Storage is refused: the signal is recorded once per page then; the ledger adds nothing for a repeat.
        }
        void this.record(signalRecord(this.configurationValue.textVersion));
    }

    private showQuestion(): void {
        if (!this.questionTarget.open && !this.settingsTarget.open) {
            this.questionTarget.showModal();
        }
    }

    private stored(): Choice | null {
        return readChoice(document.cookie, this.configurationValue.cookieName, this.configurationValue.textVersion);
    }

    private switches(): Answers {
        const answers: Answers = { preferences: false, statistics: false, marketing: false };
        for (const category of SWITCHABLE) {
            answers[category] = this.switchOf(category)?.checked ?? false;
        }

        return answers;
    }

    /** Puts the stored choice back into the switches; no choice is every optional switch off. */
    private restore(choice: Choice | null): void {
        for (const category of SWITCHABLE) {
            const control = this.switchOf(category);
            if (null !== control) {
                control.checked = null !== choice && choice[category];
            }
        }
    }

    private switchOf(category: Category): HTMLInputElement | null {
        return this.settingsTarget.querySelector<HTMLInputElement>(`input[type="checkbox"][name="${category}"]`);
    }
}
