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

/**
 * A breadcrumb crumb that points at an edition-scoped list — e.g. the offer's
 * "Sommerferienpass" crumb linking to /admin/angebote/<edition>.
 *
 * The crumb is server-rendered with the offer's OWN single edition. But the
 * admin may have been looking at the list filtered to several editions at once
 * (Sommerferienpass + others). That selection lives only in localStorage (the
 * same `admin-path-prefered--<viewKey>` bucket nav_restore restores), so the
 * server can't know it. When the stored selection is a SUPERSET — this crumb's
 * edition plus at least one more — we surface it here:
 *
 *   • relabel  "Sommerferienpass"  →  "Sommerferienpass +1"
 *   • repoint  the link at the full multi-edition URL
 *
 * so the crumb resolves to the same list the bare "Angebote" crumb does (via
 * nav_restore). Outside that superset case the crumb is left exactly as the
 * server rendered it.
 *
 * DOM contract (set via the breadcrumb item's linkAttributes):
 *   data-controller="ferienpass--admin-breadcrumb-filter"
 *   data-view-key="admin_offers"   // localStorage bucket: admin-path-prefered--<key>
 */
export default class extends Controller {
    connect() {
        try {
            this._apply();
        } catch (_) {
            // localStorage unavailable / malformed — leave the crumb untouched.
        }
    }

    _apply() {
        const viewKey = this.element.dataset.viewKey;
        if (!viewKey) return;

        const href = this.element.getAttribute('href') || '';
        let url;
        try {
            url = new URL(href, window.location.href);
        } catch (_) {
            return;
        }
        if (url.search) return; // only plain path crumbs

        const path = url.pathname.replace(/\/+$/, '');
        const slash = path.lastIndexOf('/');
        if (slash <= 0) return;

        const prefix = path.slice(0, slash);
        const tail = path.slice(slash + 1);
        // The server renders exactly one own-edition alias; bail if it's empty
        // or somehow already a multi-edition tail.
        if (!tail || tail.includes('+')) return;

        const stored = localStorage.getItem(`admin-path-prefered--${viewKey}`);
        if (!stored) return;

        const aliases = stored.split('+').filter(Boolean);
        if (aliases.length <= 1) return;        // a single (or no) edition — nothing to surface
        if (!aliases.includes(tail)) return;    // the stored filter isn't about this offer's edition

        // Repoint at the full selection…
        this.element.setAttribute('href', `${prefix}/${stored}`);

        // …and annotate the label with the count of the OTHER editions.
        const extra = aliases.length - 1;
        const base = (this.element.textContent || '').trim();
        if (base && !/\s\+\d+$/.test(base)) {
            this.element.textContent = `${base} +${extra}`;
        }
    }
}
