document.addEventListener('DOMContentLoaded', () => {

    // ── Loading animation (Lottie) ────────────────────────────────────────
    lottie.loadAnimation({
        container:  document.getElementById('lottie-loading'),
        renderer:   'svg',
        loop:       true,
        autoplay:   true,
        path:       'lottie-logo.json',
    });

    // ── Plan configuration ────────────────────────────────────────────────
    const UNLIMITED_COST = 299.99;

    const PLANS = {
        scale: {
            id: 'scale', label: 'Scale', legacy: false,
            unitLabel: 'Total Orders', unitLabelShort: 'Orders',
            baseFee: 39.99, baseUnits: 300, blockCost: 40.00, blockSize: 300, maxBill: 799.99,
        },
        convert: {
            id: 'convert', label: 'Convert', legacy: false,
            unitLabel: 'Total Orders', unitLabelShort: 'Orders',
            baseFee: 49.99, baseUnits: 300, blockCost: 50.00, blockSize: 300, maxBill: 999.99,
        },
        growth: {
            id: 'growth', label: 'Growth', legacy: true,
            unitLabel: 'Total Emails Sent', unitLabelShort: 'Emails',
            baseFee: 34.99, baseUnits: 300, blockCost: 35.00, blockSize: 300, maxBill: 699.99,
        },
        growth_referrals: {
            id: 'growth_referrals', label: 'Growth + Refs', legacy: true,
            unitLabel: 'Total Emails Sent', unitLabelShort: 'Emails',
            baseFee: 39.99, baseUnits: 300, blockCost: 40.00, blockSize: 300, maxBill: 699.99,
        },
        legacy_scale: {
            id: 'legacy_scale', label: 'Legacy Scale', legacy: true,
            unitLabel: 'Total Orders', unitLabelShort: 'Orders',
            baseFee: 34.99, baseUnits: 300, blockCost: 35.00, blockSize: 300, maxBill: 699.99,
        },
        enterprise_usage: {
            id: 'enterprise_usage', label: 'Enterprise Usage', legacy: true,
            unitLabel: 'Total Emails Sent', unitLabelShort: 'Emails',
            baseFee: 99.99, baseUnits: 2000, blockCost: 100.00, blockSize: 2000, maxBill: 499.99,
        },
    };

    const PLAN_ORDER = ['scale', 'convert', 'growth', 'growth_referrals', 'legacy_scale', 'enterprise_usage'];

    // ── Module-level state ────────────────────────────────────────────────
    let currentPlanId        = 'scale';
    let isDarkMode           = false;
    let isMuted              = false;
    let lastResult           = null;
    let lastBreakevenWarning = false; // tracks previous warning state to detect transitions

    let stateCache = {
        activePlan: 'scale',
        darkMode: false,
        planInputs: {
            scale:            { units: '0', baseDiscount: '0', usageDiscount: '0' },
            convert:          { units: '0', baseDiscount: '0', usageDiscount: '0' },
            growth:           { units: '0', baseDiscount: '0', usageDiscount: '0' },
            growth_referrals: { units: '0', baseDiscount: '0', usageDiscount: '0' },
            legacy_scale:     { units: '0', baseDiscount: '0', usageDiscount: '0' },
            enterprise_usage: { units: '0', baseDiscount: '0', usageDiscount: '0' },
        },
        muted: false,
        // tracks whether each plan's unlimited alert has already been played
        planBreakevenWarned: {
            scale: false, convert: false, growth: false,
            growth_referrals: false, legacy_scale: false, enterprise_usage: false,
        },
    };

    // ── DOM references ────────────────────────────────────────────────────
    const unitInput           = document.getElementById('unit-input');
    const unitInputLabel      = document.getElementById('unit-input-label');
    const baseDiscountInput   = document.getElementById('base-discount');
    const usageDiscountInput  = document.getElementById('usage-discount');

    const unitLabelInline     = document.getElementById('unit-label-inline');
    const unitsDisplay        = document.getElementById('units-display');
    const usageChargesCount   = document.getElementById('usage-charges-count');
    const baseFeeLabel        = document.getElementById('base-fee-label');
    const usageChargeLabel    = document.getElementById('usage-charge-label');
    const discountedBaseFeeEl = document.getElementById('discounted-base-fee');
    const baseFeeDiscountText = document.getElementById('base-fee-discount-text');
    const discountedBlockEl   = document.getElementById('discounted-charge-per-block');
    const usageDiscountText   = document.getElementById('usage-charge-discount-text');
    const usageCalculation    = document.getElementById('usage-calculation');
    const totalBillEl         = document.getElementById('total-bill');
    const capDisplay          = document.getElementById('cap-display');
    const breakevenIndicator  = document.getElementById('breakeven-indicator');
    const breakevenText       = document.getElementById('breakeven-text');
    const bottomGlow          = document.getElementById('bottom-glow');
    const darkModeCheckbox    = document.getElementById('dark-mode-checkbox');
    const resetBtn            = document.getElementById('reset-btn');
    const muteBtn             = document.getElementById('mute-btn');
    const planLogo            = document.getElementById('plan-logo');
    const cursorTip           = document.getElementById('cursor-tip');
    const loadingOverlay      = document.getElementById('loading-overlay');

    // Inject version number from manifest dynamically
    const versionEl = document.getElementById('ext-version');
    if (versionEl) versionEl.textContent = chrome.runtime.getManifest().version;
    const copyBtn             = document.getElementById('copy-explanation-btn');
    const copyBreakdownBtn    = document.getElementById('copy-breakdown-btn');

    // ── Sound system ──────────────────────────────────────────────────────
    const sndSelect   = new Audio('sounds/select.wav');
    const sndDisabled = new Audio('sounds/disabled.wav');
    const sndAlert    = new Audio('sounds/unlimited_alert.mp3');
    const sndType     = [
        new Audio('sounds/type_01.wav'),
        new Audio('sounds/type_02.wav'),
        new Audio('sounds/type_03.wav'),
        new Audio('sounds/type_04.wav'),
        new Audio('sounds/type_05.wav'),
    ];
    // ── Cursor-following tooltip ──────────────────────────────────────────
    function tipShow(e, text) {
        cursorTip.textContent = text;
        cursorTip.classList.add('visible');
        tipMove(e);
    }
    function tipMove(e) {
        cursorTip.style.left = e.clientX + 'px';
        cursorTip.style.top  = e.clientY + 'px';
    }
    function tipHide() {
        cursorTip.classList.remove('visible');
    }

    function playSelect()   { if (!isMuted) sndSelect.cloneNode().play().catch(() => {}); }
    function playDisabled() { if (!isMuted) sndDisabled.cloneNode().play().catch(() => {}); }
    function playType()     { if (!isMuted) sndType[Math.floor(Math.random() * sndType.length)].cloneNode().play().catch(() => {}); }
    function playAlert()    { if (!isMuted) sndAlert.cloneNode().play().catch(() => {}); }

    function applyMute(muted) {
        isMuted = muted;
        muteBtn.classList.toggle('is-muted', muted);
    }

    // ── Utility ───────────────────────────────────────────────────────────

    function clampDiscount(val) {
        const n = parseFloat(val);
        return Math.min(1, Math.max(0, isNaN(n) ? 0 : n / 100));
    }

    // ── Calculation ───────────────────────────────────────────────────────

    function calculateBreakeven(plan, discountedBase, discountedBlock) {
        if (discountedBlock === 0)            return Infinity;
        if (plan.maxBill <= UNLIMITED_COST)   return Infinity;
        if (discountedBase >= UNLIMITED_COST) return plan.baseUnits;
        const blocksNeeded = Math.ceil((UNLIMITED_COST - discountedBase) / discountedBlock);
        return plan.baseUnits + (blocksNeeded - 1) * plan.blockSize + 1;
    }

    function calculateBilling(units, plan) {
        const safeUnits   = Math.max(0, units);
        const baseDiscP   = clampDiscount(baseDiscountInput.value);
        const usageDiscP  = clampDiscount(usageDiscountInput.value);
        const discountedBase  = plan.baseFee   * (1 - baseDiscP);
        const discountedBlock = plan.blockCost * (1 - usageDiscP);

        const unitsAboveBase = safeUnits - plan.baseUnits;
        let usageBlocks      = 0;
        let totalUsageCharge = 0;
        if (unitsAboveBase > 0) {
            usageBlocks      = Math.ceil(unitsAboveBase / plan.blockSize);
            totalUsageCharge = usageBlocks * discountedBlock;
        }

        const rawBill   = discountedBase + totalUsageCharge;
        const totalBill = Math.min(rawBill, plan.maxBill);

        return {
            safeUnits, usageBlocks,
            discountedBase, discountedBlock,
            baseDiscP, usageDiscP,
            totalUsageCharge, totalBill,
            isCapped: rawBill >= plan.maxBill,
            breakevenUnits: calculateBreakeven(plan, discountedBase, discountedBlock),
        };
    }

    // ── Rendering ─────────────────────────────────────────────────────────

    /**
     * Updates a rate label element.
     * When a discount is active, prepends a coloured "DISCOUNTED" pill badge.
     * When no discount, shows a plain label.
     */
    function updateRateLabel(labelEl, hasDiscount, plainText) {
        if (hasDiscount) {
            labelEl.innerHTML =
                `<span class="disc-label">Discounted</span> ${plainText}:`;
        } else {
            labelEl.textContent = `${plainText}:`;
        }
    }

    function renderResults(result, plan) {
        const {
            safeUnits, usageBlocks,
            discountedBase, discountedBlock,
            baseDiscP, usageDiscP,
            totalUsageCharge, totalBill,
            breakevenUnits,
        } = result;

        // Summary line
        unitLabelInline.textContent   = plan.unitLabelShort;
        unitsDisplay.textContent      = safeUnits.toLocaleString();
        usageChargesCount.textContent = usageBlocks;

        // Rate labels: show "DISCOUNTED" badge only when discount > 0
        updateRateLabel(baseFeeLabel,      baseDiscP  > 0, 'Base Fee');
        updateRateLabel(usageChargeLabel,  usageDiscP > 0, 'Usage Charge');

        // Rate values
        discountedBaseFeeEl.textContent = `$${discountedBase.toFixed(2)}`;
        baseFeeDiscountText.textContent = baseDiscP > 0
            ? `(${(baseDiscP * 100).toFixed(0)}% off)`
            : '';

        discountedBlockEl.textContent = `$${discountedBlock.toFixed(2)}`;
        usageDiscountText.textContent = usageDiscP > 0
            ? `(${(usageDiscP * 100).toFixed(0)}% off)`
            : '';

        // Calculation line
        usageCalculation.textContent =
            `${usageBlocks} block${usageBlocks !== 1 ? 's' : ''} × $${discountedBlock.toFixed(2)}` +
            ` = $${totalUsageCharge.toFixed(2)} + base $${discountedBase.toFixed(2)}`;

        // Total and cap
        totalBillEl.textContent = `$${totalBill.toFixed(2)}`;
        capDisplay.textContent  = `$${plan.maxBill.toFixed(2)}`;

        // Breakeven
        renderBreakevenIndicator(
            safeUnits, totalBill, breakevenUnits,
            plan.unitLabelShort.toLowerCase()
        );
    }

    function renderBreakevenIndicator(currentUnits, currentBill, breakevenUnits, unitLabel) {
        if (breakevenUnits === Infinity) {
            breakevenIndicator.style.display = 'none';
            lastBreakevenWarning = false;
            setBottomGlow(false);
            return;
        }
        if (currentUnits < breakevenUnits) {
            breakevenIndicator.className = 'breakeven-indicator breakeven-neutral';
            breakevenText.textContent =
                `Unlimited ($${UNLIMITED_COST.toFixed(2)}/mo) becomes cheaper at ` +
                `${breakevenUnits.toLocaleString()} ${unitLabel}`;
            lastBreakevenWarning = false;
            stateCache.planBreakevenWarned[currentPlanId] = false;
            setBottomGlow(false);
        } else {
            const savings = Math.max(0, currentBill - UNLIMITED_COST).toFixed(2);
            breakevenIndicator.className = 'breakeven-indicator breakeven-warning';
            breakevenText.textContent =
                `⚠️ Unlimited ($${UNLIMITED_COST.toFixed(2)}/mo) saves $${savings}/month`;
            if (!lastBreakevenWarning) playAlert(); // play only on transition into warning
            lastBreakevenWarning = true;
            stateCache.planBreakevenWarned[currentPlanId] = true;
            setBottomGlow(true);
        }
    }

    // ── Bottom glow: shows on warning, fades as indicator scrolls into view ──
    let glowActive = false;

    function setBottomGlow(active) {
        glowActive = active;
        if (!active) {
            bottomGlow.style.opacity = '0';
            return;
        }
        updateGlowFromScroll();
    }

    function updateGlowFromScroll() {
        if (!glowActive) return;
        const rect = breakevenIndicator.getBoundingClientRect();
        const winH  = window.innerHeight;
        // How many px of the indicator are inside the viewport from the bottom
        const visible = winH - rect.top;
        if (visible <= 0) {
            // Indicator fully below viewport
            bottomGlow.style.opacity = '1';
        } else if (visible >= rect.height) {
            // Indicator fully visible
            bottomGlow.style.opacity = '0';
        } else {
            // Partially visible — fade proportionally
            bottomGlow.style.opacity = String(1 - visible / rect.height);
        }
    }

    window.addEventListener('scroll', updateGlowFromScroll, { passive: true });

    // ── Copy explanation ──────────────────────────────────────────────────

    function buildExplanationText() {
        const plan      = PLANS[currentPlanId];
        const baseDiscP = clampDiscount(baseDiscountInput.value);
        const usageDiscP = clampDiscount(usageDiscountInput.value);

        if (baseDiscP === 0 && usageDiscP === 0) return null;

        const origBase     = plan.baseFee;
        const discBase     = origBase  * (1 - baseDiscP);
        const origUsage    = plan.blockCost;
        const discUsage    = origUsage * (1 - usageDiscP);
        const basePct      = (baseDiscP  * 100).toFixed(0);
        const usagePct     = (usageDiscP * 100).toFixed(0);

        if (baseDiscP > 0 && usageDiscP > 0) {
            if (baseDiscP === usageDiscP) {
                return `This would reduce your base fee from $${origBase.toFixed(2)} to $${discBase.toFixed(2)} ` +
                    `and the usage fees from $${origUsage.toFixed(2)} to $${discUsage.toFixed(2)} (${basePct}% off both).`;
            }
            return `This would reduce your base fee from $${origBase.toFixed(2)} to $${discBase.toFixed(2)} (${basePct}% off) ` +
                `and the usage fees from $${origUsage.toFixed(2)} to $${discUsage.toFixed(2)} (${usagePct}% off).`;
        }
        if (baseDiscP > 0) {
            return `This would reduce your base fee from $${origBase.toFixed(2)} to $${discBase.toFixed(2)} (${basePct}% off).`;
        }
        return `This would reduce your usage fees from $${origUsage.toFixed(2)} to $${discUsage.toFixed(2)} per block (${usagePct}% off).`;
    }

    function buildBreakdownText() {
        if (!lastResult) return null;
        const { usageBlocks, discountedBlock, totalUsageCharge, discountedBase, totalBill, baseDiscP, usageDiscP } = lastResult;
        const plan = PLANS[currentPlanId];
        const blockLabel = usageBlocks === 1 ? 'usage charge' : 'usage charges';

        const baseDiscLine  = baseDiscP  > 0 ? ` (${Math.round(baseDiscP  * 100)}% discount off $${plan.baseFee.toFixed(2)})` : '';
        const blockDiscLine = usageDiscP > 0 ? ` (${Math.round(usageDiscP * 100)}% discount off $${plan.blockCost.toFixed(2)})` : '';

        return `${usageBlocks} ${blockLabel} × $${discountedBlock.toFixed(2)}${blockDiscLine} = $${totalUsageCharge.toFixed(2)} + base charge of $${discountedBase.toFixed(2)}${baseDiscLine} = $${totalBill.toFixed(2)}`;
    }

    function updateCopyBtn() {
        const baseDiscP  = clampDiscount(baseDiscountInput.value);
        const usageDiscP = clampDiscount(usageDiscountInput.value);
        copyBtn.disabled = (baseDiscP === 0 && usageDiscP === 0);
    }

    // ── Theming ───────────────────────────────────────────────────────────

    function applyTheme(planId, dark) {
        document.body.classList.toggle('theme-convert', planId === 'convert');
        document.body.classList.toggle('dark', dark);
        // Same logo for all plans — only colors/theme change, never the logo
        darkModeCheckbox.checked = !dark;
    }

    // ── Tabs ──────────────────────────────────────────────────────────────

    function renderTabs(activePlanId) {
        document.querySelectorAll('.plan-tab').forEach(btn => {
            btn.classList.toggle('active', btn.dataset.plan === activePlanId);
            btn.setAttribute('aria-selected', btn.dataset.plan === activePlanId);
        });
    }

    // ── Plan switching ────────────────────────────────────────────────────

    function switchPlan(planId) {
        currentPlanId = planId;
        const plan   = PLANS[planId];
        const inputs = stateCache.planInputs[planId] || {};

        unitInput.value          = inputs.units         || '0';
        baseDiscountInput.value  = inputs.baseDiscount  || '0';
        usageDiscountInput.value = inputs.usageDiscount || '0';

        // Restore this plan's warned state so alert doesn't replay on reopen
        lastBreakevenWarning = stateCache.planBreakevenWarned[planId] || false;

        unitInputLabel.textContent = plan.unitLabel;
        applyTheme(planId, isDarkMode);
        renderTabs(planId);
        recalculate();
    }

    // ── Core recalculate ─────────────────────────────────────────────────

    function recalculate() {
        const plan   = PLANS[currentPlanId];
        const units  = parseInt(unitInput.value, 10) || 0;
        lastResult   = calculateBilling(units, plan);
        renderResults(lastResult, plan);
        updateCopyBtn();
    }

    // ── State persistence ─────────────────────────────────────────────────

    function saveState() {
        stateCache.activePlan = currentPlanId;
        stateCache.darkMode   = isDarkMode;
        stateCache.muted      = isMuted;
        stateCache.planInputs[currentPlanId] = {
            units:         unitInput.value,
            baseDiscount:  baseDiscountInput.value,
            usageDiscount: usageDiscountInput.value,
        };
        chrome.storage.local.set({ billingCalcState: stateCache });
    }

    function loadStateAndCalculate() {
        const startTime = Date.now();
        chrome.storage.session.get('hasSeenLoadingThisSession', (sessionStored) => {
        const isFirstThisSession = !sessionStored.hasSeenLoadingThisSession;
        chrome.storage.local.get('billingCalcState', (stored) => {
            const isFirstEver = isFirstThisSession;

            if (stored.billingCalcState) {
                const loaded = stored.billingCalcState;
                stateCache.activePlan = loaded.activePlan || 'scale';
                stateCache.darkMode   = loaded.darkMode   || false;
                stateCache.muted      = loaded.muted      || false;
                if (loaded.planInputs) {
                    PLAN_ORDER.forEach(id => {
                        if (loaded.planInputs[id]) {
                            stateCache.planInputs[id] = loaded.planInputs[id];
                        }
                    });
                }
                if (loaded.planBreakevenWarned) {
                    PLAN_ORDER.forEach(id => {
                        if (loaded.planBreakevenWarned[id] !== undefined) {
                            stateCache.planBreakevenWarned[id] = loaded.planBreakevenWarned[id];
                        }
                    });
                }
            }
            currentPlanId = stateCache.activePlan;
            isDarkMode    = stateCache.darkMode;
            applyMute(stateCache.muted || false);
            // Suppress the toggle transition during initial state restore
            // so the button snaps to the saved position instead of animating
            darkModeCheckbox.closest('.switch').classList.add('no-transition');
            switchPlan(currentPlanId);
            requestAnimationFrame(() => {
                darkModeCheckbox.closest('.switch').classList.remove('no-transition');
            });

            if (isFirstEver) {
                // First time ever — show the animation for 1 second, then mark as seen
                const elapsed = Date.now() - startTime;
                const delay   = Math.max(0, 1000 - elapsed);
                setTimeout(() => {
                    loadingOverlay.classList.add('hidden');
                    chrome.storage.session.set({ hasSeenLoadingThisSession: true });
                }, delay);
            } else {
                // All subsequent opens this session — dismiss immediately
                loadingOverlay.classList.add('hidden');
            }
        });
        }); // end session.get
    }

    // ── Reset ─────────────────────────────────────────────────────────────

    function resetAllFields() {
        PLAN_ORDER.forEach(id => {
            stateCache.planInputs[id]          = { units: '0', baseDiscount: '0', usageDiscount: '0' };
            stateCache.planBreakevenWarned[id] = false;
        });
        lastBreakevenWarning = false;
        unitInput.value          = '0';
        baseDiscountInput.value  = '0';
        usageDiscountInput.value = '0';
        saveState();
        recalculate();
        playSelect();
    }

    // ── Event listeners ───────────────────────────────────────────────────

    function attachEventListeners() {
        // Tab clicks
        document.querySelectorAll('.plan-tab').forEach(btn => {
            btn.addEventListener('click', () => {
                playSelect();
                saveState();
                switchPlan(btn.dataset.plan);
                saveState();
            });
        });

        // Input / discount changes + typing sounds + zero placeholder behaviour
        [unitInput, baseDiscountInput, usageDiscountInput].forEach(el => {
            el.addEventListener('focus', () => {
                if (el.value === '0') el.value = '';
            });
            el.addEventListener('blur', () => {
                if (el.value === '' || el.value === '-') {
                    el.value = '0';
                    saveState();
                    recalculate();
                }
            });
            el.addEventListener('input', () => {
                saveState();
                recalculate();
            });
            el.addEventListener('keydown', (e) => {
                // Block chars that number inputs allow but we don't want: e, E, +
                if (['e', 'E', '+'].includes(e.key)) {
                    e.preventDefault();
                    playDisabled();
                    return;
                }
                if (e.key === 'Backspace' || e.key === 'Delete') {
                    playType();
                } else if (e.key.length === 1) {
                    const isValid = /^[0-9.\-]$/.test(e.key) || e.ctrlKey || e.metaKey;
                    isValid ? playType() : playDisabled();
                }
            });
        });

        // Copy breakdown button
        copyBreakdownBtn.addEventListener('click', () => {
            const text = buildBreakdownText();
            if (!text) return;
            playSelect();

            function showCopiedBreakdown() {
                copyBreakdownBtn.innerHTML = '✓ Copied!';
                copyBreakdownBtn.classList.add('copied');
                setTimeout(() => {
                    copyBreakdownBtn.innerHTML = '<span class="btn-icon"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="100%" height="100%"><defs><style>.cls-1,.cls-2{fill:none;stroke-miterlimit:10;stroke-width:2px;stroke:currentColor;}.cls-2{stroke-linecap:square;}</style></defs><g><line class="cls-1" x1="10" y1="7.5" x2="18" y2="7.5"/><line class="cls-1" x1="10" y1="11.5" x2="18" y2="11.5"/><line class="cls-1" x1="10" y1="15.5" x2="18" y2="15.5"/><line class="cls-1" x1="8" y1="7.5" x2="6" y2="7.5"/><line class="cls-1" x1="8" y1="11.5" x2="6" y2="11.5"/><line class="cls-1" x1="8" y1="15.5" x2="6" y2="15.5"/><polygon class="cls-2" points="4 22.5 6.66 20.5 9.33 22.5 11.99 20.5 14.66 22.5 17.33 20.5 20 22.5 21 21.5 21 1.5 3 1.5 3 21.5 4 22.5"/></g></svg></span>Copy Breakdown';
                    copyBreakdownBtn.classList.remove('copied');
                }, 2000);
            }

            if (navigator.clipboard && navigator.clipboard.writeText) {
                navigator.clipboard.writeText(text).then(showCopiedBreakdown).catch(() => {
                    const ta = document.createElement('textarea');
                    ta.value = text;
                    ta.style.cssText = 'position:fixed;opacity:0;top:0;left:0;pointer-events:none';
                    document.body.appendChild(ta);
                    ta.focus(); ta.select();
                    try { document.execCommand('copy'); showCopiedBreakdown(); } catch (e) {}
                    document.body.removeChild(ta);
                });
            } else {
                const ta = document.createElement('textarea');
                ta.value = text;
                ta.style.cssText = 'position:fixed;opacity:0;top:0;left:0;pointer-events:none';
                document.body.appendChild(ta);
                ta.focus(); ta.select();
                try { document.execCommand('copy'); showCopiedBreakdown(); } catch (e) {}
                document.body.removeChild(ta);
            }
        });

        // Copy explanation button
        copyBtn.addEventListener('click', () => {
            const text = buildExplanationText();
            if (!text) return;
            playSelect();

            function showCopied() {
                copyBtn.innerHTML = '✓ Copied!';
                copyBtn.classList.add('copied');
                setTimeout(() => {
                    copyBtn.innerHTML = '<span class="btn-icon"><svg width="100%" height="100%" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" clip-rule="evenodd" d="M6 2C4.34315 2 3 3.34315 3 5V21C3 21.3844 3.22035 21.7348 3.56681 21.9013C3.91328 22.0678 4.32453 22.021 4.6247 21.7809L6.55371 20.2377L8.9453 21.8321C9.30764 22.0736 9.78464 22.0529 10.1247 21.7809L12 20.2806L13.8753 21.7809C14.2154 22.0529 14.6924 22.0736 15.0547 21.8321L17.4463 20.2377L19.3753 21.7809C19.6755 22.021 20.0867 22.0678 20.4332 21.9013C20.7797 21.7348 21 21.3844 21 21V5C21 3.34315 19.6569 2 18 2H6ZM10 7C9.44772 7 9 7.44772 9 8C9 8.55228 9.44772 9 10 9H10.01C10.5623 9 11.01 8.55228 11.01 8C11.01 7.44772 10.5623 7 10.01 7H10ZM14.7071 7.29289C14.3166 6.90237 13.6834 6.90237 13.2929 7.29289L9.29289 11.2929C8.90237 11.6834 8.90237 12.3166 9.29289 12.7071C9.68342 13.0976 10.3166 13.0976 10.7071 12.7071L14.7071 8.70711C15.0976 8.31658 15.0976 7.68342 14.7071 7.29289ZM15.01 12C15.01 11.4477 14.5623 11 14.01 11H14C13.4477 11 13 11.4477 13 12C13 12.5523 13.4477 13 14 13H14.01C14.5623 13 15.01 12.5523 15.01 12Z" fill="currentColor"/></svg></span>Copy Discount Explanation';
                    copyBtn.classList.remove('copied');
                }, 2000);
            }

            function fallbackCopy() {
                const ta = document.createElement('textarea');
                ta.value = text;
                ta.style.cssText = 'position:fixed;opacity:0;top:0;left:0;pointer-events:none';
                document.body.appendChild(ta);
                ta.focus();
                ta.select();
                try { document.execCommand('copy'); showCopied(); } catch (e) {}
                document.body.removeChild(ta);
            }

            if (navigator.clipboard && navigator.clipboard.writeText) {
                navigator.clipboard.writeText(text).then(showCopied).catch(fallbackCopy);
            } else {
                fallbackCopy();
            }
        });

        // Logo — hover tooltip + click to copy pricing link
        planLogo.addEventListener('mousemove', (e) => tipShow(e, 'Click to copy a link to the pricing page'));
        planLogo.addEventListener('mouseleave', tipHide);
        planLogo.addEventListener('click', () => {
            const url = 'https://loox.app/pricing';
            const copy = (text) => {
                if (navigator.clipboard?.writeText) {
                    navigator.clipboard.writeText(text).catch(() => {});
                } else {
                    const ta = Object.assign(document.createElement('textarea'),
                        { value: text, style: 'position:fixed;opacity:0' });
                    document.body.appendChild(ta);
                    ta.select(); document.execCommand('copy');
                    document.body.removeChild(ta);
                }
            };
            copy(url);
            playSelect();
            tipShow({ clientX: event.clientX, clientY: event.clientY }, '✓ Link copied!');
            setTimeout(tipHide, 1500);
        });

        // Disabled explanation button — cursor-following tooltip
        copyBtn.addEventListener('mousemove', (e) => {
            if (copyBtn.disabled) tipShow(e, 'Enter a discount first');
        });
        copyBtn.addEventListener('mouseleave', tipHide);
        copyBtn.addEventListener('mouseenter', (e) => {
            if (copyBtn.disabled) tipShow(e, 'Enter a discount first');
        });

        // Reset button — spring spin on click, resets all plans
        resetBtn.addEventListener('click', () => {
            resetBtn.classList.add('spinning');
            resetBtn.addEventListener('animationend', () => {
                resetBtn.classList.remove('spinning');
            }, { once: true });
            resetAllFields();
        });

        // Mute toggle
        muteBtn.addEventListener('click', () => {
            applyMute(!isMuted);
            saveState();
        });

        // Dark mode toggle
        // Checkbox checked = light/day; unchecked = dark/night
        darkModeCheckbox.addEventListener('change', () => {
            isDarkMode = !darkModeCheckbox.checked;
            applyTheme(currentPlanId, isDarkMode);
            saveState();
        });
    }

    // ── Bootstrap ─────────────────────────────────────────────────────────
    attachEventListeners();
    loadStateAndCalculate();
});
