/**
 * Vollstart Repair Desk — Public Frontend JavaScript
 *
 * Renders the status lookup form and displays repair status.
 * Uses wp.i18n for translations.
 */
(function($) {
    'use strict';

    var __ = wp.i18n.__;
    var cfg = window.vollstartRdPublic || {};

    // --- Modal Spinner ---
    var spinnerCount = 0;
    function rdShowSpinner() {
        spinnerCount++;
        if (spinnerCount === 1) {
            $('body').append('<div id="rd-modal-spinner"></div>');
        }
    }
    function rdHideSpinner() {
        spinnerCount = Math.max(0, spinnerCount - 1);
        if (spinnerCount === 0) {
            $('#rd-modal-spinner').remove();
        }
    }

    // --- Auto-fill from direct link (/repair-status/A1B2-C3D4) ---

    $(document).ready(function() {
        var auto = window.vollstartRdAutoLookup;
        if (auto && auto.accessCode) {
            $('#rd-lookup-code').val(auto.accessCode);
            if (auto.repairNumber) {
                // Both values: auto-submit
                $('#rd-lookup-number').val(auto.repairNumber);
                $('#rd-status-form').trigger('submit');
            } else {
                $('#rd-lookup-number').focus();
            }
        }
    });

    // --- Status Lookup ---

    $(document).on('submit', '#rd-status-form', function(e) {
        e.preventDefault();
        var number = $('#rd-lookup-number').val().trim();
        var code = $('#rd-lookup-code').val().trim();

        if (!number || !code) return;

        var $btn = $(this).find('.rd-btn-lookup');
        $btn.prop('disabled', true).text(__('Checking...', 'vollstart-repair-desk'));
        $('#rd-status-error').hide();
        $('#rd-status-result').hide();
        rdShowSpinner();

        $.post(cfg.ajaxurl, {
            action: 'vollstart_rd_public',
            sub_action: 'lookup',
            nonce: cfg.nonce,
            repair_number: number,
            access_code: code
        }, function(response) {
            $btn.prop('disabled', false).text(__('Check Status', 'vollstart-repair-desk'));
            if (response.success) {
                renderResult(response.data);
            } else {
                $('#rd-status-error').text(response.data.message || __('Not found.', 'vollstart-repair-desk')).show();
            }
            rdHideSpinner();
        }).fail(function() {
            $btn.prop('disabled', false).text(__('Check Status', 'vollstart-repair-desk'));
            $('#rd-status-error').text(__('Connection error. Please try again.', 'vollstart-repair-desk')).show();
            rdHideSpinner();
        });
    });

    function renderResult(data) {
        var html = buildResultHtml(data);
        $('#rd-status-result').html(html).show();
        $('#rd-status-lookup').hide();
        // Generate QR code
        if (data.status_url && typeof QRCode !== 'undefined') {
            var qrEl = document.getElementById('rd-public-qr');
            if (qrEl) new QRCode(qrEl, { text: data.status_url, width: 180, height: 180, colorDark: '#1e293b', colorLight: '#ffffff', correctLevel: QRCode.CorrectLevel.M });
        }
    }

    function buildResultHtml(data) {
        var html = '';

        // QR code (for sharing on phone)
        if (data.status_url) {
            html += '<div style="text-align:center;padding:16px 16px 0"><div id="rd-public-qr" style="display:inline-block;background:#fff;padding:12px;border-radius:8px"></div></div>';
        }

        // Status card
        html += '<div class="rd-status-card">';
        html += '<div class="rd-status-header">';
        html += '<span class="rd-status-number">' + esc(data.repair_number) + '</span>';
        html += '<span class="rd-status-badge" style="background:' + esc(data.status_color) + '">' + esc(data.status_label) + '</span>';
        html += '</div>';

        // Repair details
        var device = [data.device_brand, data.device_model].filter(Boolean).join(' ');
        if (device) {
            html += '<div class="rd-status-row"><span class="rd-status-label">' + __('Device', 'vollstart-repair-desk') + '</span><span>' + esc(device) + '</span></div>';
        }
        if (data.device_serial) {
            html += '<div class="rd-status-row"><span class="rd-status-label">' + __('Serial', 'vollstart-repair-desk') + '</span><span>' + esc(data.device_serial) + '</span></div>';
        }
        if (data.defect) {
            html += '<div class="rd-status-row"><span class="rd-status-label">' + __('Issue', 'vollstart-repair-desk') + '</span><span>' + esc(data.defect) + '</span></div>';
        }
        if (data.priority && data.priority !== 'normal') {
            var prioLabel = data.priority === 'urgent' ? __('Urgent', 'vollstart-repair-desk') : __('High', 'vollstart-repair-desk');
            var prioColor = data.priority === 'urgent' ? '#dc2626' : '#f59e0b';
            html += '<div class="rd-status-row"><span class="rd-status-label">' + __('Priority', 'vollstart-repair-desk') + '</span><span style="color:' + prioColor + ';font-weight:600">' + prioLabel + '</span></div>';
        }
        if (data.created_at) {
            html += '<div class="rd-status-row"><span class="rd-status-label">' + __('Received', 'vollstart-repair-desk') + '</span><span>' + formatDate(data.created_at) + '</span></div>';
        }
        if (data.estimated_date) {
            html += '<div class="rd-status-row"><span class="rd-status-label">' + __('Estimated completion', 'vollstart-repair-desk') + '</span><span>' + formatDate(data.estimated_date) + '</span></div>';
        }
        if (data.estimated_price) {
            html += '<div class="rd-status-row"><span class="rd-status-label">' + __('Estimated price', 'vollstart-repair-desk') + '</span><span>' + parseFloat(data.estimated_price).toFixed(2) + ' ' + (data.currency || '&euro;') + '</span></div>';
        }
        if (data.warranty_until) {
            var wpToday = new Date(); wpToday.setHours(0,0,0,0);
            var wpDate = new Date(data.warranty_until + 'T00:00:00');
            var wpDiff = Math.round((wpDate - wpToday) / 86400000);
            var wpColor = wpDiff < 0 ? '#ef4444' : wpDiff <= 30 ? '#f59e0b' : '#22c55e';
            var wpLabel = wpDiff < 0 ? __('Expired', 'vollstart-repair-desk') : wpDiff <= 30 ? __('Expiring soon', 'vollstart-repair-desk') : __('Active', 'vollstart-repair-desk');
            html += '<div class="rd-status-row"><span class="rd-status-label">' + __('Warranty', 'vollstart-repair-desk') + '</span><span>' + formatDate(data.warranty_until) + ' <span style="font-size:11px;color:' + wpColor + ';font-weight:600">(' + wpLabel + ')</span></span></div>';
        }
        // Repair files inside card
        if (data.files && data.files.length > 0) {
            html += '<div style="padding:10px 16px;border-top:1px solid #f1f5f9">' + renderPublicFiles(data.files) + '</div>';
        }
        html += '</div>';

        // Messages (above timeline)
        if (data.messages && data.messages.length > 0) {
            html += '<div class="rd-status-section">';
            html += '<h3>' + __('Messages', 'vollstart-repair-desk') + '</h3>';
            for (var j = 0; j < data.messages.length; j++) {
                var m = data.messages[j];
                var isShop = m.sender_type === 'staff' || m.sender_type === 'shop';
                html += '<div class="rd-message ' + (isShop ? 'rd-message-shop' : 'rd-message-customer') + '">';
                html += '<div class="rd-message-text">' + esc(m.message) + '</div>';
                html += '<div class="rd-message-meta">' + (isShop ? __('Workshop', 'vollstart-repair-desk') : __('You', 'vollstart-repair-desk')) + ' &middot; ' + formatDate(m.created_at) + '</div>';
                html += '</div>';
            }
            // Reply form inside messages section
            if (data.allow_reply) {
                html += '<form id="rd-reply-form" data-number="' + esc(data.repair_number) + '" data-code="' + esc(data.access_code || '') + '" style="margin-top:10px">';
                html += '<textarea id="rd-reply-text" rows="3" placeholder="' + __('Write a message...', 'vollstart-repair-desk') + '" style="width:100%;padding:10px;border:1px solid #e2e8f0;border-radius:8px;font-size:14px;resize:vertical;box-sizing:border-box"></textarea>';
                html += '<button type="submit" class="rd-btn-lookup" style="margin-top:8px">' + __('Send', 'vollstart-repair-desk') + '</button>';
                html += '</form>';
            }
            html += '</div>';
        } else if (data.allow_reply) {
            // No messages yet but reply allowed
            html += '<div class="rd-status-section">';
            html += '<h3>' + __('Messages', 'vollstart-repair-desk') + '</h3>';
            html += '<form id="rd-reply-form" data-number="' + esc(data.repair_number) + '" data-code="' + esc(data.access_code || '') + '">';
            html += '<textarea id="rd-reply-text" rows="3" placeholder="' + __('Write a message...', 'vollstart-repair-desk') + '" style="width:100%;padding:10px;border:1px solid #e2e8f0;border-radius:8px;font-size:14px;resize:vertical;box-sizing:border-box"></textarea>';
            html += '<button type="submit" class="rd-btn-lookup" style="margin-top:8px">' + __('Send', 'vollstart-repair-desk') + '</button>';
            html += '</form>';
            html += '</div>';
        }

        // Work steps
        if (data.work_steps) {
            var hasSteps = false;
            var stepsHtml = '';
            for (var groupName in data.work_steps) {
                hasSteps = true;
                var items = data.work_steps[groupName];
                stepsHtml += '<div class="rd-steps-group">';
                stepsHtml += '<div class="rd-steps-group-title">' + esc(groupName) + '</div>';
                for (var si = 0; si < items.length; si++) {
                    var step = items[si];
                    stepsHtml += '<div class="rd-step-row ' + (step.is_checked ? 'rd-step-done' : '') + '">';
                    stepsHtml += '<span class="rd-step-check">' + (step.is_checked ? '&#10003;' : '&#9675;') + '</span>';
                    stepsHtml += '<span class="rd-step-title">' + esc(step.title) + '</span>';
                    var stepMin = Math.round(step.duration);
                    if (stepMin > 0) {
                        stepsHtml += '<span class="rd-step-time">' + stepMin + ' min</span>';
                    }
                    stepsHtml += '</div>';
                    // Step files
                    if (step.files && step.files.length > 0) {
                        stepsHtml += '<div class="rd-public-gallery rd-step-files">';
                        for (var sfi = 0; sfi < step.files.length; sfi++) {
                            var sf = step.files[sfi];
                            stepsHtml += '<a class="rd-public-file rd-public-file-sm" href="' + esc(sf.url) + '" target="_blank">';
                            if (sf.is_image) {
                                stepsHtml += '<img src="' + esc(sf.url) + '" alt="' + esc(sf.name) + '">';
                            } else {
                                stepsHtml += '<div class="rd-public-file-icon">&#128196;</div>';
                            }
                            stepsHtml += '</a>';
                        }
                        stepsHtml += '</div>';
                    }
                }
                stepsHtml += '</div>';
            }
            if (hasSteps) {
                html += '<div class="rd-status-section">';
                html += '<h3>' + __('Work Steps', 'vollstart-repair-desk') + '</h3>';
                html += stepsHtml;
                html += '</div>';
            }
        }

        // Billing summary
        if (data.billing && data.billing.total > 0) {
            // Determine context: portal detail or status page
            var isPortal = $('#rd-portal-content').length > 0;
            var showBilling = isPortal ? data.billing_in_portal : data.billing_on_status;
            if (showBilling) {
                var cur = data.currency || '\u20ac';
                html += '<div class="rd-status-section">';
                html += '<h3>' + __('Cost Summary', 'vollstart-repair-desk') + '</h3>';
                html += '<table class="rd-billing-table" style="width:100%;border-collapse:collapse;font-size:14px">';
                if (data.billing.show_est && data.billing.est_price > 0) {
                    html += '<tr style="border-bottom:1px solid #f1f5f9"><td style="padding:8px 0;color:#64748b">' + __('Base Price', 'vollstart-repair-desk') + '</td><td style="padding:8px 0;text-align:right;font-weight:500">' + parseFloat(data.billing.est_price).toFixed(2) + ' ' + cur + '</td></tr>';
                }
                if (data.billing.materials > 0) {
                    html += '<tr style="border-bottom:1px solid #f1f5f9"><td style="padding:8px 0;color:#64748b">' + __('Materials', 'vollstart-repair-desk') + '</td><td style="padding:8px 0;text-align:right;font-weight:500">' + parseFloat(data.billing.materials).toFixed(2) + ' ' + cur + '</td></tr>';
                }
                if (data.billing.steps_flat > 0) {
                    html += '<tr style="border-bottom:1px solid #f1f5f9"><td style="padding:8px 0;color:#64748b">' + __('Work Steps', 'vollstart-repair-desk') + '</td><td style="padding:8px 0;text-align:right;font-weight:500">' + parseFloat(data.billing.steps_flat).toFixed(2) + ' ' + cur + '</td></tr>';
                }
                if (data.billing.labor > 0) {
                    html += '<tr style="border-bottom:1px solid #f1f5f9"><td style="padding:8px 0;color:#64748b">' + __('Labor', 'vollstart-repair-desk') + '</td><td style="padding:8px 0;text-align:right;font-weight:500">' + parseFloat(data.billing.labor).toFixed(2) + ' ' + cur + '</td></tr>';
                }
                html += '<tr><td style="padding:10px 0 0;font-weight:700;font-size:15px;color:#1e293b">' + __('Total', 'vollstart-repair-desk') + '</td><td style="padding:10px 0 0;text-align:right;font-weight:700;font-size:15px;color:#1e293b">' + parseFloat(data.billing.total).toFixed(2) + ' ' + cur + '</td></tr>';
                html += '</table>';
                html += '</div>';
            }
        }

        // Timeline (last)
        if (data.timeline && data.timeline.length > 0) {
            html += '<div class="rd-status-timeline">';
            html += '<h3>' + __('Status History', 'vollstart-repair-desk') + '</h3>';
            for (var i = 0; i < data.timeline.length; i++) {
                var t = data.timeline[i];
                html += '<div class="rd-timeline-item">';
                html += '<div class="rd-timeline-dot" style="background:' + esc(t.color) + '"></div>';
                html += '<div class="rd-timeline-content">';
                html += '<span class="rd-timeline-status">' + esc(t.status) + '</span>';
                html += '<span class="rd-timeline-date">' + formatDate(t.created_at) + '</span>';
                if (t.note) html += '<span class="rd-timeline-note">' + esc(t.note) + '</span>';
                html += '</div></div>';
            }
            html += '</div>';
        }

        // Rating
        if (data.allow_rating !== undefined) {
            html += '<div class="rd-status-section">';
            html += '<h3>' + __('Rate your repair', 'vollstart-repair-desk') + '</h3>';
            if (data.rating > 0 && !data.allow_rating) {
                // Already rated, no update allowed
                html += '<div style="text-align:center;padding:8px">';
                html += '<div style="font-size:28px">' + renderStars(data.rating) + '</div>';
                if (data.rating_comment) html += '<p style="color:#64748b;font-size:13px;margin:4px 0 0">' + esc(data.rating_comment) + '</p>';
                html += '<p style="color:#22c55e;font-size:13px;margin:8px 0 0">' + __('Thank you for your feedback!', 'vollstart-repair-desk') + '</p>';
                html += '</div>';
            } else {
                // Rating form
                var existRating = data.rating || 0;
                html += '<div style="text-align:center;padding:8px">';
                html += '<div id="rd-status-star-select" style="font-size:32px;cursor:pointer;margin-bottom:8px">';
                for (var ri = 1; ri <= 5; ri++) {
                    html += '<span class="rd-star" data-value="' + ri + '" style="color:' + (ri <= existRating ? '#f59e0b' : '#e2e8f0') + ';transition:color 0.15s">&#9733;</span>';
                }
                html += '</div>';
                html += '<input type="hidden" id="rd-status-rating-val" value="' + existRating + '">';
                html += '<textarea id="rd-status-rating-comment" rows="2" placeholder="' + __('Comment (optional)', 'vollstart-repair-desk') + '" style="width:100%;padding:8px;border:1px solid #e2e8f0;border-radius:8px;font-size:14px;box-sizing:border-box;resize:vertical;margin-bottom:8px">' + esc(data.rating_comment || '') + '</textarea>';
                html += '<button id="rd-status-submit-rating" class="rd-btn-lookup" data-number="' + esc(data.repair_number) + '" data-code="' + esc(data.access_code || '') + '" style="width:100%">' + __('Submit Rating', 'vollstart-repair-desk') + '</button>';
                html += '</div>';
            }
            html += '</div>';
        }

        // Portal link
        if (data.portal_url) {
            html += '<div style="text-align:center;margin-top:12px"><a href="' + esc(data.portal_url) + '" style="display:inline-block;padding:10px 24px;background:#1e293b;color:#fff;border-radius:8px;text-decoration:none;font-size:14px;font-weight:600"><span class="dashicons dashicons-smartphone" style="font-size:16px;width:16px;height:16px;margin-right:6px;vertical-align:middle"></span>' + __('My Repairs', 'vollstart-repair-desk') + '</a></div>';
        }

        return html;
    }

    // --- Reply ---

    $(document).on('submit', '#rd-reply-form', function(e) {
        e.preventDefault();
        var $form = $(this);
        var message = $('#rd-reply-text').val().trim();
        if (!message) return;
        var $btn = $form.find('button[type="submit"]');
        $btn.prop('disabled', true).text(__('Sending...', 'vollstart-repair-desk'));
        rdShowSpinner();
        $.post(cfg.ajaxurl, {
            action: 'vollstart_rd_public',
            sub_action: 'reply',
            nonce: cfg.nonce,
            access_code: $form.data('code'),
            message: message
        }, function(response) {
            $btn.prop('disabled', false).text(__('Send', 'vollstart-repair-desk'));
            if (response.success) {
                $('#rd-reply-text').val('');
                // Re-lookup to refresh messages
                var rNumber = $form.data('number');
                var rCode = $form.data('code');
                $.post(cfg.ajaxurl, {
                    action: 'vollstart_rd_public',
                    sub_action: 'lookup',
                    nonce: cfg.nonce,
                    repair_number: rNumber,
                    access_code: rCode
                }, function(res) {
                    if (res.success) {
                        var target = $('#rd-portal-detail-content');
                        if (target.length) {
                            target.html(buildResultHtml(res.data));
                        } else {
                            renderResult(res.data);
                        }
                    }
                    rdHideSpinner();
                });
            } else {
                alert(response.data.message || __('Error', 'vollstart-repair-desk'));
                rdHideSpinner();
            }
        });
    });

    // --- PWA Install ---

    var deferredInstallPrompt = null;
    var isStandalone = window.matchMedia('(display-mode: standalone)').matches || window.navigator.standalone;

    window.addEventListener('beforeinstallprompt', function(e) {
        e.preventDefault();
        deferredInstallPrompt = e;
        $('#rd-pwa-install').show();
    });

    $(document).on('click', '#rd-pwa-install', function() {
        if (deferredInstallPrompt) {
            deferredInstallPrompt.prompt();
            deferredInstallPrompt.userChoice.then(function() { deferredInstallPrompt = null; $('#rd-pwa-install, #rd-pwa-banner').hide(); });
        }
    });

    $(document).on('click', '#rd-pwa-banner-close', function() {
        $('#rd-pwa-banner').hide();
        try { sessionStorage.setItem('rd_pwa_dismissed', '1'); } catch(e) {}
    });

    // Show install banner after portal loads (if not standalone, not dismissed)
    function maybeShowPwaBanner() {
        if (isStandalone) return;
        if (!window.vollstartRdPortal) return;
        try { if (sessionStorage.getItem('rd_pwa_dismissed')) return; } catch(e) {}

        var isIos = /iphone|ipad|ipod/i.test(navigator.userAgent);
        var html = '<div id="rd-pwa-banner" style="background:#1e293b;color:#fff;border-radius:12px;padding:12px 16px;margin-bottom:16px;display:flex;align-items:center;gap:12px">';
        html += '<span style="font-size:28px;flex-shrink:0">&#128241;</span>';
        html += '<div style="flex:1;min-width:0">';
        html += '<div style="font-size:14px;font-weight:600">' + __('Install as App', 'vollstart-repair-desk') + '</div>';
        if (isIos) {
            html += '<div style="font-size:12px;color:#94a3b8;margin-top:2px">' + __('Tap', 'vollstart-repair-desk') + ' <span style="font-size:16px">&#9757;</span> Share → ' + __('Add to Home Screen', 'vollstart-repair-desk') + '</div>';
        } else if (deferredInstallPrompt) {
            html += '<div style="font-size:12px;color:#94a3b8;margin-top:2px">' + __('Quick access from your home screen', 'vollstart-repair-desk') + '</div>';
        } else {
            html += '<div style="font-size:12px;color:#94a3b8;margin-top:2px">' + __('Use your browser menu to install this app', 'vollstart-repair-desk') + '</div>';
        }
        html += '</div>';
        if (deferredInstallPrompt) {
            html += '<button id="rd-pwa-install" style="background:#f97316;color:#fff;border:none;border-radius:8px;padding:8px 16px;font-size:13px;font-weight:600;cursor:pointer;white-space:nowrap">' + __('Install', 'vollstart-repair-desk') + '</button>';
        }
        html += '<button id="rd-pwa-banner-close" style="background:none;border:none;color:#64748b;cursor:pointer;font-size:18px;padding:0 4px">&times;</button>';
        html += '</div>';
        $('#rd-portal-content').prepend(html);
    }

    // --- Customer Portal ---

    $(document).ready(function() {
        var portal = window.vollstartRdPortal;
        if (portal && portal.token) {
            loadPortal(portal.token);
        }
    });

    function loadPortal(token) {
        $.post(cfg.ajaxurl, {
            action: 'vollstart_rd_public',
            sub_action: 'portal_repairs',
            nonce: cfg.nonce,
            token: token
        }, function(response) {
            if (!response.success) {
                $('#rd-portal-content').html('<p style="text-align:center;color:#dc2626">' + esc(response.data.message || __('Error', 'vollstart-repair-desk')) + '</p>');
                return;
            }
            var data = response.data;
            var repairs = data.repairs || [];
            var devices = data.devices || [];
            var html = '';

            // Customer profile card
            if (data.profile) {
                var p = data.profile;
                html += '<div class="rd-status-card" style="margin-bottom:16px">';
                html += '<div class="rd-status-header"><span class="rd-status-number">' + esc(p.name) + '</span><span style="font-size:12px;color:#94a3b8">' + esc(p.number) + '</span>';
                html += '<button id="rd-portal-refresh" style="margin-left:auto;background:none;border:1px solid #e2e8f0;border-radius:6px;padding:6px 10px;cursor:pointer;color:#64748b"><span class="dashicons dashicons-update" style="font-size:16px;width:16px;height:16px"></span></button>';
                html += '</div>';
                if (p.email) html += '<div class="rd-status-row"><span class="rd-status-label">' + __('Email', 'vollstart-repair-desk') + '</span><span>' + esc(p.email) + '</span></div>';
                if (p.phone) html += '<div class="rd-status-row"><span class="rd-status-label">' + __('Phone', 'vollstart-repair-desk') + '</span><span>' + esc(p.phone) + '</span></div>';
                if (p.address) html += '<div class="rd-status-row"><span class="rd-status-label">' + __('Address', 'vollstart-repair-desk') + '</span><span>' + esc(p.address) + '</span></div>';
                html += '</div>';
            } else {
                html += '<div style="display:flex;align-items:center;justify-content:center;gap:10px;margin-bottom:12px">';
                html += '<span style="color:#64748b;font-weight:500">' + esc(data.customer_name) + '</span>';
                html += '<button id="rd-portal-refresh" style="background:none;border:1px solid #e2e8f0;border-radius:6px;padding:6px 10px;cursor:pointer;color:#64748b"><span class="dashicons dashicons-update" style="font-size:16px;width:16px;height:16px"></span></button>';
                html += '</div>';
            }

            // Tabs (Repairs + Devices if available)
            if (devices.length > 0) {
                html += '<div style="display:flex;gap:0;margin-bottom:16px;border-bottom:2px solid #e2e8f0">';
                html += '<button class="rd-portal-tab active" data-tab="repairs" style="flex:1;padding:10px;border:none;background:none;font-size:14px;font-weight:600;color:#f97316;border-bottom:2px solid #f97316;margin-bottom:-2px;cursor:pointer">' + __('Repairs', 'vollstart-repair-desk') + ' (' + repairs.length + ')</button>';
                html += '<button class="rd-portal-tab" data-tab="devices" style="flex:1;padding:10px;border:none;background:none;font-size:14px;font-weight:500;color:#94a3b8;border-bottom:2px solid transparent;margin-bottom:-2px;cursor:pointer">' + __('Devices', 'vollstart-repair-desk') + ' (' + devices.length + ')</button>';
                html += '</div>';
            }

            // Repairs panel
            html += '<div id="rd-portal-repairs">';
            if (repairs.length === 0) {
                html += '<p style="text-align:center;color:#94a3b8">' + __('No repairs found.', 'vollstart-repair-desk') + '</p>';
            }
            var qrSvg = '<svg width="18" height="18" viewBox="0 0 18 18" fill="currentColor"><rect x="0" y="0" width="7" height="7" rx="1"/><rect x="2" y="2" width="3" height="3" fill="#fff"/><rect x="3" y="3" width="1" height="1" fill="currentColor"/><rect x="11" y="0" width="7" height="7" rx="1"/><rect x="13" y="2" width="3" height="3" fill="#fff"/><rect x="14" y="3" width="1" height="1" fill="currentColor"/><rect x="0" y="11" width="7" height="7" rx="1"/><rect x="2" y="13" width="3" height="3" fill="#fff"/><rect x="3" y="14" width="1" height="1" fill="currentColor"/><rect x="11" y="11" width="2" height="2"/><rect x="15" y="11" width="3" height="2"/><rect x="11" y="15" width="2" height="3"/><rect x="15" y="15" width="3" height="3"/></svg>';
            for (var i = 0; i < repairs.length; i++) {
                var r = repairs[i];
                html += '<div class="rd-status-card" style="margin-bottom:12px">';
                html += '<div class="rd-status-header">';
                html += '<span class="rd-status-number">' + esc(r.repair_number) + '</span>';
                if (r.unread) html += '<span style="display:inline-flex;align-items:center;justify-content:center;background:#ef4444;color:#fff;font-size:10px;font-weight:700;min-width:18px;height:18px;border-radius:999px;padding:0 4px">' + r.unread + '</span>';
                if (r.status_label) html += '<span class="rd-status-badge" style="background:' + esc(r.status_color) + '">' + esc(r.status_label) + '</span>';
                html += '<button class="rd-show-qr" data-qr="' + esc(r.qr_data) + '" data-number="' + esc(r.repair_number) + '" style="background:none;border:1px solid #e2e8f0;border-radius:6px;padding:4px 8px;cursor:pointer;color:#64748b;margin-left:auto">' + qrSvg + '</button>';
                html += '</div>';
                if (r.device) html += '<div class="rd-status-row"><span class="rd-status-label">' + __('Device', 'vollstart-repair-desk') + '</span><span>' + esc(r.device) + '</span></div>';
                if (r.defect) html += '<div class="rd-status-row"><span class="rd-status-label">' + __('Issue', 'vollstart-repair-desk') + '</span><span style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:200px">' + esc(r.defect) + '</span></div>';
                if (r.created_at) html += '<div class="rd-status-row"><span class="rd-status-label">' + __('Date', 'vollstart-repair-desk') + '</span><span>' + formatDate(r.created_at) + '</span></div>';
                // Repair rating stars
                var repairRatings = data.repair_ratings || {};
                if (repairRatings[r.repair_number]) {
                    html += '<div class="rd-status-row"><span class="rd-status-label">' + __('Your rating', 'vollstart-repair-desk') + '</span><span style="font-size:16px">' + renderStars(repairRatings[r.repair_number]) + '</span></div>';
                }
                // Open button — loads detail inline (app flow)
                if (r.access_code) {
                    html += '<div style="padding:8px 16px;border-top:1px solid #f1f5f9"><button class="rd-portal-open" data-number="' + esc(r.repair_number) + '" data-code="' + esc(r.access_code) + '" style="display:block;width:100%;text-align:center;padding:10px;background:#f97316;color:#fff;border:none;border-radius:8px;font-size:14px;font-weight:600;cursor:pointer">' + __('Open', 'vollstart-repair-desk') + '</button></div>';
                }
                html += '</div>';
            }
            html += '</div>';

            // Devices panel
            if (devices.length > 0) {
                html += '<div id="rd-portal-devices" style="display:none">';
                for (var di = 0; di < devices.length; di++) {
                    var d = devices[di];
                    html += '<div class="rd-status-card" style="margin-bottom:12px">';
                    html += '<div class="rd-status-header"><span class="rd-status-number">' + esc(d.name || [d.brand, d.model].filter(Boolean).join(' ') || __('Device', 'vollstart-repair-desk')) + '</span></div>';
                    if (d.brand || d.model) html += '<div class="rd-status-row"><span class="rd-status-label">' + __('Brand / Model', 'vollstart-repair-desk') + '</span><span>' + esc([d.brand, d.model].filter(Boolean).join(' ')) + '</span></div>';
                    if (d.serial) html += '<div class="rd-status-row"><span class="rd-status-label">' + __('Serial', 'vollstart-repair-desk') + '</span><span>' + esc(d.serial) + '</span></div>';
                    // Maintenance info
                    if (d.service_interval_days && d.next_service_date) {
                        var dToday = new Date(); dToday.setHours(0,0,0,0);
                        var dNext = new Date(d.next_service_date + 'T00:00:00');
                        var dDiff = Math.round((dNext - dToday) / 86400000);
                        if (dDiff <= 0 && !d.service_reminder_sent) {
                            html += '<div style="margin:8px 16px;padding:10px 12px;background:#fef2f2;border:1px solid #fecaca;border-radius:8px;font-size:13px;color:#ef4444;font-weight:600">';
                            html += '<span class="dashicons dashicons-warning" style="font-size:16px;width:16px;height:16px;margin-right:6px;vertical-align:middle"></span>';
                            html += __('Service overdue', 'vollstart-repair-desk') + ' — ' + esc(d.next_service_date) + ' (' + Math.abs(dDiff) + ' ' + __('days', 'vollstart-repair-desk') + ')';
                            html += '<button class="rd-dismiss-maintenance" data-product-id="' + d.id + '" style="float:right;background:none;border:1px solid #fecaca;border-radius:4px;padding:2px 8px;cursor:pointer;font-size:11px;color:#ef4444">' + __('Dismiss', 'vollstart-repair-desk') + '</button>';
                            html += '</div>';
                        } else {
                            html += '<div class="rd-status-row"><span class="rd-status-label">' + __('Next Service', 'vollstart-repair-desk') + '</span><span style="color:' + (dDiff <= 30 ? '#f59e0b' : '#64748b') + '">' + esc(d.next_service_date) + '</span></div>';
                        }
                    }
                    // Files (images + documents)
                    if (d.files && d.files.length > 0) {
                        html += '<div style="padding:8px 16px">' + renderPublicFiles(d.files) + '</div>';
                    }
                    // Repair history per device
                    if (d.repairs && d.repairs.length > 0) {
                        html += '<div style="padding:8px 16px;border-top:1px solid #f1f5f9">';
                        html += '<div style="font-size:11px;color:#64748b;text-transform:uppercase;margin-bottom:6px">' + __('Repair History', 'vollstart-repair-desk') + '</div>';
                        for (var ri = 0; ri < d.repairs.length; ri++) {
                            var rh = d.repairs[ri];
                            var rhTag = rh.status_url ? 'a href="' + esc(rh.status_url) + '" style="text-decoration:none;color:inherit"' : 'div';
                            html += '<' + rhTag + '>';
                            html += '<div style="display:flex;align-items:center;gap:8px;padding:4px 0">';
                            html += '<span style="font-size:13px;font-weight:600">' + esc(rh.repair_number) + '</span>';
                            html += '<span style="font-size:11px;padding:2px 8px;border-radius:999px;background:' + esc(rh.status_color) + '15;color:' + esc(rh.status_color) + '">' + esc(rh.status_label) + '</span>';
                            html += '<span style="font-size:12px;color:#94a3b8;margin-left:auto">' + formatDate(rh.created_at) + '</span>';
                            html += '</div>';
                            html += '</' + (rh.status_url ? 'a' : 'div') + '>';
                        }
                        html += '</div>';
                    }
                    html += '</div>';
                }
                html += '</div>';
            }

            // Business rating
            if (data.allow_business_rating !== undefined) {
                html += '<div class="rd-status-card" style="margin-top:16px">';
                html += '<div class="rd-status-header"><span class="rd-status-number">' + __('Rate us', 'vollstart-repair-desk') + '</span></div>';
                if (data.business_rating > 0 && !data.allow_business_rating) {
                    html += '<div style="text-align:center;padding:12px"><div style="font-size:28px">' + renderStars(data.business_rating) + '</div>';
                    if (data.business_rating_comment) html += '<p style="color:#64748b;font-size:13px;margin:4px 0 0">' + esc(data.business_rating_comment) + '</p>';
                    html += '<p style="color:#22c55e;font-size:13px;margin:8px 0 0">' + __('Thank you!', 'vollstart-repair-desk') + '</p></div>';
                } else {
                    html += '<div style="text-align:center;padding:12px">';
                    html += '<p style="color:#64748b;font-size:13px;margin-bottom:8px">' + __('How is your overall experience with us?', 'vollstart-repair-desk') + '</p>';
                    html += '<div id="rd-biz-star-select" style="font-size:32px;cursor:pointer;margin-bottom:8px">';
                    for (var bi = 1; bi <= 5; bi++) html += '<span class="rd-star" data-value="' + bi + '" style="color:' + (bi <= (data.business_rating || 0) ? '#f59e0b' : '#e2e8f0') + ';transition:color 0.15s">&#9733;</span>';
                    html += '</div>';
                    html += '<input type="hidden" id="rd-biz-rating-val" value="' + (data.business_rating || 0) + '">';
                    html += '<textarea id="rd-biz-rating-comment" rows="2" placeholder="' + __('Comment (optional)', 'vollstart-repair-desk') + '" style="width:100%;padding:8px;border:1px solid #e2e8f0;border-radius:8px;font-size:14px;box-sizing:border-box;resize:vertical;margin-bottom:8px">' + esc(data.business_rating_comment || '') + '</textarea>';
                    html += '<button id="rd-submit-biz-rating" class="rd-btn-lookup" style="width:100%">' + __('Submit', 'vollstart-repair-desk') + '</button>';
                    html += '</div>';
                }
                html += '</div>';
            }

            $('#rd-portal-content').html(html);
            maybeShowPwaBanner();
        });
    }

    // Show QR code overlay (large, scannable)
    $(document).on('click', '.rd-show-qr', function(e) {
        e.preventDefault();
        e.stopPropagation();
        var qrData = $(this).attr('data-qr');
        var number = $(this).attr('data-number');
        var url = cfg.siteUrl + qrData;
        // Try to build proper URL from statusPageUrl if available
        if (window.vollstartRdPublic) {
            // We're on the portal page, build from current location
            var base = window.location.href.replace(/\/my\/.*$/, '/');
            url = base + qrData;
        }
        var overlay = '<div class="rd-lightbox" style="flex-direction:column;gap:16px">';
        overlay += '<div style="background:#fff;padding:24px;border-radius:16px;text-align:center">';
        overlay += '<h3 style="margin:0 0 12px;font-size:20px;color:#1e293b">' + esc(number) + '</h3>';
        overlay += '<div id="rd-qr-overlay-code" style="background:#fff;padding:12px;border-radius:8px"></div>';
        overlay += '<p style="margin:12px 0 0;font-size:13px;color:#94a3b8">' + __('Scan to verify', 'vollstart-repair-desk') + '</p>';
        overlay += '</div></div>';
        $('body').append(overlay);
        if (typeof QRCode !== 'undefined') {
            new QRCode(document.getElementById('rd-qr-overlay-code'), {
                text: url,
                width: 250,
                height: 250,
                colorDark: '#1e293b',
                colorLight: '#ffffff',
                correctLevel: QRCode.CorrectLevel.M
            });
        }
    });

    // Portal: open repair detail inline (app flow)
    $(document).on('click', '.rd-portal-open', function() {
        var number = $(this).data('number');
        var code = $(this).data('code');
        var $btn = $(this);
        $btn.prop('disabled', true).text(__('Loading...', 'vollstart-repair-desk'));
        rdShowSpinner();
        $.post(cfg.ajaxurl, {
            action: 'vollstart_rd_public',
            sub_action: 'lookup',
            nonce: cfg.nonce,
            repair_number: number,
            access_code: code
        }, function(response) {
            if (!response.success) {
                $btn.prop('disabled', false).text(__('Open', 'vollstart-repair-desk'));
                rdHideSpinner();
                return;
            }
            // Hide portal list, show detail
            var $portal = $('#rd-portal-content');
            $portal.children().hide();
            var detailHtml = '<div id="rd-portal-detail">';
            detailHtml += '<button id="rd-portal-back" style="background:none;border:1px solid #e2e8f0;border-radius:8px;padding:8px 16px;cursor:pointer;font-size:14px;color:#64748b;margin-bottom:12px">&larr; ' + __('Back', 'vollstart-repair-desk') + '</button>';
            detailHtml += '<div id="rd-portal-detail-content"></div>';
            detailHtml += '</div>';
            $portal.append(detailHtml);
            // Render repair detail into portal
            var resultHtml = buildResultHtml(response.data);
            $('#rd-portal-detail-content').html(resultHtml);
            // Generate QR if present
            if (response.data.status_url && typeof QRCode !== 'undefined') {
                var qrEl = document.getElementById('rd-public-qr');
                if (qrEl) new QRCode(qrEl, { text: response.data.status_url, width: 180, height: 180, colorDark: '#1e293b', colorLight: '#ffffff', correctLevel: QRCode.CorrectLevel.M });
            }
            window.scrollTo(0, 0);
            rdHideSpinner();
        });
    });

    // Portal: back to list
    $(document).on('click', '#rd-portal-back', function() {
        $('#rd-portal-detail').remove();
        $('#rd-portal-content').children().show();
        // Reload portal to refresh unread counts
        var portal = window.vollstartRdPortal;
        if (portal && portal.token) loadPortal(portal.token);
    });

    // Dismiss maintenance warning
    $(document).on('click', '.rd-dismiss-maintenance', function() {
        var $btn = $(this);
        var productId = $btn.data('product-id');
        var portal = window.vollstartRdPortal;
        rdShowSpinner();
        $.post(cfg.ajaxurl, {
            action: 'vollstart_rd_public',
            sub_action: 'dismiss_maintenance',
            nonce: cfg.nonce,
            token: portal ? portal.token : '',
            product_id: productId
        }, function(res) {
            if (res.success) {
                $btn.closest('div[style*="background:#fef2f2"]').slideUp(200, function() { $(this).remove(); });
            }
            rdHideSpinner();
        });
    });

    // Portal refresh
    $(document).on('click', '#rd-portal-refresh', function() {
        var $btn = $(this);
        $btn.find('.dashicons').css('animation', 'spin 0.5s linear');
        var portal = window.vollstartRdPortal;
        if (portal && portal.token) loadPortal(portal.token);
    });

    // Portal tab switch
    $(document).on('click', '.rd-portal-tab', function() {
        var tab = $(this).data('tab');
        $('.rd-portal-tab').css({ 'color': '#94a3b8', 'border-bottom-color': 'transparent', 'font-weight': '500' });
        $(this).css({ 'color': '#f97316', 'border-bottom-color': '#f97316', 'font-weight': '600' });
        $('#rd-portal-repairs, #rd-portal-devices').hide();
        $('#rd-portal-' + tab).show();
    });

    // --- Public file gallery (reusable) ---

    function renderPublicFiles(files) {
        if (!files || !files.length) return '';
        var html = '<div class="rd-public-gallery">';
        for (var i = 0; i < files.length; i++) {
            var f = files[i];
            html += '<div class="rd-public-file">';
            if (f.is_image) {
                html += '<img src="' + esc(f.url) + '" alt="' + esc(f.name) + '" class="rd-lightbox-trigger" style="cursor:zoom-in">';
            } else {
                html += '<div class="rd-public-file-icon"><span style="font-size:36px">&#128196;</span></div>';
            }
            html += '<div class="rd-public-file-name">' + esc(f.name) + '</div>';
            html += '<div class="rd-public-file-btn-group">';
            html += '<a class="rd-public-file-btn" href="' + esc(f.url) + '" download="' + esc(f.name) + '"><span class="dashicons dashicons-download"></span></a>';
            html += '</div>';
            html += '</div>';
        }
        html += '</div>';
        return html;
    }

    // Lightbox
    $(document).on('click', '.rd-lightbox-trigger', function(e) {
        e.preventDefault();
        var src = $(this).attr('data-src') || $(this).attr('src');
        if (!src) return;
        $('body').append('<div class="rd-lightbox"><img src="' + src + '"></div>');
    });
    $(document).on('click', '.rd-lightbox', function() { $(this).remove(); });

    // --- Business Rating in Portal ---

    $(document).on('click', '#rd-biz-star-select .rd-star', function() {
        var val = $(this).data('value');
        $('#rd-biz-rating-val').val(val);
    });

    $(document).on('click', '#rd-submit-biz-rating', function() {
        var rating = parseInt($('#rd-biz-rating-val').val()) || 0;
        if (!rating) { alert(__('Please select a rating.', 'vollstart-repair-desk')); return; }
        var $btn = $(this);
        $btn.prop('disabled', true).text(__('Submitting...', 'vollstart-repair-desk'));
        rdShowSpinner();
        var portal = window.vollstartRdPortal;
        $.post(cfg.ajaxurl, {
            action: 'vollstart_rd_public',
            sub_action: 'submit_business_rating',
            nonce: cfg.nonce,
            token: portal ? portal.token : '',
            rating: rating,
            comment: $('#rd-biz-rating-comment').val()
        }, function(res) {
            if (res.success) {
                var $card = $btn.closest('.rd-status-card');
                var shtml = '<div class="rd-status-header"><span class="rd-status-number">' + __('Rate us', 'vollstart-repair-desk') + '</span></div>';
                shtml += '<div style="text-align:center;padding:12px"><div style="font-size:28px">' + renderStars(rating) + '</div>';
                shtml += '<p style="color:#22c55e;font-size:13px;margin:8px 0 0">' + esc(res.data.message) + '</p></div>';
                $card.html(shtml);
            } else {
                $btn.prop('disabled', false).text(__('Submit', 'vollstart-repair-desk'));
                alert(res.data.message || __('Error', 'vollstart-repair-desk'));
            }
            rdHideSpinner();
        });
    });

    // --- Status Page Rating ---

    $(document).on('click', '#rd-status-star-select .rd-star', function() {
        var val = $(this).data('value');
        $('#rd-status-rating-val').val(val);
    });

    $(document).on('click', '#rd-status-submit-rating', function() {
        var rating = parseInt($('#rd-status-rating-val').val()) || 0;
        if (!rating) { alert(__('Please select a rating.', 'vollstart-repair-desk')); return; }
        var $btn = $(this);
        $btn.prop('disabled', true).text(__('Submitting...', 'vollstart-repair-desk'));
        rdShowSpinner();
        $.post(cfg.ajaxurl, {
            action: 'vollstart_rd_public',
            sub_action: 'submit_status_rating',
            nonce: cfg.nonce,
            repair_number: $btn.data('number'),
            access_code: $btn.data('code'),
            rating: rating,
            comment: $('#rd-status-rating-comment').val()
        }, function(res) {
            if (res.success) {
                var $section = $btn.closest('.rd-status-section');
                var shtml = '<h3>' + __('Rate your repair', 'vollstart-repair-desk') + '</h3>';
                shtml += '<div style="text-align:center;padding:12px">';
                shtml += '<div style="font-size:28px">' + renderStars(rating) + '</div>';
                if ($('#rd-status-rating-comment').val()) shtml += '<p style="color:#64748b;font-size:13px;margin:4px 0 0">' + esc($('#rd-status-rating-comment').val()) + '</p>';
                shtml += '<p style="color:#22c55e;font-size:13px;margin:8px 0 0">' + esc(res.data.message) + '</p>';
                shtml += '</div>';
                $section.html(shtml);
            } else {
                $btn.prop('disabled', false).text(__('Submit Rating', 'vollstart-repair-desk'));
                alert(res.data.message || __('Error', 'vollstart-repair-desk'));
            }
            rdHideSpinner();
        });
    });

    // --- Rating Page ---

    $(document).ready(function() {
        var ratingData = window.vollstartRdRating;
        if (ratingData && ratingData.token) {
            renderRatingForm();
        }
    });

    function renderRatingForm() {
        var $app = $('#rd-rating-app');
        if (!$app.length) return;
        var repairNumber = $app.data('repair-number');
        var existing = parseInt($app.data('existing-rating')) || 0;
        var existingComment = $app.data('existing-comment') || '';
        var allowUpdate = $app.data('allow-update') === '1' || $app.data('allow-update') === 1;
        var alreadyRated = existing > 0;

        var html = '<div class="rd-status-card">';
        html += '<div class="rd-status-header"><span class="rd-status-number">' + esc(repairNumber) + '</span></div>';
        html += '<div style="padding:20px;text-align:center">';

        if (alreadyRated && !allowUpdate) {
            html += '<div style="font-size:32px;margin-bottom:8px">' + renderStars(existing) + '</div>';
            if (existingComment) html += '<p style="color:#64748b;font-size:14px">' + esc(existingComment) + '</p>';
            html += '<p style="color:#22c55e;font-weight:600">' + __('Thank you for your feedback!', 'vollstart-repair-desk') + '</p>';
        } else {
            html += '<p style="color:#64748b;margin-bottom:12px">' + __('How would you rate your experience?', 'vollstart-repair-desk') + '</p>';
            html += '<div id="rd-star-select" style="font-size:36px;cursor:pointer;margin-bottom:12px">';
            for (var i = 1; i <= 5; i++) {
                html += '<span class="rd-star" data-value="' + i + '" style="color:' + (i <= existing ? '#f59e0b' : '#e2e8f0') + ';transition:color 0.15s">&#9733;</span>';
            }
            html += '</div>';
            html += '<input type="hidden" id="rd-rating-value" value="' + existing + '">';
            html += '<textarea id="rd-rating-comment" rows="3" placeholder="' + __('Comment (optional)', 'vollstart-repair-desk') + '" style="width:100%;padding:10px;border:1px solid #e2e8f0;border-radius:8px;font-size:14px;box-sizing:border-box;resize:vertical;margin-bottom:12px">' + esc(existingComment) + '</textarea>';
            html += '<button id="rd-submit-rating" class="rd-btn-lookup" style="width:100%">' + __('Submit Rating', 'vollstart-repair-desk') + '</button>';
        }
        html += '</div></div>';
        $app.html(html);
    }

    function renderStars(rating) {
        var s = '';
        for (var i = 1; i <= 5; i++) {
            s += '<span style="color:' + (i <= rating ? '#f59e0b' : '#e2e8f0') + '">&#9733;</span>';
        }
        return s;
    }

    // Star hover + click
    $(document).on('mouseenter', '.rd-star', function() {
        var val = $(this).data('value');
        $(this).parent().find('.rd-star').each(function() {
            $(this).css('color', $(this).data('value') <= val ? '#f59e0b' : '#e2e8f0');
        });
    });
    $(document).on('mouseleave', '#rd-star-select', function() {
        var selected = parseInt($('#rd-rating-value').val()) || 0;
        $(this).find('.rd-star').each(function() {
            $(this).css('color', $(this).data('value') <= selected ? '#f59e0b' : '#e2e8f0');
        });
    });
    $(document).on('click', '.rd-star', function() {
        var val = $(this).data('value');
        $('#rd-rating-value').val(val);
    });

    // Submit rating
    $(document).on('click', '#rd-submit-rating', function() {
        var rating = parseInt($('#rd-rating-value').val()) || 0;
        if (rating < 1) { alert(__('Please select a rating.', 'vollstart-repair-desk')); return; }
        var $btn = $(this);
        $btn.prop('disabled', true).text(__('Submitting...', 'vollstart-repair-desk'));
        rdShowSpinner();
        $.post(cfg.ajaxurl, {
            action: 'vollstart_rd_public',
            sub_action: 'submit_rating',
            nonce: cfg.nonce,
            token: window.vollstartRdRating.token,
            rating: rating,
            comment: $('#rd-rating-comment').val()
        }, function(res) {
            if (res.success) {
                var html = '<div style="text-align:center;padding:40px 20px">';
                html += '<div style="font-size:48px;margin-bottom:12px">&#10003;</div>';
                html += '<div style="font-size:32px;margin-bottom:8px">' + renderStars(rating) + '</div>';
                html += '<p style="color:#22c55e;font-weight:600">' + esc(res.data.message) + '</p>';
                html += '</div>';
                $('#rd-rating-app').html(html);
            } else {
                $btn.prop('disabled', false).text(__('Submit Rating', 'vollstart-repair-desk'));
                alert(res.data.message || __('Error', 'vollstart-repair-desk'));
            }
            rdHideSpinner();
        });
    });

    // --- Helpers ---

    function esc(str) {
        if (str === null || str === undefined) return '';
        return String(str)
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#39;');
    }

    function formatDate(str) {
        if (!str) return '';
        var d = new Date(str.replace(' ', 'T'));
        if (isNaN(d.getTime())) return str;
        return d.toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' });
    }

})(jQuery);
