/* Restaurant Order System — Customer JS v1.6.0
   Multi-order per table. Customer closes session; kitchen handles payment.
*/
(function($){
  'use strict';

  var ROS = {
    settings:      {},
    menu:          [],
    tables:        [],
    cart:          {},
    currentTable:  null,   // { id, name }
    tableSession:  null,   // table_session from server
    sessionKey:    null,   // latest order's session_key (for legacy compat)
    pollTimer:     null,
    lastOverall:   null,

    init: function(){
      this.loadSettings();
      this.bindEvents();
    },

    ajax: function(action, data, cb){
      $.post(rosData.ajax_url, $.extend({ action: action, nonce: rosData.nonce }, data), cb, 'json');
    },

    toast: function(msg, type){
      var t = $('<div class="ros-toast '+(type||'')+'">'+msg+'</div>');
      $('body').append(t);
      setTimeout(function(){ t.addClass('show'); }, 10);
      setTimeout(function(){ t.removeClass('show'); setTimeout(function(){ t.remove(); }, 400); }, 3200);
    },

    showScreen: function(id){
      $('.ros-screen').removeClass('active');
      $('#ros-screen-'+id).addClass('active');
      window.scrollTo(0, 0);
    },

    cur: function(){ return this.settings.currency_symbol || '$'; },
    esc: function(str){ return $('<div>').text(str||'').html(); },

    /* ── SETTINGS ── */
    loadSettings: function(){
      this.ajax('ros_get_settings', {}, function(r){
        if(!r.success) return;
        ROS.settings = r.data;
        ROS.applySettings();
        ROS.loadTables();
      });
    },

    applySettings: function(){
      var s    = this.settings;
      var name = s.restaurant_name || 'Restaurant';
      var addr = [s.restaurant_address, s.restaurant_phone].filter(Boolean).join(' · ');
      $('#ros-restaurant-name').text(name);
      $('#ros-restaurant-address').text(addr);
      $('#ros-menu-rname').text(name);
      $('#ros-menu-raddr').text(addr);
      if(s.logo_url){
        $('#ros-logo-wrap').html('<img src="'+s.logo_url+'" alt="">');
        $('#ros-menu-logo-sm').html('<img src="'+s.logo_url+'" alt="">');
      }
    },

    /* ── TABLES ── */
    loadTables: function(){
      this.ajax('ros_get_tables', {}, function(r){
        if(!r.success) return;
        ROS.tables = r.data;
        ROS.renderTables();
      });
    },

    renderTables: function(){
      var html = '';
      var shapes = window.ROS_SHAPES;
      this.tables.forEach(function(t){
        var occupied   = t.has_active_order;
        var isMe       = t.my_table;
        var isReserved = !!(t.reservation);
        var shape      = t.shape || 'rect_4';
        var cardCls, svgState, subLabel;

        if(!occupied && !isReserved){
          cardCls  = 'ros-table-free';
          svgState = 'free';
          subLabel = '<div class="ros-table-seats">'+t.seats+' personen</div>';
        } else if(isMe){
          cardCls  = 'ros-table-occupied ros-table-mine';
          svgState = 'mine';
          var orderTxt = t.order_count > 1 ? t.order_count+' bestellingen' : '1 bestelling';
          subLabel = '<div class="ros-table-my-label">'+orderTxt+' · Beheren</div>';
        } else if(isReserved && !occupied){
          cardCls  = 'ros-table-occupied ros-table-reserved';
          svgState = 'reserved';
          subLabel = '<div class="ros-table-busy-label">Gereserveerd</div>';
        } else {
          cardCls  = 'ros-table-occupied';
          svgState = 'occupied';
          subLabel = '<div class="ros-table-busy-label">Bezet</div>';
        }

        var svgHtml = shapes ? shapes.get(shape, svgState) : '🪑';

        html += '<div class="ros-table-card '+cardCls+'" data-id="'+t.id+'" data-name="'+ROS.esc(t.name)+'">';
        html +=   '<div class="ros-table-chip"></div>';
        html +=   '<div class="ros-table-svg">'+svgHtml+'</div>';
        html +=   '<div class="ros-table-name">'+ROS.esc(t.name)+'</div>';
        html +=   subLabel;
        html += '</div>';
      });
      $('#ros-tables-grid').html(html || '<p style="grid-column:1/-1;text-align:center;color:#999;padding:40px">Geen tafels.</p>');
    },

    /* ── TABLE CLICK ── */
    handleTableClick: function($card){
      var tableId   = $card.data('id');
      var tableName = $card.data('name');

      this.ajax('ros_check_table', { table_id: tableId }, function(r){
        if(!r.success){ ROS.toast('Verbindingsfout.','error'); return; }

        if(r.result === 'free'){
          ROS.currentTable  = { id: tableId, name: tableName };
          ROS.tableSession  = null;
          ROS.sessionKey    = null;
          ROS.loadMenu();

        } else if(r.result === 'mine'){
          ROS.currentTable  = { id: tableId, name: tableName };
          ROS.tableSession  = r.table_session;
          ROS.sessionKey    = r.session_key;
          ROS.lastOverall   = r.overall;
          ROS.showStatusScreen(r.overall, r.grand_total, r.order_count);
          ROS.startPolling();

        } else if(r.result === 'reserved'){
          // Table is reserved — show reserved modal (different from occupied)
          ROS.showReservedModal(tableName, r.guest_name, r.arrival_time, r.persons);

        } else {
          ROS.showOccupiedModal(tableName);
        }
      });
    },

    showOccupiedModal: function(tableName){
      $('#ros-occupied-modal').remove();
      var html = '<div class="ros-modal-overlay" id="ros-occupied-modal">'
               + '<div class="ros-modal"><div class="ros-modal-icon">🔴</div>'
               + '<h3>'+this.esc(tableName)+' is bezet</h3>'
               + '<p>Deze tafel is in gebruik door andere gasten.</p>'
               + '<p>Kies een andere tafel of vraag het personeel.</p>'
               + '<button class="ros-modal-close-btn" id="ros-close-modal">Sluiten</button>'
               + '</div></div>';
      $('body').append(html);
      setTimeout(function(){ $('#ros-occupied-modal').addClass('visible'); }, 10);
    },

    showReservedModal: function(tableName, guestName, arrivalTime, persons){
      $('#ros-occupied-modal').remove();
      var dt = arrivalTime ? new Date(arrivalTime.replace(' ','T')) : null;
      var timeStr = dt ? dt.toLocaleTimeString('nl-NL',{hour:'2-digit',minute:'2-digit'}) : '';
      var dateStr = dt ? dt.toLocaleDateString('nl-NL',{weekday:'long',day:'numeric',month:'long'}) : '';
      var html = '<div class="ros-modal-overlay" id="ros-occupied-modal">'
               + '<div class="ros-modal">'
               + '<div class="ros-modal-icon">📅</div>'
               + '<h3>'+this.esc(tableName)+' is gereserveerd</h3>'
               + '<p>Deze tafel is gereserveerd voor <strong>'+this.esc(guestName||'')+'</strong>.</p>'
               + (timeStr ? '<p>Aankomst: '+dateStr+' om '+timeStr+(persons ? ' · '+persons+' personen' : '')+'</p>' : '')
               + '<p>Kies alstublieft een andere tafel of vraag het personeel.</p>'
               + '<button class="ros-modal-close-btn" id="ros-close-modal">Sluiten</button>'
               + '</div></div>';
      $('body').append(html);
      setTimeout(function(){ $('#ros-occupied-modal').addClass('visible'); }, 10);
    },

    /* ── MENU ── */
    loadMenu: function(){
      this.cart = {};
      this.updateCartBar();
      $('#ros-current-table-label, #ros-order-table-label').text(this.currentTable.name);
      this.showScreen('menu');

      if(this.menu.length){ this.renderMenu(); return; }
      $('#ros-dishes-wrap').html('<div class="ros-loader"><div class="ros-spinner"></div></div>');
      this.ajax('ros_get_menu', {}, function(r){
        if(!r.success) return;
        ROS.menu = r.data;
        ROS.renderMenu();
      });
    },

    renderMenu: function(){
      var tabs = '';
      this.menu.forEach(function(cat, i){
        tabs += '<div class="ros-cat-tab'+(i===0?' active':'')+'" data-cat="'+cat.id+'">'+ROS.esc(cat.name)+'</div>';
      });
      $('#ros-cat-tabs').html(tabs);
      if(this.menu[0]) this.renderDishes(this.menu[0].id);
    },

    renderDishes: function(catId){
      var cat = this.menu.find(function(c){ return c.id == catId; });
      if(!cat || !cat.dishes || !cat.dishes.length){
        $('#ros-dishes-wrap').html('<div class="ros-empty-cat"><div class="ros-empty-cat-icon">🍽️</div><p>Geen gerechten.</p></div>');
        return;
      }
      var html = '';
      cat.dishes.forEach(function(d){
        var qty = ROS.cart[d.id] ? ROS.cart[d.id].qty : 0;
        var imgHtml = d.image_url
          ? '<img class="ros-dish-img" src="'+d.image_url+'" alt="'+ROS.esc(d.name)+'">'
          : '<div class="ros-dish-img-placeholder">🍴</div>';
        html += '<div class="ros-dish-card'+(qty>0?' in-cart':'')+'" data-id="'+d.id+'">';
        html +=   imgHtml;
        html +=   '<div class="ros-dish-info">';
        html +=     '<div class="ros-dish-name">'+ROS.esc(d.name)+'</div>';
        if(d.description) html += '<div class="ros-dish-desc">'+ROS.esc(d.description)+'</div>';
        html +=     '<div class="ros-dish-bottom">';
        html +=       '<div class="ros-dish-price">'+ROS.cur()+parseFloat(d.price).toFixed(2)+'</div>';
        html +=       '<div class="ros-dish-controls">';
        html +=         '<button class="ros-qty-btn ros-minus" data-id="'+d.id+'">−</button>';
        html +=         '<span class="ros-qty-num" id="ros-qty-'+d.id+'">'+qty+'</span>';
        html +=         '<button class="ros-qty-btn ros-plus" data-id="'+d.id+'" data-price="'+d.price+'" data-name="'+ROS.esc(d.name)+'">+</button>';
        html +=       '</div>';
        html +=     '</div>';
        html +=   '</div>';
        html += '</div>';
      });
      $('#ros-dishes-wrap').html(html);
    },

    /* ── CART ── */
    addToCart: function(id,name,price){
      if(!this.cart[id]) this.cart[id]={id:id,name:name,price:parseFloat(price),qty:0};
      this.cart[id].qty++;
      this.updateCartBar(); this.updateDishQty(id);
    },
    removeFromCart: function(id){
      if(!this.cart[id]||!this.cart[id].qty) return;
      this.cart[id].qty--;
      if(!this.cart[id].qty) delete this.cart[id];
      this.updateCartBar(); this.updateDishQty(id);
    },
    updateDishQty: function(id){
      var qty=this.cart[id]?this.cart[id].qty:0;
      $('#ros-qty-'+id).text(qty);
      $('.ros-dish-card[data-id="'+id+'"]').toggleClass('in-cart',qty>0);
    },
    updateCartBar: function(){
      var items=Object.values(this.cart);
      var count=items.reduce(function(s,i){return s+i.qty;},0);
      var total=items.reduce(function(s,i){return s+i.price*i.qty;},0);
      $('#ros-cart-bubble').text(count);
      $('#ros-cart-total').text(this.cur()+total.toFixed(2));
      $('#ros-cart-bar').toggleClass('visible',count>0);
    },

    /* ── ORDER REVIEW ── */
    showOrderReview: function(){
      var items=Object.values(this.cart);
      if(!items.length){this.toast('Winkelwagen is leeg.','error');return;}
      var total=items.reduce(function(s,i){return s+i.price*i.qty;},0);
      var html='';
      items.forEach(function(i){
        html+='<div class="ros-order-item">'
            +'<div class="ros-oi-left"><div class="ros-oi-name">'+ROS.esc(i.name)+'</div><div class="ros-oi-qty">× '+i.qty+'</div></div>'
            +'<div class="ros-oi-price">'+ROS.cur()+(i.price*i.qty).toFixed(2)+'</div>'
            +'</div>';
      });
      $('#ros-order-list').html(html);
      $('#ros-order-total-display').text(this.cur()+total.toFixed(2));
      $('#ros-order-notes').val('');
      this.showScreen('order');
    },

    /* ── PLACE ORDER ── */
    placeOrder: function(){
      var items=Object.values(this.cart);
      if(!items.length) return;
      var $btn=$('#ros-confirm-order').prop('disabled',true).css('opacity','0.7');
      var payload=items.map(function(i){return{id:i.id,name:i.name,price:i.price,qty:i.qty};});

      this.ajax('ros_place_order',{
        table_id: this.currentTable.id,
        items:    JSON.stringify(payload),
        notes:    $('#ros-order-notes').val()
      }, function(r){
        $btn.prop('disabled',false).css('opacity','1');
        if(!r.success){ROS.toast('Fout bij plaatsen bestelling.','error');return;}
        ROS.sessionKey   = r.session_key;
        ROS.tableSession = r.table_session;
        ROS.cart         = {};
        ROS.lastOverall  = 'pending';
        ROS.showStatusScreen('pending', null, null);
        ROS.startPolling();
        ROS.toast('🎉 Bestelling verzonden naar keuken!','success');
      });
    },

    /* ── STATUS SCREEN ── */
    showStatusScreen: function(overall, grandTotal, orderCount){
      var icons  = { pending:'⏳', accepted:'👨‍🍳', preparing:'🔥', ready:'🎉', customer_closed:'✅' };
      var titles = { pending:'Bestelling Ontvangen!', accepted:'Geaccepteerd!', preparing:'Wordt Bereid...', ready:'Klaar!', customer_closed:'Afgerond — Keuken handelt betaling af' };
      var msgs   = {
        pending:         'De keuken heeft uw bestelling ontvangen.',
        accepted:        'De keuken heeft uw bestelling geaccepteerd.',
        preparing:       'Uw eten wordt bereid. Nog even geduld!',
        ready:           'Uw bestelling staat klaar. Eet smakelijk! 😊',
        customer_closed: 'U heeft afgerond. De keuken handelt de betaling af.',
      };

      $('#ros-status-icon').text(icons[overall]||'🍽️');
      $('#ros-status-title').text(titles[overall]||'Status');
      $('#ros-status-message').text(msgs[overall]||'');

      // Order count badge
      if(orderCount && orderCount > 1){
        $('#ros-status-order-count').text(orderCount+' bestellingen').show();
      } else {
        $('#ros-status-order-count').hide();
      }

      // Grand total
      if(grandTotal){
        $('#ros-status-grand-total').text('Totaal: '+this.cur()+parseFloat(grandTotal).toFixed(2)).show();
      } else {
        $('#ros-status-grand-total').hide();
      }

      // Tracker
      var steps=['pending','accepted','preparing','ready'];
      var idx=steps.indexOf(overall);
      steps.forEach(function(s,i){
        $('#ros-step-'+s).removeClass('done current');
        if(i<idx) $('#ros-step-'+s).addClass('done');
        else if(i===idx) $('#ros-step-'+s).addClass('current');
      });

      // Buttons: show "Meer bestellen" always unless customer_closed
      var isClosed = (overall==='customer_closed');
      $('#ros-order-more').toggle(!isClosed);
      $('#ros-close-order').toggle(!isClosed);

      this.showScreen('status');
    },

    startPolling: function(){
      clearInterval(this.pollTimer);
      this.pollTimer = setInterval(function(){
        if(!ROS.currentTable) return;
        ROS.ajax('ros_get_table_status', { table_id: ROS.currentTable.id }, function(r){
          if(!r.success) return;
          if(r.overall !== ROS.lastOverall){
            ROS.lastOverall = r.overall;
            ROS.showStatusScreen(r.overall, r.grand_total, r.count);
            var msgs={
              accepted: '✅ Keuken heeft uw order geaccepteerd!',
              preparing:'🔥 Uw eten wordt bereid!',
              ready:    '🎉 Uw bestelling is klaar!'
            };
            if(msgs[r.overall]) ROS.toast(msgs[r.overall],'success');
            if(r.overall==='customer_closed') clearInterval(ROS.pollTimer);
          } else {
            // Update totals and count even if status same
            ROS.showStatusScreen(r.overall, r.grand_total, r.count);
          }
        });
      }, 5000);
    },

    /* ── EVENTS ── */
    bindEvents: function(){

      $(document).on('click','#ros-tables-grid .ros-table-card',function(){
        ROS.handleTableClick($(this));
      });

      $(document).on('click','#ros-close-modal, #ros-occupied-modal',function(e){
        if($(e.target).is('#ros-occupied-modal,#ros-close-modal')){
          $('#ros-occupied-modal').removeClass('visible');
          setTimeout(function(){$('#ros-occupied-modal').remove();},300);
        }
      });

      $(document).on('click','.ros-cat-tab',function(){
        $('.ros-cat-tab').removeClass('active');
        $(this).addClass('active');
        ROS.renderDishes($(this).data('cat'));
      });

      $(document).on('click','.ros-plus',function(e){
        e.stopPropagation();
        ROS.addToCart($(this).data('id'),$(this).data('name'),$(this).data('price'));
      });
      $(document).on('click','.ros-minus',function(e){
        e.stopPropagation();
        ROS.removeFromCart($(this).data('id'));
      });

      $(document).on('click','.ros-cart-cta',function(){ ROS.showOrderReview(); });
      $(document).on('click','#ros-back-to-tables',function(){ ROS.showScreen('tables'); ROS.loadTables(); });
      $(document).on('click','#ros-back-to-menu',function(){ ROS.showScreen('menu'); ROS.updateCartBar(); });
      $(document).on('click','#ros-confirm-order',function(){ ROS.placeOrder(); });

      // More bestellen — go back to menu, keep session alive
      $(document).on('click','#ros-order-more',function(){
        clearInterval(ROS.pollTimer);
        ROS.cart={};
        ROS.loadMenu();
      });

      // Afronden — klant kiest betaalmethode
      $(document).on('click','#ros-close-order',function(){
        ROS.showPaymentModal();
      });
    },

    /* ── PAYMENT MODAL ── */
    paymentConfig: null,

    loadPaymentConfig: function(cb){
      if(this.paymentConfig){ cb(this.paymentConfig); return; }
      this.ajax('ros_get_payment_config',{},function(r){
        ROS.paymentConfig = r.success ? r : { stripe_enabled: false };
        cb(ROS.paymentConfig);
      });
    },

    showPaymentModal: function(){
      var self = this;
      this.loadPaymentConfig(function(cfg){
        // Build modal HTML
        var stripeBtn = cfg.stripe_enabled
          ? '<button class="ros-pay-choice ros-pay-stripe" id="ros-pay-card">'
            + '<span class="ros-pay-choice-icon">💳</span>'
            + '<div><strong>Kaart betalen</strong><small>Creditcard / Debitcard via Stripe</small></div>'
            + '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="9 18 15 12 9 6"/></svg>'
            + '</button>'
          : '';

        var html = '<div class="ros-modal-overlay visible" id="ros-pay-modal">'
                 + '<div class="ros-modal ros-pay-modal-inner">'
                 + '<div class="ros-pay-modal-header">'
                 + '<div class="ros-modal-icon">💰</div>'
                 + '<h3>Hoe wilt u betalen?</h3>'
                 + '<p>Kies uw betaalmethode</p>'
                 + '</div>'
                 + '<div class="ros-pay-choices">'
                 + '<button class="ros-pay-choice ros-pay-cash" id="ros-pay-cash">'
                 + '<span class="ros-pay-choice-icon">💵</span>'
                 + '<div><strong>Cash</strong><small>Betalen aan de kassa</small></div>'
                 + '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="9 18 15 12 9 6"/></svg>'
                 + '</button>'
                 + '<button class="ros-pay-choice ros-pay-pin" id="ros-pay-pin">'
                 + '<span class="ros-pay-choice-icon">🏦</span>'
                 + '<div><strong>Pin / Bankpas</strong><small>Betalen met de pin-automaat</small></div>'
                 + '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="9 18 15 12 9 6"/></svg>'
                 + '</button>'
                 + stripeBtn
                 + '</div>'
                 + '<button class="ros-pay-cancel" id="ros-pay-cancel">Annuleren</button>'
                 + '</div>'
                 + '</div>';

        $('#ros-payment-modal').html(html).show();

        // Cash
        $('#ros-pay-cash').off('click').on('click', function(){
          ROS.doCustomerClose('cash');
        });
        // Pin
        $('#ros-pay-pin').off('click').on('click', function(){
          ROS.doCustomerClose('pin');
        });
        // Card (Stripe)
        $('#ros-pay-card').off('click').on('click', function(){
          ROS.showStripeForm(cfg);
        });
        // Cancel
        $('#ros-pay-cancel, #ros-pay-modal').off('click').on('click', function(e){
          if($(e.target).is('#ros-pay-modal, #ros-pay-cancel')){
            $('#ros-payment-modal').hide().html('');
          }
        });
      });
    },

    doCustomerClose: function(method){
      var self = this;
      $('#ros-payment-modal').hide().html('');
      clearInterval(this.pollTimer);
      this.ajax('ros_customer_close',{ table_id: this.currentTable.id, payment_method: method },function(r){
        if(r.success){
          var methodLabels = { cash:'💵 Cash', pin:'🏦 Pin', stripe:'💳 Kaart' };
          ROS.toast('✅ Afgerond met '+(methodLabels[method]||method)+'! Keuken handelt betaling af.','success');
          ROS.showStatusScreen('customer_closed', null, null);
        }
      });
    },

    /* ── STRIPE FORM ── */
    showStripeForm: function(cfg){
      var self = this;
      // Get grand total from status screen
      var totalEl = document.getElementById('ros-status-grand-total');
      var totalTxt = totalEl ? totalEl.textContent.replace(/[^0-9.,]/g,'').replace(',','.') : '0';
      var amount = parseFloat(totalTxt) || 0;

      if(amount <= 0){
        // Try to get from poll
        this.ajax('ros_get_table_status',{ table_id: this.currentTable.id },function(r){
          if(r.success) {
            amount = parseFloat(r.grand_total||0);
            ROS._startStripeIntent(cfg, amount);
          }
        });
      } else {
        this._startStripeIntent(cfg, amount);
      }
    },

    _startStripeIntent: function(cfg, amount){
      var self = this;
      // Show loading state
      $('#ros-pay-modal .ros-pay-choices').html('<div style="text-align:center;padding:30px"><div class="ros-spinner" style="margin:0 auto 14px"></div><p style="color:#666">Verbinden met betaalserver...</p></div>');

      this.ajax('ros_stripe_intent',{
        table_id: this.currentTable.id,
        amount:   amount
      }, function(r){
        if(!r.success){
          ROS.toast('Stripe fout: '+(r.message||'Probeer opnieuw'),'error');
          $('#ros-payment-modal').hide().html('');
          return;
        }
        ROS._renderStripeForm(cfg, r.client_secret, r.intent_id, amount);
      });
    },

    _renderStripeForm: function(cfg, clientSecret, intentId, amount){
      var self   = this;
      var cur    = this.cur();

      var formHtml = '<div style="padding:0">'
        + '<div style="text-align:center;margin-bottom:18px">'
        + '<div style="font-size:2rem;margin-bottom:8px">💳</div>'
        + '<strong style="font-size:1rem">Betalen met kaart</strong>'
        + '<div style="font-size:1.3rem;font-weight:800;color:#C9A96E;margin-top:4px">'+cur+parseFloat(amount).toFixed(2)+'</div>'
        + '</div>'
        + '<div id="ros-stripe-card-element" style="background:#f8f8f8;border:1.5px solid #ddd;border-radius:10px;padding:14px;margin-bottom:14px;min-height:44px"></div>'
        + '<div id="ros-stripe-error" style="color:#e74c3c;font-size:0.82rem;margin-bottom:10px;display:none"></div>'
        + '<button id="ros-stripe-submit" style="width:100%;padding:14px;background:linear-gradient(135deg,#635BFF,#4F46E5);color:#fff;border:none;border-radius:50px;font-size:0.95rem;font-weight:800;cursor:pointer;display:flex;align-items:center;justify-content:center;gap:8px">'
        + '🔒 Nu Betalen — '+cur+parseFloat(amount).toFixed(2)
        + '</button>'
        + '<button id="ros-stripe-back" style="width:100%;margin-top:10px;background:none;border:none;color:#888;font-size:0.82rem;cursor:pointer;padding:8px">← Andere betaalmethode</button>'
        + '<div style="text-align:center;margin-top:12px;font-size:0.72rem;color:#aaa">Beveiligd door Stripe 🔒</div>'
        + '</div>';

      $('#ros-pay-modal .ros-pay-modal-inner').html(
        '<div class="ros-pay-modal-header"><h3>Kaartbetaling</h3></div>' + formHtml
      );

      // Load Stripe.js dynamically
      if(typeof Stripe === 'undefined'){
        var script = document.createElement('script');
        script.src = 'https://js.stripe.com/v3/';
        script.onload = function(){ self._initStripe(cfg.stripe_pk, clientSecret, intentId); };
        document.head.appendChild(script);
      } else {
        self._initStripe(cfg.stripe_pk, clientSecret, intentId);
      }

      $('#ros-stripe-back').on('click', function(){
        $('#ros-payment-modal').hide().html('');
        ROS.showPaymentModal();
      });
    },

    _initStripe: function(pk, clientSecret, intentId){
      var self    = this;
      var stripe  = Stripe(pk);
      var elements= stripe.elements();
      var card    = elements.create('card', {
        style: {
          base:  { fontSize:'16px', color:'#1A1A1A', fontFamily:'Inter, sans-serif', '::placeholder':{ color:'#aaa' } },
          invalid:{ color:'#e74c3c' }
        }
      });
      card.mount('#ros-stripe-card-element');
      card.on('change', function(e){
        $('#ros-stripe-error').toggle(!!e.error).text(e.error ? e.error.message : '');
      });

      $('#ros-stripe-submit').off('click').on('click', function(){
        var $btn = $(this).prop('disabled',true).text('Bezig...');
        stripe.confirmCardPayment(clientSecret, {
          payment_method: { card: card }
        }).then(function(result){
          if(result.error){
            $('#ros-stripe-error').show().text(result.error.message);
            $btn.prop('disabled',false).html('🔒 Nu Betalen');
          } else if(result.paymentIntent.status === 'succeeded'){
            // Payment OK — close session
            ROS.ajax('ros_stripe_confirm',{ table_id: ROS.currentTable.id, intent_id: intentId },function(r){
              $('#ros-payment-modal').hide().html('');
              clearInterval(ROS.pollTimer);
              ROS.toast('✅ Betaling geslaagd! Dank u wel 🎉','success');
              ROS.showStatusScreen('customer_closed', null, null);
            });
          }
        });
      });
    }
  };

  $(document).ready(function(){
    if($('#ros-customer-app').length) ROS.init();
  });

})(jQuery);
