☰

MHenhancer

Link fixer, BBCode copier, Lusthaus search, and High-Res Image Downloader for modelle-hamburg.de

θα χρειαστεί να εγκαταστήσετε μια επέκταση όπως το Tampermonkey, το Greasemonkey ή το Violentmonkey για να εγκαταστήσετε αυτόν τον κώδικα.

You will need to install an extension such as Tampermonkey or Violentmonkey to install this script.

θα χρειαστεί να εγκαταστήσετε μια επέκταση όπως το Tampermonkey ή το Violentmonkey για να εγκαταστήσετε αυτόν τον κώδικα.

θα χρειαστεί να εγκαταστήσετε μια επέκταση όπως το Tampermonkey ή το Userscripts για να εγκαταστήσετε αυτόν τον κώδικα.

You will need to install an extension such as Tampermonkey to install this script.

Θα χρειαστεί να εγκαταστήσετε μια επέκταση διαχείρισης κώδικα χρήστη για να εγκαταστήσετε αυτόν τον κώδικα.

(Έχω ήδη έναν διαχειριστή κώδικα χρήστη, επιτρέψτε μου να τον εγκαταστήσω!)

You will need to install an extension such as Stylus to install this style.

You will need to install an extension such as Stylus to install this style.

You will need to install an extension such as Stylus to install this style.

You will need to install a user style manager extension to install this style.

You will need to install a user style manager extension to install this style.

You will need to install a user style manager extension to install this style.

(Έχω ήδη έναν διαχειριστή στυλ χρήστη, επιτρέψτε μου να τον εγκαταστήσω!)

// ==UserScript==
// @name         MHenhancer
// @namespace    https://greasyfork.org/users/290665
// @version      2.0
// @description  Link fixer, BBCode copier, Lusthaus search, and High-Res Image Downloader for modelle-hamburg.de
// @match        https://*.modelle-hamburg.de/modelle/*
// @match        https://modelle-hamburg.de/modelle/*
// @include      *://*modelle-hamburg.de/modelle/*
// @include      /https://(www\.)?modelle-hamburg\.de/.*/[^/]*_\d+(\.html)?/
// @icon         https://www.google.com/s2/favicons?sz=64&domain=modelle-hamburg.de
// @grant        GM_download
// @grant        GM_addStyle
// @grant        GM_setClipboard
// @run-at       document-end
// ==/UserScript==

(function () {
    'use strict';

    // Inject styles
    const styles = `
        .mhe-container {
            display: inline-flex;
            flex-direction: column;
            align-items: flex-start;
            align-self: flex-end;
            gap: 4px;
            margin: 0 16px 2px 20px;
            flex-shrink: 0;
            vertical-align: bottom;
        }
        .mhe-badge {
            display: inline-flex;
            align-items: center;
            gap: 5px;
            font-size: 11px;
            font-weight: 700;
            line-height: 1;
            letter-spacing: 0.03em;
            color: #ce167b;
            background-color: #fcdfef;
            border: 1px solid #f8c0df;
            padding: 3px 9px;
            border-radius: 9999px;
            user-select: none;
        }
        .mhe-badge svg {
            width: 12px;
            height: 12px;
            fill: currentColor;
            flex-shrink: 0;
        }
        .mhe-toolbar {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            flex-wrap: wrap;
        }
        /* Site-matching pink buttons */
        .mhe-btn {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            padding: 6px 13px;
            font-size: 13px;
            font-weight: 500;
            line-height: 1.3;
            color: #ffffff;
            background-color: #e82190;
            border: 1px solid #ce167b;
            border-radius: 6px;
            cursor: pointer;
            text-decoration: none;
            user-select: none;
            box-shadow: 0 1px 2px rgba(0, 0, 0, 0.08);
            transition: background-color 0.15s ease, border-color 0.15s ease, transform 0.08s ease;
        }
        .mhe-btn:hover {
            background-color: #ce167b;
            border-color: #ab1266;
            color: #ffffff;
        }
        .mhe-btn:active {
            background-color: #ab1266;
            transform: translateY(1px);
        }
        .mhe-btn svg {
            width: 14px;
            height: 14px;
            flex-shrink: 0;
            fill: currentColor;
        }
        .mhe-toast {
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 999999;
            background-color: #ce167b;
            color: #ffffff;
            font-weight: 600;
            font-size: 14px;
            padding: 10px 18px;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.25);
            pointer-events: none;
            opacity: 0;
            transform: translateY(-10px);
            transition: opacity 0.25s ease, transform 0.25s ease;
        }
        .mhe-toast.mhe-show {
            opacity: 1;
            transform: translateY(0);
        }
        /* Modal for Download Dialog */
        .mhe-modal-backdrop {
            position: fixed;
            inset: 0;
            background: rgba(0, 0, 0, 0.6);
            z-index: 999998;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 16px;
        }
        .mhe-modal {
            background: #ffffff;
            border-radius: 12px;
            width: 100%;
            max-width: 640px;
            max-height: 80vh;
            display: flex;
            flex-direction: column;
            box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.3);
            overflow: hidden;
            font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
        }
        .mhe-modal-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 14px 18px;
            border-bottom: 1px solid #e5e7eb;
            background: #fdf2f8;
        }
        .mhe-modal-title {
            font-size: 15px;
            font-weight: 600;
            color: #890e52;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
        .mhe-modal-close {
            background: none;
            border: none;
            font-size: 20px;
            line-height: 1;
            color: #6b7280;
            cursor: pointer;
            padding: 4px;
        }
        .mhe-modal-close:hover {
            color: #111827;
        }
        .mhe-modal-body {
            padding: 16px;
            overflow-y: auto;
            flex: 1;
            font-size: 13px;
            line-height: 1.5;
            color: #374151;
        }
        .mhe-dl-item {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 6px 8px;
            border-bottom: 1px solid #f3f4f6;
            font-family: monospace;
            font-size: 12px;
            word-break: break-all;
        }
        .mhe-dl-item:last-child {
            border-bottom: none;
        }
        .mhe-status-pending { color: #6b7280; }
        .mhe-status-success { color: #16a34a; font-weight: bold; }
        .mhe-status-error { color: #dc2626; font-weight: bold; }
    `;

    if (typeof GM_addStyle === 'function') {
        GM_addStyle(styles);
    } else {
        const styleEl = document.createElement('style');
        styleEl.textContent = styles;
        document.head.appendChild(styleEl);
    }

    // SVG Icons
    const icons = {
        sparkles: '<svg viewBox="0 0 20 20"><path fill-rule="evenodd" d="M11.3 1.046A1 1 0 0112 2v5h4a1 1 0 01.82 1.573l-7 10A1 1 0 018 18v-5H4a1 1 0 01-.82-1.573l7-10a1 1 0 011.12-.38z" clip-rule="evenodd"></path></svg>',
        copy: '<svg viewBox="0 0 20 20"><path d="M8 3a1 1 0 011-1h2a1 1 0 110 2H9a1 1 0 01-1-1z"></path><path d="M6 3a2 2 0 00-2 2v11a2 2 0 002 2h8a2 2 0 002-2V5a2 2 0 00-2-2 3 3 0 01-3 2H9a3 3 0 01-3-2z"></path></svg>',
        link: '<svg viewBox="0 0 20 20"><path fill-rule="evenodd" d="M12.586 4.586a2 2 0 112.828 2.828l-3 3a2 2 0 01-2.828 0 1 1 0 00-1.414 1.414 4 4 0 005.656 0l3-3a4 4 0 00-5.656-5.656l-1.5 1.5a1 1 0 101.414 1.414l1.5-1.5zm-5 5a2 2 0 012.828 0 1 1 0 101.414-1.414 4 4 0 00-5.656 0l-3 3a4 4 0 105.656 5.656l1.5-1.5a1 1 0 10-1.414-1.414l-1.5 1.5a2 2 0 11-2.828-2.828l3-3z" clip-rule="evenodd"></path></svg>',
        search: '<svg viewBox="0 0 20 20"><path fill-rule="evenodd" d="M8 4a4 4 0 100 8 4 4 0 000-8zM2 8a6 6 0 1110.89 3.476l4.817 4.817a1 1 0 01-1.414 1.414l-4.816-4.816A6 6 0 012 8z" clip-rule="evenodd"></path></svg>',
        download: '<svg viewBox="0 0 20 20"><path fill-rule="evenodd" d="M3 17a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zm3.293-7.707a1 1 0 011.414 0L9 10.586V3a1 1 0 112 0v7.586l1.293-1.293a1 1 0 111.414 1.414l-3 3a1 1 0 01-1.414 0l-3-3a1 1 0 010-1.414z" clip-rule="evenodd"></path></svg>'
    };

    // Toast utility
    function showToast(text) {
        let toast = document.querySelector('.mhe-toast');
        if (!toast) {
            toast = document.createElement('div');
            toast.className = 'mhe-toast';
            document.body.appendChild(toast);
        }
        toast.textContent = text;
        toast.classList.add('mhe-show');
        clearTimeout(toast._timeout);
        toast._timeout = setTimeout(() => {
            toast.classList.remove('mhe-show');
        }, 2200);
    }

    // Clipboard copy helper
    function copyToClipboard(str, successMsg) {
        if (typeof GM_setClipboard === 'function') {
            GM_setClipboard(str);
            showToast(successMsg || 'Kopiert!');
        } else if (navigator.clipboard && navigator.clipboard.writeText) {
            navigator.clipboard.writeText(str).then(() => {
                showToast(successMsg || 'Kopiert!');
            }).catch(() => {
                fallbackCopy(str, successMsg);
            });
        } else {
            fallbackCopy(str, successMsg);
        }
    }

    function fallbackCopy(text, successMsg) {
        const textArea = document.createElement('textarea');
        textArea.value = text;
        textArea.style.position = 'fixed';
        textArea.style.opacity = '0';
        document.body.appendChild(textArea);
        textArea.select();
        try {
            document.execCommand('copy');
            showToast(successMsg || 'Kopiert!');
        } catch (err) {
            showToast('Kopieren fehlgeschlagen!');
        }
        document.body.removeChild(textArea);
    }

    // Nuxt Data Resolver
    function getNuxtData() {
        const el = document.getElementById('__NUXT_DATA__');
        if (!el) return null;
        try {
            return JSON.parse(el.textContent);
        } catch (e) {
            return null;
        }
    }

    function resolveNuxt(data, val, depth = 0) {
        if (!data || depth > 10) return val;
        if (typeof val === 'number' && val >= 0 && val < data.length) {
            return resolveNuxt(data, data[val], depth + 1);
        }
        return val;
    }

    function getNuxtModel(data) {
        if (!data || !Array.isArray(data)) return null;
        for (const item of data) {
            if (item && typeof item === 'object' && item.type !== undefined) {
                const resolvedType = resolveNuxt(data, item.type);
                if (resolvedType === 'model') {
                    return item;
                }
            }
        }
        return null;
    }

    // Extractors
    function getAdID() {
        const nuxtData = getNuxtData();
        const model = getNuxtModel(nuxtData);
        if (model && model.id !== undefined) {
            const id = resolveNuxt(nuxtData, model.id);
            if (id) return String(id);
        }
        const url = window.location.pathname;
        const match = url.match(/_(\d+)(?:\.html)?(?:$|[?#])/);
        return match ? match[1] : '';
    }

    function getAdName() {
        const nuxtData = getNuxtData();
        const model = getNuxtModel(nuxtData);
        if (model && model.name !== undefined) {
            const name = resolveNuxt(nuxtData, model.name);
            if (name) return String(name).trim();
        }
        const h1 = document.querySelector('h1');
        if (h1) return h1.textContent.trim();
        const ogTitle = document.querySelector('meta[property="og:title"]');
        if (ogTitle && ogTitle.content) {
            return ogTitle.content.split('-')[0].trim();
        }
        return '';
    }

    function getSlogan() {
        const nuxtData = getNuxtData();
        const model = getNuxtModel(nuxtData);
        if (model && model.slogan !== undefined) {
            const sloganObj = resolveNuxt(nuxtData, model.slogan);
            if (sloganObj && typeof sloganObj === 'object') {
                const de = resolveNuxt(nuxtData, sloganObj.de);
                if (de && typeof de === 'object') {
                    const txt = resolveNuxt(nuxtData, de.fsk16) || resolveNuxt(nuxtData, de.fsk18);
                    if (txt) return String(txt).trim();
                } else if (typeof de === 'string') {
                    return de.trim();
                }
            }
        }
        // DOM selector: div under or next to h1
        const sloganEl = document.querySelector('h1 + * [class*="text-gray-600"], h1 ~ div[class*="text-gray-600"], .w-full.text-\\[18px\\]');
        if (sloganEl) return sloganEl.textContent.trim();
        return '';
    }

    function getAboutText() {
        const nuxtData = getNuxtData();
        const model = getNuxtModel(nuxtData);
        if (model && model.intro !== undefined) {
            const introObj = resolveNuxt(nuxtData, model.intro);
            if (introObj && typeof introObj === 'object') {
                const de = resolveNuxt(nuxtData, introObj.de);
                if (de && typeof de === 'object') {
                    const txt = resolveNuxt(nuxtData, de.fsk16) || resolveNuxt(nuxtData, de.fsk18);
                    if (txt) return cleanHtmlText(String(txt));
                } else if (typeof de === 'string') {
                    return cleanHtmlText(de);
                }
            }
        }
        // Fallback from DOM
        const headings = document.querySelectorAll('h2');
        for (const h2 of headings) {
            if (h2.textContent.includes('Über mich')) {
                const parent = h2.closest('div.flex.flex-col') || h2.parentElement?.parentElement;
                if (parent) {
                    const desc = parent.querySelector('.mhh-text.mhh-text-medium.overflow-hidden');
                    if (desc) return cleanHtmlText(desc.textContent);
                }
            }
        }
        const legacyAbout = document.querySelector('#mainframe .about-text');
        if (legacyAbout) return cleanHtmlText(legacyAbout.textContent);
        return '';
    }

    function getPhone() {
        // 1. Check meta[name="keywords"]
        const metaKw = document.querySelector('meta[name="keywords"]');
        if (metaKw && metaKw.content) {
            const m = metaKw.content.match(/(\+?\d[\d\s\/\(\)\-]{6,}\d)/);
            if (m) return m[1].trim();
        }
        // 2. Check tel: links
        const telLink = document.querySelector('a[href^="tel:"]');
        if (telLink) {
            return telLink.getAttribute('href').replace(/^tel:/, '').trim();
        }
        return '';
    }

    // Formats telephone number into unique, non-repeating national and international variations
    function formatPhoneNumbers(rawPhone) {
        if (!rawPhone) return { bbcode: '', variants: [] };

        const cleaned = rawPhone.trim();
        let digits = cleaned.replace(/[ \/\-\(\)]/g, '').replace(/\+49\(0\)/, '+49').replace(/^0049/, '+49');

        let intl = '';
        let nat = '';

        if (digits.startsWith('+49')) {
            intl = digits;
            nat = '0' + digits.slice(3);
        } else if (digits.startsWith('49') && digits.length > 9) {
            intl = '+' + digits;
            nat = '0' + digits.slice(2);
        } else if (digits.startsWith('+41')) {
            intl = digits;
            nat = '0' + digits.slice(3);
        } else if (digits.startsWith('+')) {
            intl = digits;
            nat = digits;
        } else if (digits.startsWith('0')) {
            nat = digits;
            intl = '+49' + digits.slice(1);
        } else {
            intl = '+49' + digits;
            nat = '0' + digits;
        }

        const variants = [];
        // 1. International
        if (intl) variants.push(intl);
        // 2. National non-separated
        if (nat) variants.push(nat);
        // 3. National separated after 5th digit (e.g. 01521-2550238)
        if (nat.length > 5) {
            variants.push(nat.slice(0, 5) + '-' + nat.slice(5));
        }
        // 4. National separated after 4th digit (e.g. 0152-12550238)
        if (nat.length > 4) {
            variants.push(nat.slice(0, 4) + '-' + nat.slice(4));
        }

        // Deduplicate while preserving insertion order
        const uniqueVariants = [];
        for (const v of variants) {
            if (v && !uniqueVariants.includes(v)) {
                uniqueVariants.push(v);
            }
        }

        const telLink = intl.startsWith('+') ? intl : nat;
        const firstDisplay = uniqueVariants[0] || '';
        const restDisplay = uniqueVariants.slice(1);

        let bbcode = `[URL="tel:${telLink}"]${firstDisplay}[/URL]`;
        if (restDisplay.length > 0) {
            bbcode += ', ' + restDisplay.join(', ');
        }

        return { bbcode, variants: uniqueVariants };
    }

    function getAddress() {
        const nuxtData = getNuxtData();
        const model = getNuxtModel(nuxtData);
        let street = '';
        let city = '';
        if (model && model.place !== undefined) {
            const place = resolveNuxt(nuxtData, model.place);
            if (place && typeof place === 'object') {
                const st = resolveNuxt(nuxtData, place.street) || '';
                const hno = resolveNuxt(nuxtData, place.house_no) || '';
                street = `${st} ${hno}`.trim();
                const ct = resolveNuxt(nuxtData, place.city) || '';
                const dist = resolveNuxt(nuxtData, place.district) || '';
                city = (ct && dist) ? `${ct}-${dist}` : (dist || ct);
            }
        }
        if (!street && !city) {
            const metaKw = document.querySelector('meta[name="keywords"]');
            if (metaKw && metaKw.content) {
                const parts = metaKw.content.split(',').map(s => s.trim());
                if (parts.length >= 3) {
                    street = parts[1];
                    city = parts[2];
                }
            }
        }
        if (/Sage ich Dir am Telefon/i.test(street)) {
            street = '';
        }
        if (street && city) return `${street}, ${city}`;
        return street || city;
    }

    function getDetailsBB() {
        // Collect from DOM "Alle Details über mich"
        const details = [];
        const headings = document.querySelectorAll('h2');
        let detailsSection = null;
        for (const h2 of headings) {
            if (h2.textContent.includes('Alle Details')) {
                let curr = h2.parentElement;
                while (curr && curr !== document.body && !curr.querySelector('div[class*="mhh-text-large"]')) {
                    curr = curr.parentElement;
                }
                detailsSection = curr;
                break;
            }
        }
        if (detailsSection) {
            const largeTexts = detailsSection.querySelectorAll('div[class*="mhh-text-large"]');
            for (let i = 0; i < largeTexts.length - 1; i += 2) {
                const k = largeTexts[i].textContent.trim();
                const v = largeTexts[i + 1].textContent.trim();
                if (k && v) {
                    details.push(`[B]${k}:[/B] ${v}`);
                }
            }
        }
        // Legacy fallback
        if (details.length === 0) {
            const legacyDetails = document.querySelector('#mainframe table.model-details');
            if (legacyDetails) {
                let html = legacyDetails.innerHTML
                    .replace(/\n/g, '')
                    .replace(/<(\/)?th>/g, '[$1B]')
                    .replace(/<.+?>/g, ' ')
                    .replace(/ *\[B\]/g, ', [B]')
                    .replace(/\[\/B\]/g, ':[/B]')
                    .replace(/ +/g, ' ')
                    .replace(/^[ ,]+/g, '');
                return html;
            }
        }
        return details.join(', ');
    }

    function getServicesBB() {
        // Collect from DOM "Meine Vorlieben"
        const headings = document.querySelectorAll('h2');
        let vorliebenSection = null;
        for (const h2 of headings) {
            if (h2.textContent.includes('Meine Vorlieben')) {
                vorliebenSection = h2.closest('.flex.flex-col') || h2.parentElement?.parentElement?.parentElement;
                break;
            }
        }
        if (vorliebenSection) {
            const categories = [];
            // Category headers: text-mhhprimary-600
            const catHeaders = vorliebenSection.querySelectorAll('div[class*="text-mhhprimary-600"]');
            for (const catH of catHeaders) {
                const catName = catH.textContent.trim();
                const catContainer = catH.nextElementSibling;
                if (catContainer) {
                    const items = [];
                    const itemEls = catContainer.querySelectorAll('div[class*="mhh-text"]');
                    for (const el of itemEls) {
                        const txt = el.textContent.trim();
                        if (txt && !items.includes(txt)) {
                            items.push(txt);
                        }
                    }
                    if (items.length > 0) {
                        categories.push(`[B]${catName}:[/B] ` + items.join(', '));
                    }
                }
            }
            if (categories.length > 0) {
                return '\n' + categories.join('\n');
            }
        }
        // Legacy fallback
        const legacyService = document.querySelector('#mainframe div.service-panel ul');
        if (legacyService) {
            let s = legacyService.innerHTML
                .replace(/\n/g, '')
                .replace(/<label>.*<\/label>/, '')
                .replace(/<\/li>\s*<li>/g, ', ')
                .replace(/<.+?>/g, '')
                .replace(/\[B\]/g, '\n[B]')
                .replace(/\[\/B\]/g, ':[/B]')
                .replace(/^[ ,]+/g, '');
            return s;
        }
        return '';
    }

    function getGalleryImages() {
        const imgUrls = [];
        const nuxtData = getNuxtData();
        const model = getNuxtModel(nuxtData);

        if (model && model.images !== undefined) {
            const imagesList = resolveNuxt(nuxtData, model.images);
            if (Array.isArray(imagesList)) {
                for (const imgIdx of imagesList) {
                    const imgItem = resolveNuxt(nuxtData, imgIdx);
                    if (imgItem && typeof imgItem === 'object') {
                        const full = resolveNuxt(nuxtData, imgItem.full_image);
                        const thumb = resolveNuxt(nuxtData, imgItem.thumbnail);
                        const url = (full && full.url) ? resolveNuxt(nuxtData, full.url) : (thumb ? resolveNuxt(nuxtData, thumb.url) : null);
                        if (url && !imgUrls.includes(url)) {
                            imgUrls.push(url);
                        }
                    }
                }
            }
        }

        // DOM fallback if Nuxt list is empty
        if (imgUrls.length === 0) {
            const domImgs = document.querySelectorAll('img[srcset*="images/modelle/"], img[src*="images/modelle/"]');
            for (const img of domImgs) {
                let src = img.getAttribute('src');
                const srcset = img.getAttribute('srcset');
                if (srcset) {
                    const parts = srcset.split(',');
                    const highest = parts[parts.length - 1].trim().split(' ')[0];
                    if (highest) src = highest;
                }
                if (src) {
                    // Try to point to _full if it's a resized pattern
                    const fullSrc = src.replace(/_\d+_\d+_\d+(\.[a-z]+)$/i, '_full$1');
                    if (!imgUrls.includes(fullSrc)) {
                        imgUrls.push(fullSrc);
                    }
                }
            }
        }

        return imgUrls;
    }

    function cleanHtmlText(str) {
        if (!str) return '';
        const temp = document.createElement('div');
        temp.innerHTML = str;
        return temp.textContent || temp.innerText || '';
    }

    function properLink() {
        const id = getAdID();
        const baseURL = window.location.protocol + '//' + window.location.host;
        return `${baseURL}/modelle/x/x/_${id}.html`;
    }

    // Action Handlers
    function copyText() {
        const name = getAdName();
        const phoneData = formatPhoneNumbers(getPhone());
        const subheader = getSlogan();
        const text = getAboutText();
        const URL = properLink();
        const address = getAddress();
        const service = getServicesBB();
        const data = getDetailsBB();
        const adid = getAdID();

        let dataBB = `Infoservice\n[QUOTE][SIZE="1"]MHID = ${adid} | MHID${adid}\n\n[URL=${URL}][B]${name}[/B]\n${subheader}[/URL]\n\n${text}\n\n`
            + `${data}\n`
            + (phoneData.bbcode ? `[B]Telefon:[/B] ${phoneData.bbcode}\n` : '')
            + (address ? `[B]Adresse:[/B] [URL="https://www.google.de/maps/place/${encodeURIComponent(address)}"]${address}[/URL]\n` : '')
            + `[B]Service:[/B] ${service}\n`
            + `[/SIZE][/QUOTE]`;

        dataBB = dataBB.replace(/ {2,}/g, ' ').replace(/\n{3,}/g, '\n\n');
        copyToClipboard(dataBB, 'Infotext kopiert!');
    }

    function shareLink() {
        const link = properLink();
        copyToClipboard(link, 'Link kopiert!');
    }

    function LHsearch() {
        const name = getAdName();
        const phoneData = formatPhoneNumbers(getPhone());
        let searchterm = '("' + name + '"';
        if (phoneData.variants.length > 0) {
            searchterm += ' OR ' + phoneData.variants.join(' OR ');
        }
        searchterm += ')';
        const url = 'https://www.google.de/search?as_sitesearch=lusthaus.cc&q=' + encodeURIComponent(searchterm);
        window.open(url, '_blank');
    }

    function downloadAll() {
        const name = getAdName();
        const id = getAdID();
        const phone = getPhone();
        let folder = `${name} (MH ${id})`;
        if (phone) folder += ` - ${phone}`;
        // Clean folder name of illegal filesystem characters
        folder = folder.replace(/[\/\\:*?"<>|]/g, '').trim();

        const imgList = getGalleryImages();
        if (imgList.length === 0) {
            alert('Keine Bilder gefunden!');
            return;
        }

        // Create Modal
        const backdrop = document.createElement('div');
        backdrop.className = 'mhe-modal-backdrop';

        const modal = document.createElement('div');
        modal.className = 'mhe-modal';

        modal.innerHTML = `
            <div class="mhe-modal-header">
                <div class="mhe-modal-title">Download: ${folder} (${imgList.length} Bilder)</div>
                <button class="mhe-modal-close" title="Schließen">&times;</button>
            </div>
            <div class="mhe-modal-body"></div>
        `;

        backdrop.appendChild(modal);
        document.body.appendChild(backdrop);

        const closeBtn = modal.querySelector('.mhe-modal-close');
        const closeModal = () => {
            if (backdrop.parentElement) {
                document.body.removeChild(backdrop);
            }
        };
        closeBtn.addEventListener('click', closeModal);
        backdrop.addEventListener('click', (e) => {
            if (e.target === backdrop) closeModal();
        });

        const body = modal.querySelector('.mhe-modal-body');

        imgList.forEach((url, idx) => {
            // Extract filename from URL
            const urlPath = url.split('?')[0];
            const originalFilename = urlPath.substring(urlPath.lastIndexOf('/') + 1);
            const extMatch = originalFilename.match(/\.[a-z0-9]+$/i);
            const ext = extMatch ? extMatch[0] : '.jpg';
            const baseName = originalFilename.replace(/\.[a-z0-9]+$/i, '');
            const filename = `${folder}/${baseName}${ext}`;

            const item = document.createElement('div');
            item.className = 'mhe-dl-item';
            item.innerHTML = `<span>[${idx + 1}/${imgList.length}] ${originalFilename}</span><span class="mhe-status-pending">Warte...</span>`;
            body.appendChild(item);

            const statusEl = item.querySelector('span:last-child');

            if (typeof GM_download === 'function') {
                GM_download({
                    url: url,
                    name: filename,
                    saveAs: false,
                    onerror: function (err) {
                        const errMsg = (err && err.error) ? `${err.error}: ${err.details || ''}` : 'Fehler';
                        statusEl.className = 'mhe-status-error';
                        statusEl.textContent = `✗ ${errMsg}`;
                    },
                    onload: function () {
                        statusEl.className = 'mhe-status-success';
                        statusEl.textContent = '✓ Fertig';
                    }
                });
            } else {
                // Browser fallback
                fetch(url)
                    .then(res => res.blob())
                    .then(blob => {
                        const blobUrl = URL.createObjectURL(blob);
                        const a = document.createElement('a');
                        a.href = blobUrl;
                        a.download = originalFilename;
                        document.body.appendChild(a);
                        a.click();
                        document.body.removeChild(a);
                        URL.revokeObjectURL(blobUrl);
                        statusEl.className = 'mhe-status-success';
                        statusEl.textContent = '✓ Gespeichert';
                    })
                    .catch(e => {
                        statusEl.className = 'mhe-status-error';
                        statusEl.textContent = '✗ Fehler: ' + e.message;
                    });
            }
        });
    }

    // UI Injection
    function createToolbar() {
        const container = document.createElement('div');
        container.id = 'mhenhancer-container';
        container.className = 'mhe-container';

        // Title Badge above buttons
        const badge = document.createElement('div');
        badge.className = 'mhe-badge';
        const scriptName = (typeof GM_info !== 'undefined' && GM_info?.script?.name) || 'MHenhancer';
        const scriptVer = (typeof GM_info !== 'undefined' && GM_info?.script?.version) || '2.0';
        badge.innerHTML = `${icons.sparkles}<span>${scriptName} v${scriptVer}</span>`;
        container.appendChild(badge);

        const toolbar = document.createElement('div');
        toolbar.id = 'mhenhancer-toolbar';
        toolbar.className = 'mhe-toolbar';

        // 1. Copy BBCode Button
        const btnCopy = document.createElement('button');
        btnCopy.type = 'button';
        btnCopy.className = 'mhe-btn';
        btnCopy.title = 'Anzeigentext als Forum-BBCode kopieren';
        btnCopy.innerHTML = `${icons.copy}<span>Text kopieren</span>`;
        btnCopy.addEventListener('click', copyText);
        toolbar.appendChild(btnCopy);

        // 2. Share Link Button
        const btnShare = document.createElement('button');
        btnShare.type = 'button';
        btnShare.className = 'mhe-btn';
        btnShare.title = 'Kurzen Anzeigenlink kopieren';
        btnShare.innerHTML = `${icons.link}<span>Link kopieren</span>`;
        btnShare.addEventListener('click', shareLink);
        toolbar.appendChild(btnShare);

        // 3. Lusthaus Search Button
        const btnLH = document.createElement('button');
        btnLH.type = 'button';
        btnLH.className = 'mhe-btn';
        btnLH.title = 'Im Lusthaus-Forum suchen';
        btnLH.innerHTML = `${icons.search}<span>LH-Suche</span>`;
        btnLH.addEventListener('click', LHsearch);
        toolbar.appendChild(btnLH);

        // 4. Download Images Button
        const btnDl = document.createElement('button');
        btnDl.type = 'button';
        btnDl.className = 'mhe-btn';
        btnDl.title = 'Alle Bilder in voller Auflösung herunterladen';
        btnDl.innerHTML = `${icons.download}<span>Bilder laden</span>`;
        btnDl.addEventListener('click', downloadAll);
        toolbar.appendChild(btnDl);

        container.appendChild(toolbar);
        return container;
    }

    function injectUI() {
        const id = getAdID();
        if (!id) return; // Not a model detail page

        // Avoid duplicate container for same model
        const existingContainer = document.getElementById('mhenhancer-container');
        if (existingContainer) {
            if (existingContainer.getAttribute('data-model-id') === id) {
                return; // Already injected for this model
            }
            existingContainer.remove();
        }

        const h1 = document.querySelector('h1');
        if (!h1) return;

        // Ensure H1 and its parent flex container align cleanly to bottom
        const h1Parent = h1.parentElement;
        if (h1Parent) {
            h1Parent.style.display = 'flex';
            h1Parent.style.flexDirection = 'row';
            h1Parent.style.alignItems = 'flex-end';
            h1Parent.style.flexWrap = 'wrap';
            h1.style.width = 'auto';
            h1.style.minWidth = 'auto';
            h1.style.marginBottom = '0px';
        }

        const container = createToolbar();
        container.setAttribute('data-model-id', id);
        const tb = container.querySelector('#mhenhancer-toolbar');
        if (tb) tb.setAttribute('data-model-id', id);

        // Best placement: In the flex container directly next to H1 or immediately after H1
        if (h1Parent && h1Parent.classList.contains('flex')) {
            h1Parent.appendChild(container);
        } else if (h1.nextSibling) {
            h1.parentNode.insertBefore(container, h1.nextSibling);
        } else {
            h1.parentNode.appendChild(container);
        }

        // Clean up legacy tab download button if present
        const oldTabBtn = document.getElementById('mhenhancer-tab-dl');
        if (oldTabBtn) oldTabBtn.remove();
    }

    // SPA Navigation & Mutation Observer
    let lastUrl = window.location.href;
    const observer = new MutationObserver(() => {
        const currentUrl = window.location.href;
        if (currentUrl !== lastUrl) {
            lastUrl = currentUrl;
            setTimeout(injectUI, 300);
        } else if (!document.getElementById('mhenhancer-container')) {
            injectUI();
        }
    });

    observer.observe(document.body, {
        childList: true,
        subtree: true
    });

    // Initial run
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', injectUI);
    } else {
        injectUI();
    }

    // Retries in case Nuxt hydration updates DOM shortly after load
    setTimeout(injectUI, 500);
    setTimeout(injectUI, 1200);
    setTimeout(injectUI, 2500);

})();