'use strict';
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
import { Controller } from '@hotwired/stimulus';
// @ts-ignore
import { getComponent } from '@symfony/ux-live-component';
const STORAGE_KEY = 'ferienpass.participantIds';
/**
 * Bridges localStorage <-> the live component's `participantIds` writable
 * LiveProp so anonymous applications can be remembered across visits without
 * starting a server-side session — keeping the offer-detail response
 * cacheable by Varnish.
 *
 * Attached to the root element of any LiveComponent that exposes the
 * `participantIds` prop (ApplicationForm and the embedded sign-in
 * Registration component).
 *
 * - On connect: reads UUIDs from localStorage and pushes them to the server.
 * - On every successful re-render: writes the current prop value back to
 *   localStorage. After a successful sign-up the participants are adopted
 *   into the new account; the next render is on a different page (full
 *   redirect), so stale entries get re-validated server-side on next read
 *   (mismatched/already-claimed UUIDs are filtered out by `user IS NULL`).
 */
export default class extends Controller {
    constructor() {
        super(...arguments);
        this.comp = null;
    }
    initialize() {
        return __awaiter(this, void 0, void 0, function* () {
            try {
                this.comp = yield getComponent(this.element);
            }
            catch (_a) {
                return;
            }
            const stored = this.read();
            if (stored.length > 0) {
                try {
                    // Push to server; the LiveComponent will re-render.
                    yield this.comp.set('participantIds', stored, true);
                }
                catch (_b) {
                    // Best-effort — if the API differs we just lose the sync, the
                    // user can still apply (just won't see prior anonymous entries).
                }
            }
            this.element.addEventListener('live:render', () => this.persist());
        });
    }
    read() {
        try {
            const raw = localStorage.getItem(STORAGE_KEY);
            const parsed = raw ? JSON.parse(raw) : [];
            if (!Array.isArray(parsed)) {
                return [];
            }
            // Defensive: only keep non-empty strings of plausible UUID length.
            return parsed.filter((x) => typeof x === 'string' && x.length >= 32 && x.length <= 64);
        }
        catch (_a) {
            return [];
        }
    }
    persist() {
        var _a, _b, _c, _d;
        if (!this.comp) {
            return;
        }
        try {
            const data = (_c = (_b = (_a = this.comp).getData) === null || _b === void 0 ? void 0 : _b.call(_a, 'participantIds')) !== null && _c !== void 0 ? _c : (_d = this.comp.props) === null || _d === void 0 ? void 0 : _d.participantIds;
            if (Array.isArray(data)) {
                localStorage.setItem(STORAGE_KEY, JSON.stringify(data.filter((x) => typeof x === 'string')));
            }
        }
        catch (_e) {
            // localStorage may be unavailable (private mode quota etc.) — ignore.
        }
    }
}
