<?xml version="1.0" encoding="utf-8"?>
<odoo>
    <!-- 1. Global Order Total Display -->
    <template id="chennora_total_uber_display" inherit_id="website_sale.total" name="Chennora Total Uber Display">
        <!-- Hide the original Odoo delivery row that appears ABOVE subtotal safely -->
        <xpath expr="//tr[@id='order_delivery']" position="attributes">
            <attribute name="style">display: none !important;</attribute>
            <attribute name="class" add="d-none" separator=" "/>
        </xpath>

        <!-- Use a unified filter for all delivery-related lines -->
        <xpath expr="//tr[@id='order_total_untaxed']" position="before">
            <t t-set="all_delivery_lines" t-value="website_sale_order.order_line.filtered(lambda l: l.is_delivery or 'Uber' in (l.product_id.name or '') or 'Delivery' in (l.product_id.name or ''))"/>
            <t t-set="all_delivery_amount" t-value="sum(all_delivery_lines.mapped('price_subtotal'))"/>
        </xpath>

        <!-- Fix Subtotal value safely to exclude delivery fee, while keeping classes for JS -->
        <xpath expr="//tr[@id='order_total_untaxed']//td[not(hasclass('text-start'))]//span" position="replace">
            <span class="monetary_field" style="white-space: nowrap;"
                  t-esc="website_sale_order.amount_untaxed - all_delivery_amount"
                  t-options='{"widget": "monetary", "display_currency": website_sale_order.currency_id}'/>
        </xpath>

        <xpath expr="//tr[@id='order_total_untaxed']" position="after">
            <tr t-if="all_delivery_lines" id="uber_delivery_row">
                <td class="border-0 pb-2 ps-0 pt-0 text-start text-muted" colspan="2">Delivery Fee</td>
                <td class="text-end border-0 pb-2 pe-0 pt-0">
                    <span t-esc="all_delivery_amount" t-options='{"widget": "monetary", "display_currency": website_sale_order.currency_id}' class="monetary_field"/>
                </td>
            </tr>
        </xpath>
    </template>

    <!-- Force enable Pay Now button on payment page if it's disabled by Odoo's shipping logic -->
    <template id="chennora_force_pay_button" inherit_id="website_sale.payment" name="Chennora Force Pay Button">
        <xpath expr="//div[@id='payment_method']" position="inside">
            <script type="text/javascript">
                (function() {
                    function enablePayButton() {
                        const payBtn = document.querySelector('#o_payment_form_button, .btn-primary[type="submit"]');
                        if (payBtn &amp;&amp; payBtn.disabled) {
                            console.log("Chennora: Force enabling payment button");
                            payBtn.disabled = false;
                        }
                    }
                    setInterval(enablePayButton, 1000); // Check every second as Odoo JS might toggle it
                })();
            </script>
        </xpath>
    </template>

    <!-- 2. Hide Uber fee from cart summary -->
    <template id="chennora_cart_summary_uber_hide" inherit_id="website_sale.checkout_layout" name="Chennora Cart Summary Uber Hide">
        <xpath expr="//table[@id='cart_products']//tr" position="attributes">
            <attribute name="t-if">line.product_id.name != 'Uber Delivery Fee'</attribute>
        </xpath>
    </template>

    <!-- 3. MAIN FORM: Optimized Pickup/Delivery Layout -->
    <template id="chennora_address_unified" inherit_id="website_sale.address" name="Chennora Address Unified" priority="99">
        
        <!-- Hide 'Billing address' title -->
        <xpath expr="//div[contains(@class, 'oe_cart')]//*[self::h2 or self::h3][1]" position="attributes">
            <attribute name="class" add="d-none" separator=" "/>
        </xpath>

        <!-- Hide yellow 'Be aware' box -->
        <xpath expr="//div[hasclass('alert-warning')][contains(., 'billing and shipping')]" position="attributes">
            <attribute name="class" add="d-none" separator=" "/>
            <attribute name="style">display: none !important;</attribute>
        </xpath>

        <!-- Hide 'Company Name' and 'VAT' fields using robust label selectors -->
        <xpath expr="//div[label[@for='company_name']]" position="attributes">
            <attribute name="class" add="d-none" separator=" "/>
            <attribute name="style">display: none !important;</attribute>
        </xpath>
        <xpath expr="//div[label[@for='vat']]" position="attributes">
            <attribute name="class" add="d-none" separator=" "/>
            <attribute name="style">display: none !important;</attribute>
        </xpath>

        <!-- Inject Selection Cards -->
        <xpath expr="//form" position="before">
            <style>
                .order-type-card { border: 2px solid #eee; border-radius: 12px; cursor: pointer; transition: all 0.3s ease; padding: 20px; text-align: center; height: 100%; position: relative; overflow: hidden; }
                .order-type-card.active { border-color: #00A67E; background-color: #f0fffb; box-shadow: 0 4px 15px rgba(0,166,126,0.1); }
                .order-type-card i { font-size: 2rem; margin-bottom: 10px; color: #666; }
                .order-type-card.active i { color: #00A67E; }
                .order-type-card h5 { margin-bottom: 5px; font-weight: bold; }
                .order-type-card p { font-size: 0.85rem; color: #888; margin: 0; }
                .active-mark { display: none; position: absolute; top: 10px; right: 10px; color: #00A67E; }
                .order-type-card.active .active-mark { display: block; }
                .section-header { font-weight: bold; margin: 30px 0 15px 0; padding-bottom: 8px; border-bottom: 2px solid #f8f9fa; font-size: 1.1rem; }
                
                .animated { animation-duration: 0.5s; animation-fill-mode: both; }
                @keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }
                .fadeIn { animation-name: fadeIn; }
                #uber_message strong { display: block; margin-bottom: 4px; }
            </style>

            <div class="row mb-4 g-3 mt-1">
                <div class="col-6">
                    <div id="card_delivery" class="order-type-card active" onclick="setOrderType('delivery')">
                        <i class="active-mark fa fa-check-circle"></i>
                        <i class="fa fa-truck"></i>
                        <h5>Delivery</h5>
                        <p>Deliver to my address</p>
                    </div>
                </div>
                <div class="col-6">
                    <div id="card_pickup" class="order-type-card" onclick="setOrderType('pickup')">
                        <i class="active-mark fa fa-check-circle"></i>
                        <i class="fa fa-shopping-basket"></i>
                        <h5>Store Pickup</h5>
                        <p>Pick up at the restaurant</p>
                    </div>
                </div>
            </div>
            
            <input type="hidden" name="fulfilment_type" id="hidden_fulfilment_type" value="delivery"/>

            <div id="uber_message" class="alert d-none my-3" role="alert"></div>
            <div id="contact_info_header" class="section-header mt-4"><i class="fa fa-user me-2"></i>Contact Details</div>
        </xpath>

        <!-- Hide 'Ship to same address' section -->
        <xpath expr="//label[contains(., 'Ship to the same address')]/ancestor::div[1]" position="attributes">
            <attribute name="style">display: none !important;</attribute>
            <attribute name="class" add="d-none" separator=" "/>
        </xpath>

        <!-- Use JS for more reliable UI management -->
        <xpath expr="//form" position="after">
            <script type="text/javascript">
                (function() {
                    function initUnifiedForm() {
                        const hiddenType = document.getElementById('hidden_fulfilment_type');
                        const msgDiv = document.getElementById('uber_message');
                        const submitBtn = document.querySelector('button[type="submit"]') || document.querySelector('.btn-primary') || document.querySelector('.s_website_form_send');
                        let debounceTimer;

                        // Force Name, Email, and Phone to be required
                        ['name', 'email', 'phone'].forEach(fieldName => {
                            const input = document.querySelector(`form.checkout_autoformat [name="${fieldName}"]`);
                            if (input) input.setAttribute('required', 'required');
                        });

                        // 1. Add prominent red required icons to labels
                        document.querySelectorAll('form.checkout_autoformat .control-label, form.checkout_autoformat label').forEach(label => {
                            const inputId = label.getAttribute('for');
                            const input = inputId ? document.getElementById(inputId) : label.closest('.mb-3')?.querySelector('input, select');
                            if (input &amp;&amp; input.hasAttribute('required') &amp;&amp; !label.querySelector('.fa-asterisk')) {
                                label.innerHTML += ' <i class="fa fa-asterisk text-danger" style="font-size: 7px; vertical-align: top; margin-left: 2px;"></i>';
                            }
                        });

                        // 2. Clear error state on input change (Real-time update)
                        document.querySelectorAll('form.checkout_autoformat input, form.checkout_autoformat select').forEach(input => {
                            const handler = function() {
                                const val = this.value ? this.value.trim() : "";
                                // Check if the field is actually filled (0 is valid for select if it's not the placeholder)
                                const isFilled = val &amp;&amp; val !== "0" &amp;&amp; val !== "";
                                
                                if (isFilled) {
                                    this.classList.remove('is-invalid');
                                    this.style.borderColor = '';
                                    
                                    // Update the summary error list dynamically
                                    const form = this.closest('form');
                                    const errorDiv = document.getElementById('chennora_val_error');
                                    if (errorDiv) {
                                        const stillInvalid = form.querySelectorAll('.is-invalid');
                                        if (stillInvalid.length === 0) {
                                            errorDiv.style.display = 'none';
                                        } else {
                                            let missingNames = [];
                                            stillInvalid.forEach(inv => {
                                                const l = form.querySelector(`label[for="${inv.name}"]`) || inv.closest('.mb-3')?.querySelector('label');
                                                missingNames.push(l ? l.textContent.replace('*', '').trim() : inv.name);
                                            });
                                            errorDiv.innerHTML = `<strong>Missing Required Fields:</strong><br/>${missingNames.join(', ')}`;
                                        }
                                    }
                                }
                            };
                            input.addEventListener('input', handler);
                            input.addEventListener('change', handler);
                        });

                        // 3. Custom Validation on Submit
                        if (submitBtn) {
                            submitBtn.addEventListener('click', function(e) {
                                const form = document.querySelector('form.checkout_autoformat');
                                if (!form) return;
                                
                                // Reset errors before checking
                                let missingFields = [];
                                const requiredInputs = form.querySelectorAll('input[required]:not([type="hidden"]), select[required]');
                                
                                requiredInputs.forEach(input => {
                                    // Skip hidden fields (from pickup/delivery toggle or company hide)
                                    const container = input.closest('div[class*="col-"], .mb-3');
                                    if (container &amp;&amp; container.style.display === 'none') return;
                                    if (input.name === 'company_name' || input.name === 'vat') return;
                                    
                                    const val = input.value ? input.value.trim() : "";
                                    const isMissing = !val || val === "0" || val === "";
                                    
                                    if (isMissing) {
                                        const label = form.querySelector(`label[for="${input.name}"]`) || input.closest('.mb-3')?.querySelector('label');
                                        const fieldName = label ? label.textContent.replace('*', '').trim() : input.name;
                                        missingFields.push(fieldName);
                                        input.classList.add('is-invalid');
                                        input.style.borderColor = '#dc3545';
                                    } else {
                                        input.classList.remove('is-invalid');
                                        input.style.borderColor = '';
                                    }
                                });

                                if (missingFields.length > 0) {
                                    e.preventDefault();
                                    e.stopPropagation();
                                    
                                    let errorDiv = document.getElementById('chennora_val_error');
                                    if (!errorDiv) {
                                        errorDiv = document.createElement('div');
                                        errorDiv.id = 'chennora_val_error';
                                        errorDiv.className = 'alert alert-danger mt-3 animated fadeIn';
                                        form.insertBefore(errorDiv, form.firstChild);
                                    }
                                    errorDiv.style.display = 'block';
                                    errorDiv.innerHTML = `<strong>Missing Required Fields:</strong><br/>${missingFields.join(', ')}`;
                                    errorDiv.scrollIntoView({ behavior: 'smooth', block: 'center' });
                                }
                            });
                        }
                        
                        function getAddressContainers() {
                            const addressNames = ['street', 'street2', 'city', 'zip', 'country_id', 'state_id'];
                            let containers = [];
                            addressNames.forEach(name => {
                                const input = document.querySelector(`[name="${name}"]`);
                                if (input) {
                                    const container = input.closest('div[class*="col-"]') || input.closest('.mb-3') || input.closest('.mb-4');
                                    if (container) containers.push(container);
                                }
                            });
                            return [...new Set(containers)];
                        }

                        let addrHeader = document.getElementById('dynamic_address_header');
                        if (!addrHeader &amp;&amp; document.querySelector('[name="street"]')) {
                            addrHeader = document.createElement('div');
                            addrHeader.id = 'dynamic_address_header';
                            addrHeader.className = 'section-header';
                            addrHeader.innerHTML = '<i class="fa fa-map-marker me-2"></i>Delivery Address';
                            const streetInput = document.querySelector('[name="street"]');
                            const streetContainer = streetInput.closest('div[class*="col-"]') || streetInput.parentNode;
                            streetContainer.parentNode.insertBefore(addrHeader, streetContainer);
                        }

                        window.setOrderType = function(type) {
                            hiddenType.value = type;
                            document.getElementById('card_delivery').classList.toggle('active', type === 'delivery');
                            document.getElementById('card_pickup').classList.toggle('active', type === 'pickup');
                            
                            const containers = getAddressContainers();
                            if (type === 'pickup') {
                                containers.forEach(c => c.style.display = 'none');
                                if (addrHeader) addrHeader.style.display = 'none';
                                if (msgDiv) msgDiv.style.display = 'none';
                                // Remove required for pickup
                                containers.forEach(c => {
                                    c.querySelectorAll('input, select').forEach(i => i.removeAttribute('required'));
                                });
                            } else {
                                containers.forEach(c => c.style.display = '');
                                if (addrHeader) addrHeader.style.display = '';
                                if (msgDiv) msgDiv.style.display = '';
                                // Restore required
                                ['street', 'city', 'zip', 'country_id', 'state_id'].forEach(name => {
                                    const i = document.querySelector(`[name="${name}"]`);
                                    if (i) i.setAttribute('required', 'required');
                                });
                                checkUber();
                            }
                            
                            // SYNC with server immediately
                            fetch('/shop/update_service_mode', {
                                method: 'POST', headers: {'Content-Type': 'application/json'},
                                body: JSON.stringify({ params: { service_mode: type } })
                            });
                        };

                        function checkUber() {
                            clearTimeout(debounceTimer);
                            debounceTimer = setTimeout(() => {
                                if (hiddenType.value !== 'delivery') return;
                                const street = document.querySelector('input[name="street"]')?.value;
                                const zip = document.querySelector('input[name="zip"]')?.value;
                                
                                if (!street || !zip) {
                                    if (msgDiv) msgDiv.style.display = 'none';
                                    return;
                                }

                                if (msgDiv) {
                                    msgDiv.className = 'alert alert-info my-3';
                                    msgDiv.style.display = '';
                                    msgDiv.innerText = "Checking Uber coverage...";
                                }

                                fetch('/shop/uber/quote', {
                                    method: 'POST', headers: {'Content-Type': 'application/json'},
                                    body: JSON.stringify({ params: { address_data: {
                                        street: street,
                                        street2: document.querySelector('input[name="street2"]')?.value,
                                        city: document.querySelector('input[name="city"]')?.value,
                                        zip: zip,
                                        country: document.querySelector('select[name="country_id"] option:checked')?.text || 'Canada',
                                        state: document.querySelector('select[name="state_id"] option:checked')?.text
                                    } } })
                                }).then(r => r.json()).then(data => {
                                    msgDiv.classList.remove('fadeIn');
                                    void msgDiv.offsetWidth; // Trigger reflow for animation
                                    msgDiv.classList.add('fadeIn');

                                    if (data.result &amp;&amp; data.result.success) {
                                        msgDiv.className = 'alert alert-success my-3 animated fadeIn';
                                        msgDiv.style.display = '';
                                        msgDiv.innerHTML = `<div class="d-flex align-items-center">
                                            <i class="fa fa-check-circle me-3" style="font-size: 24px;"></i>
                                            <div>
                                                <strong>✓ Delivery Available!</strong><br/>
                                                Uber Delivery Fee: $${data.result.fee} (Distance Based)
                                            </div>
                                        </div>`;
                                        if (submitBtn) submitBtn.disabled = false;
                                    } else {
                                        msgDiv.className = 'alert alert-danger my-3 animated fadeIn';
                                        msgDiv.style.display = '';
                                        msgDiv.innerHTML = `<div class="d-flex align-items-center">
                                            <i class="fa fa-exclamation-triangle me-3" style="font-size: 24px;"></i>
                                            <div>
                                                <strong>✕ Uber Direct: Invalid Operation</strong><br/>
                                                ${data.result?.error || "This specific address is outside the Uber delivery radius."}
                                            </div>
                                        </div>`;
                                        if (submitBtn) submitBtn.disabled = true;
                                    }
                                }).catch(err => {
                                    console.error("Uber API Error:", err);
                                    msgDiv.className = 'alert alert-warning my-3';
                                    msgDiv.innerText = "Error connecting to Uber service.";
                                });
                            }, 500); // 500ms debounce
                        }

                        // Trigger on any address field change
                        const addressFields = 'input[name="street"], input[name="street2"], input[name="city"], input[name="zip"], select[name="country_id"], select[name="state_id"]';
                        const triggers = document.querySelectorAll(addressFields);
                        triggers.forEach(t => {
                            t.addEventListener('blur', checkUber);
                            t.addEventListener('change', checkUber);
                        });

                        setOrderType('delivery');
                    }
                    if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', initUnifiedForm); else initUnifiedForm();
                })();
            </script>
        </xpath>
    </template>
    <!-- 4. CHECKOUT INJECTION: Final Safe method for Odoo 17 Selection Page -->
    <template id="chennora_checkout_safe_overrides" inherit_id="website_sale.checkout" name="Chennora Checkout Safe Overrides">
        <xpath expr="." position="inside">
            <script type="text/javascript">
                (function() {
                    function applyCheckoutFixes() {
                        // 1. Rename Wizard Step 2 (Shipping -> Address)
                        const wizardSteps = document.querySelectorAll('.progress-wizard-step, .o_wizard_step, .breadcrumb-item');
                        wizardSteps.forEach(step => {
                            if (step.textContent.trim().toLowerCase().includes('shipping')) {
                                const target = step.querySelector('span, a') || step;
                                target.textContent = 'Address';
                            }
                        });

                        // 2. Find and remove the Shipping section
                        const allHeaders = [...document.querySelectorAll('h2, h3, h4, h5')];
                        const shippingHeader = allHeaders.find(h => h.textContent.trim().toLowerCase() === 'shipping');
                        if (shippingHeader) {
                            shippingHeader.style.display = 'none';
                            if (shippingHeader.nextElementSibling) shippingHeader.nextElementSibling.style.display = 'none';
                            const shippingCol = shippingHeader.closest('.col-lg-6');
                            if (shippingCol) shippingCol.style.display = 'none';
                        }

                        // 3. Force Billing section to be full width
                        const billingHeader = allHeaders.find(h => h.textContent.trim().toLowerCase() === 'billing');
                        if (billingHeader) {
                            const billingCol = billingHeader.closest('.col-lg-6');
                            if (billingCol) {
                                billingCol.classList.remove('col-lg-6');
                                billingCol.classList.add('col-lg-12', 'w-100');
                                billingCol.style.flex = '0 0 100%';
                                billingCol.style.maxWidth = '100%';
                            }
                        }

                        // 4. CHECK UBER FOR SELECTED CARD
                        const billingGrid = document.querySelector('#address_selection');
                        if (billingGrid) {
                            let msgBox = document.getElementById('uber_checkout_msg');
                            if (!msgBox) {
                                msgBox = document.createElement('div');
                                msgBox.id = 'uber_checkout_msg';
                                billingGrid.parentNode.insertBefore(msgBox, billingGrid);
                            }

                            function verifySelectedAddress() {
                                // Find selected address card info
                                const selectedCard = document.querySelector('input[name="partner_id"]:checked')?.closest('.card');
                                if (!selectedCard) return;

                                const addressText = selectedCard.querySelector('address')?.innerText || "";
                                const parts = addressText.split('\n').map(p => p.trim());
                                const street = parts[1] || "";
                                const zipMatch = addressText.match(/[A-Z][0-9][A-Z]\s?[0-9][A-Z][0-9]/);
                                const zip = zipMatch ? zipMatch[0] : "";
                                const city = parts[2] ? parts[2].split(' ')[0] : "";
                                
                                msgBox.className = 'alert alert-info my-3';
                                msgBox.innerHTML = "Verifying Uber coverage for this address...";
                                
                                fetch('/shop/uber/quote', {
                                    method: 'POST', headers: {'Content-Type': 'application/json'},
                                    body: JSON.stringify({ params: { address_data: {
                                        street: street,
                                        zip: zip,
                                        city: city,
                                    } } })
                                }).then(r => r.json()).then(data => {
                                    if (data.result &amp;&amp; data.result.success) {
                                        msgBox.className = 'alert alert-success my-3';
                                        msgBox.innerHTML = `<strong>✓ Uber Delivery Available!</strong> Fee: $${data.result.fee}`;
                                        document.querySelector('button[type="submit"]')?.removeAttribute('disabled');
                                        setTimeout(() => { window.location.reload(); }, 1200);
                                    } else {
                                        msgBox.className = 'alert alert-danger my-3';
                                        msgBox.innerHTML = `<strong>✕ Uber Direct: Invalid Operation</strong><br/>${data.result?.error || "Outside delivery radius."}`;
                                        document.querySelector('button[type="submit"]')?.setAttribute('disabled', 'disabled');
                                    }
                                });
                            }
                            
                            document.querySelectorAll('input[name="partner_id"]').forEach(i => i.addEventListener('change', verifySelectedAddress));
                            
                            // NEW: Ultimate trigger for every touch on an address box
                            $(document).on('click', '#address_selection .card, #address_selection label', function() {
                                setTimeout(verifySelectedAddress, 50); // Small delay to let radio button update
                            });

                            verifySelectedAddress();
                        }
                    }
                    
                    if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', applyCheckoutFixes); else applyCheckoutFixes();
                    document.addEventListener('website_sale_ready', applyCheckoutFixes);
                })();
            </script>
        </xpath>
    </template>

    <!-- 5. FINAL POLISH: Hide Shipping Info using CSS (Safest method) -->
    <template id="chennora_hide_shipping_on_payment" inherit_id="website.layout" name="Chennora Hide Shipping on Payment">
        <xpath expr="." position="inside">
            <style>
                /* Hide any row or div that contains shipping info or delivery methods in the checkout */
                .js_shipping, .shipping_address, #shipping_and_billing, #delivery_carrier, #delivery_method, .js_delivery_carrier {
                    display: none !important;
                }
            </style>
        </xpath>
    </template>
</odoo>
