/**
 * ITR POS — optional "install on desktop" card (PWA).
 * Compact bottom-left card: stays clear of ITR Assistant (bottom-right).
 * No modals unless user taps Install / Help.
 * Dismiss (×) is remembered; completing/cancelling the browser install flow is not,
 * so the card can appear again after the installed app is removed.
 */
(function () {
    'use strict';

    /** v2: only set when user closes with × — not after install (so uninstall + browser shows prompt again). */
    var DISMISS_KEY = 'itrpos_pwa_install_dismiss_v2';
    var BAR_ID = 'itrpos-pwa-install-bar';
    var BODY_CLASS = 'itrpos-pwa-install-bar-visible';

    function isStandalone() {
        try {
            if (window.matchMedia && window.matchMedia('(display-mode: standalone)').matches) {
                return true;
            }
        } catch (e) {}
        if (window.navigator.standalone === true) {
            return true;
        }
        return false;
    }

    function inIframe() {
        try {
            return window.self !== window.top;
        } catch (e) {
            return true;
        }
    }

    function iframeQuery() {
        return /[?&]iframe=1(?:&|$)/.test(window.location.search || '');
    }

    function dismissed() {
        try {
            return localStorage.getItem(DISMISS_KEY) === '1';
        } catch (e) {
            return false;
        }
    }

    function shouldNeverShow() {
        if (isStandalone()) return true;
        if (inIframe() || iframeQuery()) return true;
        if (dismissed()) return true;
        return false;
    }

    var deferredPrompt = null;

    function removeBar() {
        var el = document.getElementById(BAR_ID);
        if (el && el.parentNode) {
            el.parentNode.removeChild(el);
        }
        document.body.classList.remove(BODY_CLASS);
    }

    /** Hide card only — does not block future prompts (e.g. after user uninstalls the installed PWA). */
    function hideInstallCard() {
        removeBar();
        deferredPrompt = null;
    }

    /** User chose × — do not show this card again until site data is cleared (or key removed). */
    function dismissRemembered() {
        try {
            localStorage.setItem(DISMISS_KEY, '1');
        } catch (e) {}
        hideInstallCard();
    }

    function showHelp() {
        var msg =
            'Chrome / Edge: Look for the install icon in the address bar, or open the menu (⋮) → "Install ITR POS" / "Apps" → "Install this site as an app".\n\n' +
            'Safari (iPhone/iPad): Tap Share, then "Add to Home Screen".';
        if (typeof Swal !== 'undefined' && Swal.fire) {
            Swal.fire({
                title: 'Install ITR POS',
                text: msg,
                icon: 'info',
                confirmButtonText: 'OK',
                width: 520
            });
        } else {
            window.alert(msg);
        }
    }

    function ensureStyles() {
        if (document.getElementById('itrpos-pwa-install-styles')) return;
        var st = document.createElement('style');
        st.id = 'itrpos-pwa-install-styles';
        st.textContent = [
            '#itrpos-pwa-install-bar.itrpos-pwa-install-card {',
            '  position: fixed;',
            '  left: max(12px, env(safe-area-inset-left, 0px));',
            '  bottom: max(16px, env(safe-area-inset-bottom, 0px));',
            '  right: auto; top: auto;',
            '  width: min(360px, calc(100vw - 200px));',
            '  max-width: calc(100vw - 200px);',
            '  z-index: 1040;',
            '  box-sizing: border-box;',
            '  border-radius: 14px;',
            '  background: linear-gradient(145deg, #ffffff 0%, #f8fafc 100%);',
            '  border: 1px solid rgba(15, 23, 42, 0.12);',
            '  box-shadow: 0 12px 40px rgba(15, 23, 42, 0.18), 0 2px 8px rgba(15, 23, 42, 0.06);',
            '  overflow: hidden;',
            '  font-family: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;',
            '}',
            'body[data-pos-mode] #itrpos-pwa-install-bar.itrpos-pwa-install-card {',
            '  bottom: max(12px, env(safe-area-inset-bottom, 0px));',
            '  width: min(320px, calc(100vw - 24px));',
            '  max-width: calc(100vw - 24px);',
            '}',
            '@media (max-width: 520px) {',
            '  #itrpos-pwa-install-bar.itrpos-pwa-install-card {',
            '    width: min(340px, calc(100vw - 24px));',
            '    max-width: calc(100vw - 24px);',
            '  }',
            '}',
            '.itrpos-pwa-install-card__head {',
            '  display: flex; align-items: center; justify-content: space-between; gap: 8px;',
            '  padding: 10px 12px 8px;',
            '  background: linear-gradient(90deg, #0f172a 0%, #1e3a5f 100%);',
            '  color: #f1f5f9;',
            '}',
            '.itrpos-pwa-install-card__title { font-size: 13px; font-weight: 700; letter-spacing: 0.02em; }',
            '.itrpos-pwa-install-card__close {',
            '  border: none; background: rgba(255,255,255,0.12); color: #fff;',
            '  width: 28px; height: 28px; border-radius: 8px; cursor: pointer;',
            '  font-size: 18px; line-height: 1; display: flex; align-items: center; justify-content: center;',
            '  padding: 0; flex-shrink: 0;',
            '}',
            '.itrpos-pwa-install-card__close:hover { background: rgba(255,255,255,0.22); }',
            '.itrpos-pwa-install-card__body { padding: 10px 12px 4px; font-size: 12px; line-height: 1.45; color: #334155; }',
            '.itrpos-pwa-install-card__body strong { color: #0f172a; }',
            '.itrpos-pwa-install-card__foot {',
            '  display: flex; align-items: center; justify-content: flex-end; flex-wrap: wrap; gap: 8px;',
            '  padding: 8px 12px 12px;',
            '}',
            '.itrpos-pwa-install-card__foot .btn-install-primary {',
            '  font-weight: 600; font-size: 12px; padding: 6px 14px; border-radius: 8px;',
            '  border: none; cursor: pointer;',
            '  background: linear-gradient(135deg, #2563eb 0%, #1d4ed8 100%);',
            '  color: #fff; box-shadow: 0 2px 8px rgba(37, 99, 235, 0.35);',
            '}',
            '.itrpos-pwa-install-card__foot .btn-install-primary:disabled {',
            '  opacity: 0.55; cursor: not-allowed; box-shadow: none;',
            '}',
            '.itrpos-pwa-install-card__foot .btn-install-secondary {',
            '  font-size: 12px; padding: 6px 12px; border-radius: 8px;',
            '  border: 1px solid #cbd5e1; background: #fff; color: #475569; cursor: pointer;',
            '}',
            '.itrpos-pwa-install-card__foot .btn-install-secondary:hover { background: #f1f5f9; }'
        ].join('\n');
        document.head.appendChild(st);
    }

    function setInstallEnabled(enabled) {
        var bar = document.getElementById(BAR_ID);
        if (!bar) return;
        var btn = bar.querySelector('.btn-install-primary');
        if (btn) {
            btn.disabled = !enabled;
            btn.title = enabled ? '' : 'Use your browser menu to install, or tap “How to install” for steps.';
        }
    }

    function buildBar() {
        if (document.getElementById(BAR_ID)) return;

        ensureStyles();

        var bar = document.createElement('div');
        bar.id = BAR_ID;
        bar.className = 'itrpos-pwa-install-card';
        bar.setAttribute('role', 'dialog');
        bar.setAttribute('aria-label', 'Install ITR POS');

        var head = document.createElement('div');
        head.className = 'itrpos-pwa-install-card__head';
        var title = document.createElement('div');
        title.className = 'itrpos-pwa-install-card__title';
        title.textContent = 'Install on this device';
        var btnClose = document.createElement('button');
        btnClose.type = 'button';
        btnClose.className = 'itrpos-pwa-install-card__close';
        btnClose.innerHTML = '&times;';
        btnClose.title = 'Dismiss';
        btnClose.setAttribute('aria-label', 'Dismiss');
        head.appendChild(title);
        head.appendChild(btnClose);

        var body = document.createElement('div');
        body.className = 'itrpos-pwa-install-card__body';
        body.innerHTML =
            '<strong>ITR POS</strong> can be installed as an app for quicker access from your desktop or taskbar.<br>' +
            '<span style="color:#64748b">Opens in its own window, like a lightweight application.</span>';

        var foot = document.createElement('div');
        foot.className = 'itrpos-pwa-install-card__foot';

        var btnHelp = document.createElement('button');
        btnHelp.type = 'button';
        btnHelp.className = 'btn-install-secondary';
        btnHelp.textContent = 'How to install';
        btnHelp.setAttribute('aria-label', 'How to install');

        var btnInstall = document.createElement('button');
        btnInstall.type = 'button';
        btnInstall.className = 'btn-install-primary';
        btnInstall.textContent = 'Install';
        btnInstall.disabled = !deferredPrompt;
        btnInstall.setAttribute('aria-label', 'Install ITR POS');

        foot.appendChild(btnHelp);
        foot.appendChild(btnInstall);

        btnInstall.addEventListener('click', function () {
            if (!deferredPrompt) {
                showHelp();
                return;
            }
            deferredPrompt.prompt();
            deferredPrompt.userChoice.then(function () {
                deferredPrompt = null;
                hideInstallCard();
            }).catch(function () {
                deferredPrompt = null;
            });
        });

        btnHelp.addEventListener('click', function (e) {
            e.preventDefault();
            showHelp();
        });

        btnClose.addEventListener('click', function (e) {
            e.preventDefault();
            dismissRemembered();
        });

        bar.appendChild(head);
        bar.appendChild(body);
        bar.appendChild(foot);
        document.body.appendChild(bar);
        document.body.classList.add(BODY_CLASS);
        setInstallEnabled(!!deferredPrompt);
    }

    window.addEventListener('beforeinstallprompt', function (e) {
        if (shouldNeverShow()) return;
        e.preventDefault();
        deferredPrompt = e;
        if (document.getElementById(BAR_ID)) {
            setInstallEnabled(true);
            return;
        }
        buildBar();
        setInstallEnabled(true);
    });

    window.addEventListener('load', function () {
        if (shouldNeverShow()) return;
        if (!window.isSecureContext && location.hostname !== 'localhost' && location.hostname !== '127.0.0.1') {
            return;
        }
        window.setTimeout(function () {
            if (shouldNeverShow()) return;
            if (document.getElementById(BAR_ID)) return;
            if (deferredPrompt) return;
            buildBar();
            setInstallEnabled(false);
        }, 6000);
    });
})();
