jQuery(function($) {
//---------------------------------------------------------------------------------
//---------------------------------------------------------------------------------
    window.TerminKalender = window.TerminKalender || {};

//---------------------------------------------------------------------------------
// WPCS NOTE: Functions in this file (like get_category) are intentionally NOT 
// prefixed with 'termin_kalender_' because they are strictly encapsulated within 
// the jQuery(function($){}) scope. They are invisible to the global 'window' space
// and therefore 100% safe from clashes with other plugins/themes.
//---------------------------------------------------------------------------------
// TYPE DEFINITIONS & HELPERS
//---------------------------------------------------------------------------------
    const ICS_FORMAT = 'YYYYMMDDTHHmmss';
    const ICS_FORMAT_DATE = 'YYYYMMDD';

/**
 * Helper: Get Category Label
 * Priority: 1. Local/Event Category -> 2. Global ICS Name (X-WR-CALNAME) -> 3. 'iCal'
 */
function get_category(event) {
    const ep = event.extendedProps || {};

    // 1. Check Specific Event Category (Local or defined in VEVENT)
    if (ep.category && ep.category.label) return ep.category.label;

    // Check for valid array or string in 'categories'
    // (FullCalendar often returns [] for ICS, so we must check length)
    if (Array.isArray(ep.categories) && ep.categories.length > 0) return ep.categories.join(', ');
    if (typeof ep.categories === 'string' && ep.categories.trim()) return ep.categories;

    // 2. Fallback: Extract Global Calendar Name from Page DOM
    // Finds the first container with raw ICS data
    const wrapper = document.querySelector('[data-ics_data]');
    if (wrapper) {
        // Regex to find X-WR-CALNAME line
        const match = wrapper.getAttribute('data-ics_data').match(/X-WR-CALNAME:(.*?)(?:\r\n|\r|\n|$)/);
        if (match && match[1]) {
            return match[1].trim();
        }
    }

    // 3. Ultimate Fallback
    return 'iCal';
}

    function escapeICalText(str) {
        return str ? String(str)
            .replace(/\\/g, '\\\\')
            .replace(/;/g, '\\;')
            .replace(/,/g, '\\,')
            .replace(/\r?\n/g, '\\n') : '';
    }

    function stripHtml(html) {
        var tmp = document.createElement("DIV");
        tmp.innerHTML = html;
        return tmp.textContent || tmp.innerText || "";
    }

    function buildRRule(event) {
        const ep = event.extendedProps || {};
        if (ep.rrule) return 'RRULE:' + ep.rrule;
        if (!ep.freq) return '';
        let rrule = 'RRULE:FREQ=' + ep.freq;
        let isAllDay = event.allDay || ep.allDay || '';
        if (ep.until) {
            const untilFormat = isAllDay ? ICS_FORMAT_DATE : ICS_FORMAT + 'Z';
            rrule += ';UNTIL=' + moment.utc(ep.until).format(untilFormat);
        }        if (ep.interval && ep.interval > 1) rrule += ';INTERVAL=' + ep.interval;
        if (ep.count) rrule += ';COUNT=' + ep.count;
        if (ep.byweekday) rrule += ';BYDAY=' + ep.byweekday;
        if (ep.bymonthday) rrule += ';BYMONTHDAY=' + ep.bymonthday;
        if (ep.bymonth) rrule += ';BYMONTH=' + ep.bymonth;
        return rrule;
    }
    /**
     * Helper: Generate Human Readable Recurrence Text
     * Returns a string like "🔁 Repeat: Weekly, Every 2 Weeks (Until 31.12.2025)"
     */
function get_recurrence_text(event) {
    const { __ } = wp.i18n;
    const ep = event.extendedProps || {};
    if (!ep.freq && !ep.rrule) return '';

    let text = '🔁 ' ;


        const rruleStr = ep.rrule;
        //console.log(  ep );
        if (ep.until) {
            rruleParts = {};
            if (ep.freq) rruleParts.FREQ = ep.freq;
            if (ep.until) rruleParts.UNTIL = ep.until;
            if (ep.dtstart) rruleParts.DTSTART = ep.dtstart;
            if (ep.interval) rruleParts.INTERVAL = ep.interval;
            if (ep.byweekday) rruleParts.BYDAY = ep.byweekday;
            if (ep.count) rruleParts.COUNT = ep.count;

        } else {
            const rruleParts = {};
            rruleStr.split(';').forEach(part => {
                const [name, value] = part.split('=');
                if (name && value) {
                    rruleParts[name] = value;
                }
            });
        }


        if (rruleParts.FREQ) {
            // Frequency mapping
            const freqMap = {
                'DAILY': __('days', 'termin-kalender'),
                'WEEKLY': __('weeks', 'termin-kalender'),
                'MONTHLY': __('months', 'termin-kalender'),
                'YEARLY': __('years', 'termin-kalender')
            };

            // Day mapping for BYDAY
            const dayMap = {
                'MO': __('Monday', 'termin-kalender'),
                'TU': __('Tuesday', 'termin-kalender'),
                'WE': __('Wednesday', 'termin-kalender'),
                'TH': __('Thursday', 'termin-kalender'),
                'FR': __('Friday', 'termin-kalender'),
                'SA': __('Saturday', 'termin-kalender'),
                'SU': __('Sunday', 'termin-kalender')
            };
            // Add INTERVAL if greater than 1
            if (rruleParts.INTERVAL && rruleParts.INTERVAL > 1) {
                text += __(' every', 'termin-kalender') + ' ' + rruleParts.INTERVAL + ' ' +
                       (freqMap[rruleParts.FREQ] || rruleParts.FREQ.toLowerCase())  ;
            } else {

                text += rruleParts.FREQ ;

            }
            text += '. ';
            // Add BYDAY if present (e.g., "every Monday and Friday")
            if (rruleParts.BYDAY) {
                const days = rruleParts.BYDAY.split(',').map(day => dayMap[day] || day);
                if (days.length === 1) {
                    text += __(' Every', 'termin-kalender') + ' ' + days[0];
                } else if (days.length === 2) {
                    text += __(' Every', 'termin-kalender') + ' ' + days.join(' ' + __('and', 'termin-kalender') + ' ');
                } else {
                    text += __(' Every', 'termin-kalender') + ' ' + days.slice(0, -1).join(', ') +
                           ' ' + __('and', 'termin-kalender') + ' ' + days[days.length - 1];
                }

            }

            // Add UNTIL date
            if (rruleParts.UNTIL) {
                if (ep.until) {
                    const untilDate = moment.utc(rruleParts.UNTIL, 'YYYYMMDDTHHmmss[Z]');
                    text += ' ' + __('until', 'termin-kalender') + ' ' + untilDate.format('D. MMMM YYYY');
                } else {
                    const untilDate = moment(rruleParts.UNTIL, 'YYYYMMDDTHHmmss[Z]');
                    text += ' ' + __('until', 'termin-kalender') + ' ' + untilDate.format('D. MMMM YYYY');
                }

            }

            // Add COUNT if present
            if (rruleParts.COUNT) {
                text += ' (' + rruleParts.COUNT + ' ' + __('times', 'termin-kalender') + ')';
            }

            // Add EXDATE (exclusions) if present
            if (rruleParts.EXDATE) {
                const exdates = rruleParts.EXDATE.split(',').map(date => {
                    if (ep.until) {
                        return moment.utc(date, 'YYYYMMDDTHHmmss[Z]').format('D. MMM YYYY');
                    } else {
                        return moment(date, 'YYYYMMDDTHHmmss[Z]').format('D. MMM YYYY');
                    }
                });
                text += '; ' + __('excluding', 'termin-kalender') + ' ' + exdates.join(', ');
            }
        }
    //}

    return text;
}



    /**
     * Helper: Calculate Export Dates
     * Centralizes the logic for All-Day offsets and Date Formatting.
     * Prepares robust 'dtstart' and 'dtend' strings required for standard and recurring events.
     */
    function calc_export_dates(event, origin, platform) {
        const ep = event.extendedProps || {};
        const isAllDay = event.allDay || ep.allDay;
        // Clone moments to avoid mutating the original event object
        let s, e, startTime, endTime, startDay;
        //console.log('origin: ', origin);
        if (origin === 'frontent_calendar') {
            // its a Fullcalendar fronten calendar and we use UTC only and always
            // Use UTC to ensure consistency across exports
            s = moment.utc(event.start);
            startTime = moment.utc(event.start).format('HH:mm');
             e = event.end ? moment.utc(event.end) : moment.utc(s);


            if (!ep.freq && !ep.rrule ) {
                endTime   = moment.utc(event.end).format('HH:mm');
            } else {
                //e = ep.until ? moment.utc(ep.until) : moment.utc(s);
                e = moment.utc(s);
                e.set({
                    hour: moment(ep.until).hour(),
                    minute: moment(ep.until).minute()
                });
                endTime   = moment.utc(ep.until).format('HH:mm');
            }
        } else {
            // its a ical calendar and we do not use UTC
            s = moment.utc(event.start);
            startTime = moment.utc(event.start).format('HH:mm');
            e = event.end ? moment.utc(event.end) : moment.utc(s);

            if (!ep.freq && !ep.rrule ) {

                endTime   = moment.utc(event.end).format('HH:mm');
            } else {
                //e = ep.until ? moment.utc(ep.until) : moment.utc(s);
                e = moment.utc(s);
                e.set({
                    hour: moment(ep.until).hour(),
                    minute: moment(ep.until).minute()
                });
                endTime   = moment(ep.until).format('HH:mm');
            }

        }
        //------------
        startDay  = s.format('D. MMMM YYYY');
        let dtstart, dtend;
        if (isAllDay) {
            // --- ALL DAY LOGIC (Platform specific offsets) ---
            startTime = '';
            endTime   = '';
            // 1. ICS (Standard): Start = Raw, End = +1 Day (Exclusive)
            if (platform === 'ics') {
                //if (origin !== 'frontent_calendar') e.add(1, 'day');
                dtstart = s.format(ICS_FORMAT_DATE);
                dtend   = e.format(ICS_FORMAT_DATE);
            }
            // 2. Google / Yahoo: Start = +1 Day, End = +1 Day (if not frontend)
            else if (platform === 'google' || platform === 'yahoo' || platform === 'social') {
                if (origin !== 'frontent_calendar') {
                   // s.add(1, 'day');
                   // e.add(1, 'day');
                }
                dtstart = s.format(ICS_FORMAT_DATE);
                dtend   = e.format(ICS_FORMAT_DATE);
            }
            // 3. Outlook: Start = +1 Day (align w/ Google), End = Raw. (Format YYYY-MM-DD)
            else if (platform === 'outlook') {
                //if (origin !== 'frontent_calendar') s.add(1, 'day');
                dtstart = s.format('YYYY-MM-DD');
                dtend   = e.format('YYYY-MM-DD');
            }
        }
        else {
            // --- TIMED LOGIC ---
            // ICS: UTC + 'Z'
            if (platform === 'ics') {
                dtstart = s.format(ICS_FORMAT) + 'Z';
                dtend   = e.format(ICS_FORMAT) + 'Z';
            }
            // Outlook: YYYY-MM-DDTHH:mm:ss (No Z)
            else if (platform === 'outlook') {
                dtstart = s.format('YYYY-MM-DDTHH:mm:ss');
                dtend   = e.format('YYYY-MM-DDTHH:mm:ss');
            }
            // Google / Yahoo: Compact UTC (No Z)
            else {
                dtstart = s.format(ICS_FORMAT);
                dtend   = e.format(ICS_FORMAT);
            }
        }

        return { dtstart: dtstart, dtend: dtend, isAllDay: isAllDay, startTime: startTime, endTime: endTime, startDay: startDay  }; // , durationMs: durationMs
    }
    //---------------------------------------------------------------------------------
    // TEXT GENERATION (For Social Sharing)
    //---------------------------------------------------------------------------------
    // event, calendar_link, origin, ter_kal_link,
    function formatEventText(event, calendar_link, origin, ter_kal_link, useEmojis = true, d) {
        const ep = event.extendedProps || {};
        // Config: Define labels based on useEmojis flag
        const icon = {
            title:  useEmojis ? '📅 ' : '', // Title usually has no label in text, just the emoji
            date:   useEmojis ? '📆 ' : 'Date: ',
            time:   useEmojis ? '🕐 ' : 'Time: ',
            repeat: useEmojis ? '🔁 ' : 'Repeat: ',
            loc:    useEmojis ? '📍 ' : 'Location: ',
            link:   useEmojis ? '🔗 ' : 'Link: ',
            cat:    useEmojis ? '🏷️ ' : 'Category: ',
            made:   useEmojis ? '🛠️ ' : 'Made with: ' // <--- Added here
        };

        let text = icon.title + (event.title || '') + '\n';

        // Add Category
        const cat = get_category(event);
        if (cat) text += icon.cat + cat + '\n';

        if (event.allDay) {
            text += icon.date + d.startDay + '\n';
        } else {
            text += icon.date + d.startDay + '\n';
            text += icon.time + d.startTime + ' - ' + d.endTime + '\n';
        }

        if (origin === 'frontent_calendar') {
        text += get_recurrence_text(event) + '\n';
        }

        if (ep.description || ep.details) {
            const rawDesc = ep.description || ep.details;
            const desc = (typeof stripHtml === 'function') ? stripHtml(rawDesc) : rawDesc.replace(/<[^>]*>?/gm, '');
            text += '\n' + desc + '\n';
        }

        if (ep.location) text += icon.loc + ep.location + '\n';
        if (ter_kal_link) text += '\n' + icon.link + (ter_kal_link === true ? window.location.href : ter_kal_link);
        if (calendar_link) text += '\n' + icon.made + calendar_link + '\n';
        return text;
    }


//---------------------------------------------------------------------------------
// EXPORT GENERATORS
//---------------------------------------------------------------------------------

    // 1. ICS Export
    window.TerminKalender.createAndDownloadICS = function(event, calendar_link, origin, ter_kal_link) {
        const ep = event.extendedProps || {};
        ter_kal_link = ep.permalink || ter_kal_link || window.location.href;

        // 1. Calculate Dates (Single Instance)
        const d = calc_export_dates(event, origin, 'ics');

        const uid = (ep.eventID || ep.uid || Date.now()) + '@termin-kalender.pro';
        const title = escapeICalText(event.title ||  '');
        const cat = get_category(event);
        const catProp = cat ? 'CATEGORIES:' + escapeICalText(cat) : '';

        // 2. Build Description (Includes Recurrence Text)
        //const descText = ter_kal_build_description(event, calendar_link, ter_kal_link);
        const descText = formatEventText(event, calendar_link, origin, ter_kal_link, false, d);



        const description = escapeICalText(descText);
        const location = escapeICalText(ep.location || '');

        let ics = [
            'BEGIN:VCALENDAR', 'VERSION:2.0', 'PRODID:-//Termin Kalender//termin-kalender.pro//DE',
            'CALSCALE:GREGORIAN', 'METHOD:PUBLISH', 'BEGIN:VEVENT',
            'UID:' + uid,
            'DTSTAMP:' + moment.utc().format(ICS_FORMAT) + 'Z',
            'DTSTART' + (d.isAllDay ? ';VALUE=DATE:' : ':') + d.dtstart,
            'DTEND' + (d.isAllDay ? ';VALUE=DATE:' : ':') + d.dtend,
            'SUMMARY:' + title,
            description ? 'DESCRIPTION:' + description : '',
            location ? 'LOCATION:' + location : '',
            buildRRule(event),
            catProp,
            ter_kal_link ? 'URL:' + ter_kal_link : '',
            'END:VEVENT', 'END:VCALENDAR'
        ].filter(Boolean).join('\r\n');

        const blob = new Blob([ics], { type: 'text/calendar;charset=utf-8' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = (event.title || 'event') + '.ics';
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
    };

    // 2. Google Calendar URL
    window.TerminKalender.getGoogleUrl = function(event, calendar_link, origin, ter_kal_link) {
        const ep = event.extendedProps || {};
        ter_kal_link = ep.permalink || ter_kal_link || window.location.href;
        // 1. Dates
        const d = calc_export_dates(event, origin, 'google');
        const dates = d.dtstart + '/' + d.dtend;
        // 2. Description
        //const descRaw = ter_kal_build_description(event, calendar_link, ter_kal_link);
        const descRaw = formatEventText(event, calendar_link, origin, ter_kal_link, true, d);
        let url = 'https://calendar.google.com/calendar/render?action=TEMPLATE';
        url += '&text=' + encodeURIComponent(event.title ||  '');
        url += '&dates=' + dates;
        url += '&details=' + encodeURIComponent(descRaw);
        url += '&location=' + encodeURIComponent(ep.location || '');

        // REMOVED: &recur param - Exporting single instance only

        return url;
    };

    // 3. Outlook URL
    window.TerminKalender.getOutlookUrl = function(event, calendar_link, origin, ter_kal_link) {
        const ep = event.extendedProps || {};
        ter_kal_link = ep.permalink || ter_kal_link || window.location.href;
        const d = calc_export_dates(event, origin, 'outlook');
        //const descRaw = ter_kal_build_description(event, calendar_link, ter_kal_link);
        const descRaw = formatEventText(event, calendar_link, origin, ter_kal_link, true, d);
        let url = 'https://outlook.live.com/calendar/0/deeplink/compose?path=/calendar/action/compose&rru=addevent';
        url += '&subject=' + encodeURIComponent(event.title ||  '');
        url += '&startdt=' + encodeURIComponent(d.dtstart);
        if (!d.isAllDay)url += '&enddt=' + encodeURIComponent(d.dtend);
        if (d.isAllDay) url += '&allday=true';
        url += '&body=' + encodeURIComponent(descRaw);
        url += '&location=' + encodeURIComponent(ep.location || '');
        return url;
    };

    // 4. Yahoo URL
    window.TerminKalender.getYahooUrl = function(event, calendar_link, origin, ter_kal_link) {
        const ep = event.extendedProps || {};
        ter_kal_link = ep.permalink || ter_kal_link || window.location.href;

        const d = calc_export_dates(event, origin, 'yahoo'); // Yahoo uses Google logic usually
        //const descRaw = ter_kal_build_description(event, calendar_link, ter_kal_link);
        const descRaw = formatEventText(event, calendar_link, origin, ter_kal_link, false, d);
        let includeEt = true;
        let url = 'https://calendar.yahoo.com/?v=60&view=d&type=20';
        url += '&title=' + encodeURIComponent(event.title ||  '');
        url += '&st=' + d.dtstart;
        // Only add End Time if it's NOT a single-day all-day event
        if (!d.isAllDay) {
            url += '&et=' + d.dtend;
        }
        url += '&desc=' + encodeURIComponent(descRaw);
        url += '&in_loc=' + encodeURIComponent(ep.location || '');
        if (d.isAllDay) url += '&dur=allday';
        return url;
    };




    // Wrappers
    window.TerminKalender.getAppleUrl = function(event, cLink, origin) {
        window.TerminKalender.createAndDownloadICS(event, cLink, origin);
        return '';
    };
    window.TerminKalender.getOffice365Url = function(event, cLink, origin) {
        return window.TerminKalender.getOutlookUrl(event, cLink, origin).replace('outlook.live.com', 'outlook.office.com');
    };


    //---------------------------------------------------------------------------------
    // SOCIAL SHARING FUNCTIONS
    //---------------------------------------------------------------------------------
    // 1) WhatsApp (Clean Text, No Emojis, includes Category)
/*    window.TerminKalender.shareWhatsApp = function(event, calendar_link, origin, ter_kal_link) {
        const d = calc_export_dates(event, origin, 'social');
        const text = formatEventText(event, calendar_link, origin, ter_kal_link,  false, d);
        window.open('https://wa.me/?text=' + encodeURIComponent(text), '_blank', 'width=600,height=400');
    };*/
    // ter_kal_change: Smart WhatsApp routing - mobile app vs web
    window.TerminKalender.shareWhatsApp = function(event, calendar_link, origin, ter_kal_link) {
        const d = calc_export_dates(event, origin, 'social');
        const text = formatEventText(event, calendar_link, origin, ter_kal_link, true, d);
        const isMobile = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);
        const url = isMobile
            ? 'whatsapp://send?text=' + encodeURIComponent(text)
            : 'https://web.whatsapp.com/send?text=' + encodeURIComponent(text);
        window.open(url, '_blank', 'width=600,height=400');
    };


    // 2) Telegram (With Emojis, includes Category)
    window.TerminKalender.shareTelegram = function(event, calendar_link, origin, ter_kal_link) {
        const d = calc_export_dates(event, origin, 'social');
        const text = formatEventText(event, calendar_link, origin, ter_kal_link, true, d);
        window.open('https://t.me/share/url?url=' + encodeURIComponent(ter_kal_link || window.location.href) +
                    '&text=' + encodeURIComponent(text), '_blank', 'width=600,height=400');
    };

    // 3) Email
    window.TerminKalender.shareEmail = function(event, calendar_link, origin, ter_kal_link) {
        const subject = event.title ||  '';
        // useEmojis = true
        const d = calc_export_dates(event, origin, 'social');
        const body = formatEventText(event, calendar_link, origin, ter_kal_link, true, d);
        const mailtoLink = 'mailto:?subject=' + encodeURIComponent(subject) + '&body=' + encodeURIComponent(body);
        window.open(mailtoLink, '_blank');
    };

    // 4) SMS (Clean Text, No Emojis, includes Category)
    window.TerminKalender.shareSMS = function(event, calendar_link, origin, ter_kal_link) {
        const d = calc_export_dates(event, origin, 'social');
        const text = formatEventText(event, calendar_link, origin, ter_kal_link, false, d);
        window.location.href = 'sms:?body=' + encodeURIComponent(text);
    };

    // 5) Facebook
    window.TerminKalender.shareFacebook = function(event, calendar_link, origin, ter_kal_link) {
        const ep = event.extendedProps || {};
        // Check if event already has a permalink (cached from previous share)
//----------------------------------------------------------------------------
/*        if (origin === 'frontent_calendar' && !ep.permalink ) {
            // Prepare event data for backend
            const category_data = ep.category || {};
            const rrule = event.rrule || {};
            const eventData = {
                action: 'ter_kal_create_event_page',
                nonce: terminKalenderData.nonce, // <-- Must be localized in PHP
                title: event.title || '',
                description: ep.description || ep.details || '',
                start: moment.utc(event.start).format('D. MMMM YYYY, HH:mm'),
                end: event.end ? moment.utc(event.end).format('D. MMMM YYYY, HH:mm') : moment.utc(event.start).format('D. MMMM YYYY, HH:mm'),
                until:  moment.utc(ep.until).format('D. MMMM YYYY, HH:mm') || '',
                allDay: event.allDay || false,
                location: ep.location || '',
                category: get_category(event), // Uses existing helper
                uid: ep.uid || ep.eventID || event.id || '',
                category_data: category_data,
                icon: category_data.icon || '',
                textColor: category_data.textColor || '',
                backgroundColor: category_data.backgroundColor || '',
                freq: rrule.freq || '',
                byweekday: rrule.byweekday || '',
                exdate: rrule.exdate || '',
                interval: rrule.interval || '',
                bysetpos: rrule.bysetpos || '',
            };
            jQuery.ajax({
                url: terminKalenderData.ajax_url,
                method: 'POST',
                data: eventData,
                success: function(response) {
                    if (response.success && response.data.permalink) {
                        // Cache permalink in event object for future shares
                        if (!ep.permalink) {
                            ep.permalink = response.data.permalink;
                        }
                        window.open('https://www.facebook.com/sharer/sharer.php?u=' + encodeURIComponent(response.data.permalink), '_blank', 'width=600,height=400');
                    }
                }
            });
        } else {
            if (ep.permalink) {
                window.open('https://www.facebook.com/sharer/sharer.php?u=' + encodeURIComponent(ep.permalink), '_blank', 'width=600,height=400');
                return;
            } else {*/
                const fallbackUrl = ter_kal_link || window.location.href;
                window.open('https://www.facebook.com/sharer/sharer.php?u=' + encodeURIComponent(fallbackUrl), '_blank', 'width=600,height=400');
/*            }
        }*/
//----------------------------------------------------------------------------

    };

    // 5m) Facebook Messenger - Unified solution for text sharing
    window.TerminKalender.shareMessenger = function(event, calendar_link, origin, ter_kal_link) {
        const ep = event.extendedProps || {};
        const permalink_url = ep.permalink || ter_kal_link || window.location.href;
        const d = calc_export_dates(event, origin, 'social');
        const messageText = formatEventText(event, calendar_link, origin, permalink_url, true, d);
        const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
/*        const shareUrl = 'https://www.facebook.com/dialog/send?app_id=' + appId +
                         '&link=' + encodeURIComponent(permalink_url) +
                         '&redirect_uri=' + encodeURIComponent(window.location.href) +
                         '&quote=' + encodeURIComponent(messageText);*/
    // Format message text for better readability in prompt
        var formattedText = messageText
            .replace(/\. /g, '.\n')           // Break at sentences
            .replace(/\n{3,}/g, '\n\n')       // Remove excessive line breaks
            .trim();                          // Clean whitespace
        prompt('📋 Select all (Ctrl+A) and copy (Ctrl+C) to paste into Messenger:', formattedText);
            if (isMobile) {
                window.location = 'fb-messenger://';
            } else {
                window.open('https://www.messenger.com/', '_blank', 'width=600,height=650');
            }
    };

    // 6) Twitter (Content + URL)
    window.TerminKalender.shareTwitter = function(event, calendar_link, origin, ter_kal_link) {
        const d = calc_export_dates(event, origin, 'social');
        const text = formatEventText(event, calendar_link, origin, ter_kal_link, true, d);
        const url = ter_kal_link || window.location.href;
        window.open('https://twitter.com/intent/tweet?text=' + encodeURIComponent(text) +
                    '&url=' + encodeURIComponent(url), '_blank', 'width=600,height=400');
    };

    // 7) LinkedIn
    window.TerminKalender.shareLinkedIn = function(event, calendar_link, origin, ter_kal_link) {
        const url = ter_kal_link || calendar_link || window.location.href;
        window.open('https://www.linkedin.com/sharing/share-offsite/?url=' + encodeURIComponent(url), '_blank', 'width=600,height=400');
    };

    // 8) Native Share
    window.TerminKalender.shareNative = function(event, calendar_link, origin, ter_kal_link) {
        if (!navigator.share) {
            alert(terminKalenderData.strings.share_not_supported || 'Share not supported');
            return;
        }
        navigator.share({
            title: event.title ||  '',
            text: formatEventText(event, false, origin, true, d),
            url: calendar_link || window.location.href
        }).catch(() => {});
    };

//---------------------------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------------------------

    window.TerminKalender.share_buttons_calendar_ical = function(event, origin, ter_kal_link) {

        const calendar_link = 'https://termin-kalender.pro';

        return {

            Google: {
                text: '<span class="tk-emoji">📅</span> Google', class: 'tk_btn_export',
                click: function() { window.open(TerminKalender.getGoogleUrl(event, calendar_link, origin, ter_kal_link)); }
            },
            Outlook: {
                text: '<span class="tk-emoji">📅</span> Outlook', class: 'tk_btn_export',
                click: function() { window.open(TerminKalender.getOutlookUrl(event, calendar_link, origin, ter_kal_link)); }
            },
            Yahoo: {
                text: '<span class="tk-emoji">📅</span> Yahoo', class: 'tk_btn_export',
                click: function() { window.open(TerminKalender.getYahooUrl(event, calendar_link, origin, ter_kal_link)); }
            },
            Office365: {
                text: '<span class="tk-emoji">📅</span> Office 365', class: 'tk_btn_export',
                click: function() { window.open(TerminKalender.getOffice365Url(event, calendar_link, origin, ter_kal_link)); }
            },
            Email: {
                text: '<span class="tk-emoji">📧</span> Email', class: 'tk_btn_share',
                click: function() { TerminKalender.shareEmail(event, calendar_link, origin, ter_kal_link); }
            },
            WhatsApp: {
                text: '<span class="tk-emoji">💬</span> WhatsApp', class: 'tk_btn_share',
                click: function() { TerminKalender.shareWhatsApp(event, calendar_link, origin, ter_kal_link); }
            },
            Twitter: {
                text: '<span class="tk-emoji">✖</span> X', class: 'tk_btn_share',
                click: function() { TerminKalender.shareTwitter(event, calendar_link, origin, ter_kal_link); }
            },
            Telegram: {
                text: '<span class="tk-emoji">✈</span> Telegram', class: 'tk_btn_share',
                click: function() { TerminKalender.shareTelegram(event, calendar_link, origin, ter_kal_link); }
            },

            'ICS Download': {
                text: '<span class="tk-emoji">📥</span> .ics', class: 'tk_btn_primary',
                click: function() { TerminKalender.createAndDownloadICS(event, calendar_link, origin, ter_kal_link); }
            },
            Facebook: {
                text: '<span class="tk-emoji">👍</span> Facebook', class: 'tk_btn_primary',
                click: function() { TerminKalender.shareFacebook(event, calendar_link, origin, ter_kal_link); }
            },
            Messenger: {
                text: '<span class="tk-emoji">💬</span> Messenger', class: 'tk_btn_primary',
                click: function() { TerminKalender.shareMessenger(event, calendar_link, origin, ter_kal_link); }
            },
            LinkedIn: {
                text: '<span class="tk-emoji">💼</span> LinkedIn', class: 'tk_btn_primary',
                click: function() { TerminKalender.shareLinkedIn(event, calendar_link, origin, ter_kal_link); }
            },
            SMS: {
                text: '<span class="tk-emoji">💬</span> SMS', class: 'tk_btn_primary',
                click: function() { TerminKalender.shareSMS(event, calendar_link, origin, ter_kal_link); }
            },
            '---separator1---': { text: '', class: 'tk_btn_separator', disabled: true },
            [terminKalenderData.strings.close]: {
                text: '<span class="tk-emoji">✖</span> ' + terminKalenderData.strings.close, class: 'tk_btn_cancel',
                click: null // Handled natively by frontend interceptor calling dialogEl.close()
            }
        };
    };

    window.TerminKalender.render_dialog_footer_buttons = function(dialogEl, footerEl, event, origin, ter_kal_link) {
        if (!footerEl) return;
        const buttonsObj = window.TerminKalender.share_buttons_calendar_ical(event, origin, ter_kal_link);
        footerEl.innerHTML = '';
        Object.entries(buttonsObj).forEach(([key, btnDef]) => {
            if (btnDef.disabled) return;
            const btn = document.createElement('button');
            btn.type = 'button';
            btn.className = btnDef.class || 'tk_btn';
            btn.innerHTML = btnDef.text;
            btn.addEventListener('click', function(e) {
                e.preventDefault();
                if (key === terminKalenderData.strings.cancel || key === terminKalenderData.strings.close ||
                    btnDef.text.includes(terminKalenderData.strings.cancel) || btnDef.text.includes(terminKalenderData.strings.close)) {
                    dialogEl.close();
                } else if (btnDef.click) {
                    btnDef.click.call(dialogEl, e);
                }
            });
            footerEl.appendChild(btn);
        });
    };

});
