'use strict';

import {Controller} from '@hotwired/stimulus';

/**
 * Offer card controller. Owns the heart button on each card and delegates
 * to the `ferienpass--cms-wishlists` controller on the filter panel.
 *
 * Why this controller exists at all (instead of putting the action directly
 * on the card markup): the wishlists controller needs to know which card
 * triggered the menu, so it can anchor the popover to that card's heart.
 */
export default class extends Controller {
    static values = { offerId: Number };

    declare readonly offerIdValue: number;

    openWishlistMenu(event: Event): void {
        event.preventDefault();
        event.stopPropagation();
        const wishlists = this.findWishlistsController();
        if (!wishlists) return;
        // Anchor the popover at the button that was clicked — a card may carry
        // several hearts (e.g. offer details sidebar + application form).
        const anchor = event.currentTarget instanceof HTMLElement ? event.currentTarget : undefined;
        wishlists.requestCardPopover(this.element as HTMLElement, anchor);
    }

    private findWishlistsController(): { requestCardPopover: (el: HTMLElement, anchor?: HTMLElement) => void } | null {
        const el = document.querySelector<HTMLElement>('[data-controller~="ferienpass--cms-wishlists"]');
        if (!el) return null;
        const app = this.application;
        const ctrl = app.getControllerForElementAndIdentifier(el, 'ferienpass--cms-wishlists');
        return ctrl ? (ctrl as unknown as { requestCardPopover: (el: HTMLElement, anchor?: HTMLElement) => void }) : null;
    }
}
