(function () {
  'use strict';

  const PRESETS = [
    { id: 'p4',    label: '4 Products',          desc: 'Full row of product cards',
      slots: [{type:'product'},{type:'product'},{type:'product'},{type:'product'}] },
    { id: 'p3c1',  label: '3 + Accent Block',    desc: '3 products with a content accent in the 4th slot',
      slots: [{type:'product'},{type:'product'},{type:'product'},{type:'content',block_type:'countdown'}] },
    { id: 'p2c1',  label: '2 + Wide Block',      desc: '2 products with a half-width content block',
      slots: [{type:'product'},{type:'product'},{type:'content',block_type:'sale'}] },
    { id: 'p1c1',  label: 'Feature + Content',   desc: '1 product with a large content panel beside it',
      slots: [{type:'product'},{type:'content',block_type:'text'}] },
    { id: 'p2c2',  label: '2 Products + 2 Blocks', desc: '2 products with 2 content accents',
      slots: [{type:'product'},{type:'product'},{type:'content',block_type:'review_credit'},{type:'content',block_type:'raffle'}] },
    { id: 'c1',    label: 'Full-Width Banner',   desc: 'A single content block spanning the full row',
      slots: [{type:'content',block_type:'sale'}] },
  ];

  const BLOCK_TYPES = [
    { key: 'countdown',     label: 'Countdown',   color: '#e74c3c', mobile: '⚡' },
    { key: 'sale',          label: 'Sale',         color: '#f1c40f', mobile: '🔥' },
    { key: 'review_credit', label: 'Reviews',      color: '#e6a817', mobile: '⭐' },
    { key: 'raffle',        label: 'Raffle',       color: '#1abc9c', mobile: '🎲' },
    { key: 'shortcut',      label: 'Link / CTA',   color: '#9b59b6', mobile: '🔗' },
    { key: 'timer',         label: 'Timer',        color: '#e67e22', mobile: '⏱' },
    { key: 'text',          label: 'Text',         color: '#3498db', mobile: '📝' },
    { key: 'image',         label: 'Image',        color: '#2ecc71', mobile: '🖼' },
  ];

  let state = { step: 1, presetIdx: 0, slots: [], storeId: 0, csrfToken: '', categoryName: '' };

  document.addEventListener('DOMContentLoaded', function () {
    var trigger = document.getElementById('btn-new-block');
    var overlay = document.getElementById('wz-overlay');
    if (!trigger || !overlay) return;
    state.storeId   = parseInt(overlay.dataset.storeId || '0', 10);
    state.csrfToken = overlay.dataset.csrf || '';
    trigger.addEventListener('click', function (e) { e.preventDefault(); openWizard(); });
    overlay.addEventListener('click', function (e) { if (e.target === overlay) closeWizard(); });
    document.getElementById('wz-cancel').addEventListener('click', closeWizard);
    document.getElementById('wz-back').addEventListener('click', prevStep);
    document.getElementById('wz-next').addEventListener('click', nextStep);
  });

  function openWizard() {
    state.step = 1; state.presetIdx = 0; state.slots = []; state.categoryName = '';
    renderStep1(); updateNav();
    document.getElementById('wz-overlay').style.display = 'flex';
  }
  function closeWizard() { document.getElementById('wz-overlay').style.display = 'none'; }

  function nextStep() {
    if (state.step === 1) {
      state.slots = PRESETS[state.presetIdx].slots.map(function (s) {
        return Object.assign({ title:'', body:'', bg_color: getBtColor(s.block_type), text_color:'#ffffff', cta:'', cta_link:'', slot_size:1 }, s);
      });
      state.step = 2; renderStep2();
    } else if (state.step === 2) {
      state.step = 3; renderStep3();
    } else if (state.step === 3) {
      collectStep3(); submitWizard(); return;
    }
    updateNav(); setActiveStep(state.step);
  }
  function prevStep() {
    if (state.step > 1) {
      state.step--;
      setActiveStep(state.step);
      if (state.step === 1) renderStep1();
      if (state.step === 2) renderStep2();
      updateNav();
    }
  }
  function updateNav() {
    document.getElementById('wz-back').style.display = state.step === 1 ? 'none' : 'inline-flex';
    document.getElementById('wz-next').textContent   = state.step === 3 ? 'CREATE ROW' : 'NEXT →';
  }
  function setActiveStep(n) {
    document.querySelectorAll('.wz-step').forEach(function (el, i) { el.style.display = (i+1===n) ? 'block' : 'none'; });
    document.querySelectorAll('.wz-pip').forEach(function (el, i) { el.classList.toggle('active', i < n); });
  }
  function getBtColor(key) {
    var bt = BLOCK_TYPES.find(function(t){return t.key===key;});
    return bt ? bt.color : '#2D6A4F';
  }

  function renderStep1() {
    setActiveStep(1);
    renderPreset();
    var prev = document.getElementById('wz-prev-preset');
    var next = document.getElementById('wz-next-preset');
    if (prev && next) {
      prev.onclick = function () { state.presetIdx = (state.presetIdx - 1 + PRESETS.length) % PRESETS.length; renderPreset(); };
      next.onclick = function () { state.presetIdx = (state.presetIdx + 1) % PRESETS.length; renderPreset(); };
    }
  }
  function renderPreset() {
    var p = PRESETS[state.presetIdx];
    var el = document.getElementById('wz-preset-label');
    var de = document.getElementById('wz-preset-desc');
    var pv = document.getElementById('wz-preset-preview');
    if (el) el.textContent = p.label;
    if (de) de.textContent = p.desc;
    if (!pv) return;
    var productCount = p.slots.filter(function(s){return s.type==='product';}).length;
    var contentCount = p.slots.filter(function(s){return s.type==='content';}).length;
    var remaining    = 4 - productCount;
    var cSize        = contentCount > 0 ? Math.floor(remaining / contentCount) : 0;
    pv.innerHTML = '';
    var grid = document.createElement('div');
    grid.className = 'wz-preset-grid';
    p.slots.forEach(function (s) {
      var cell = document.createElement('div');
      var span = s.type === 'content' ? cSize : 1;
      cell.className = 'wz-preset-cell ' + s.type;
      cell.style.gridColumn = 'span ' + Math.max(1, span);
      if (s.type === 'content') {
        var bt = BLOCK_TYPES.find(function(t){return t.key===s.block_type;}) || BLOCK_TYPES[0];
        cell.style.background = bt.color + '22';
        cell.style.borderColor = bt.color + '55';
        cell.innerHTML = '<span class="wz-cell-icon">' + bt.mobile + '</span><span class="wz-cell-label">' + bt.label + '</span>';
      } else {
        cell.innerHTML = '<span class="wz-cell-icon">🛒</span><span class="wz-cell-label">Product</span>';
      }
      grid.appendChild(cell);
    });
    var total = p.slots.reduce(function(acc,s){ return acc + (s.type==='content'?Math.max(1,cSize):1); }, 0);
    for (var i = total; i < 4; i++) {
      var ghost = document.createElement('div');
      ghost.className = 'wz-preset-cell ghost';
      ghost.innerHTML = '<span class="wz-cell-label">empty</span>';
      grid.appendChild(ghost);
    }
    pv.appendChild(grid);
    var dots = document.getElementById('wz-preset-dots');
    if (dots) {
      dots.innerHTML = '';
      PRESETS.forEach(function (_, i) {
        var d = document.createElement('span');
        d.className = 'wz-dot' + (i === state.presetIdx ? ' active' : '');
        dots.appendChild(d);
      });
    }
  }

  function renderStep2() {
    setActiveStep(2);
    var area = document.getElementById('wz-slots-area');
    area.innerHTML = '';
    state.slots.forEach(function (slot, i) {
      var card = document.createElement('div');
      card.className = 'wz-slot-card ' + slot.type;
      card.dataset.index = i;
      card.innerHTML = buildSlotCard(slot, i);
      area.appendChild(card);
    });
    area.addEventListener('click', function (e) {
      var typeBtn = e.target.closest('.wz-type-btn');
      if (typeBtn) {
        var idx = parseInt(typeBtn.dataset.slot, 10);
        state.slots[idx].type = typeBtn.dataset.type;
        if (typeBtn.dataset.type === 'content' && !state.slots[idx].block_type) state.slots[idx].block_type = 'countdown';
        var card = area.querySelector('[data-index="'+idx+'"]');
        card.className = 'wz-slot-card ' + state.slots[idx].type;
        card.innerHTML = buildSlotCard(state.slots[idx], idx);
        return;
      }
      var blockBtn = e.target.closest('.wz-block-type-btn');
      if (blockBtn) {
        var idx = parseInt(blockBtn.dataset.slot, 10);
        state.slots[idx].block_type = blockBtn.dataset.btype;
        state.slots[idx].bg_color   = getBtColor(blockBtn.dataset.btype);
        var card = area.querySelector('[data-index="'+idx+'"]');
        card.innerHTML = buildSlotCard(state.slots[idx], idx);
      }
    });
  }
  function buildSlotCard(slot, i) {
    var isContent = slot.type === 'content';
    var html = '<div class="wz-slot-num">Slot '+(i+1)+'</div>' +
      '<div class="wz-slot-type-btns">' +
        '<button class="wz-type-btn product'+(slot.type==='product'?' active':'')+'" data-slot="'+i+'" data-type="product">🛒 Product</button>' +
        '<button class="wz-type-btn content'+(isContent?' active':'')+'" data-slot="'+i+'" data-type="content">✦ Block</button>' +
      '</div>';
    if (isContent) {
      html += '<div class="wz-btype-grid">';
      BLOCK_TYPES.forEach(function (bt) {
        var sel = (slot.block_type||'countdown') === bt.key;
        html += '<button class="wz-block-type-btn'+(sel?' selected':'')+'" data-slot="'+i+'" data-btype="'+bt.key+'" style="'+(sel?'border-color:'+bt.color+';color:'+bt.color+';background:'+bt.color+'18;':'')+'">'+bt.mobile+' '+bt.label+'</button>';
      });
      html += '</div>';
    }
    return html;
  }

  function renderStep3() {
    setActiveStep(3);
    var area = document.getElementById('wz-details-area');
    var hasProduct = state.slots.some(function(s){return s.type==='product';});
    var contents   = state.slots.filter(function(s){return s.type==='content';});
    var html = '';
    if (hasProduct) {
      html += '<div class="wz-detail-group"><label class="wz-label">Product Group Name</label>' +
        '<p class="wz-hint">Row header on the storefront. Add products via the Products tab.</p>' +
        '<input type="text" id="wz-cat-name" class="wz-input" placeholder="e.g. Top Picks, Premium Selection…" value="'+esc(state.categoryName)+'"></div>';
    }
    contents.forEach(function (slot) {
      var idx = state.slots.indexOf(slot);
      var bt  = BLOCK_TYPES.find(function(t){return t.key===(slot.block_type||'countdown');}) || BLOCK_TYPES[0];
      html += '<div class="wz-detail-group" data-content-idx="'+idx+'">' +
        '<div class="wz-detail-header" style="color:'+bt.color+'">'+bt.mobile+' '+bt.label+' — Slot '+(idx+1)+'</div>' +
        '<label class="wz-label">Title</label>' +
        '<input type="text" class="wz-input wz-content-title" data-idx="'+idx+'" placeholder="Short headline" value="'+esc(slot.title||'')+'"><br>' +
        '<label class="wz-label" style="margin-top:10px">Body <span style="opacity:.5;font-weight:400">(HTML ok)</span></label>' +
        '<textarea class="wz-input wz-content-body" data-idx="'+idx+'" rows="2" placeholder="Short punch line or offer…">'+esc(slot.body||'')+'</textarea>' +
        '<div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;margin-top:10px">' +
          '<div><label class="wz-label">BG</label><input type="color" class="wz-color wz-content-bg" data-idx="'+idx+'" value="'+esc(slot.bg_color||bt.color)+'"></div>' +
          '<div><label class="wz-label">Text</label><input type="color" class="wz-color wz-content-tc" data-idx="'+idx+'" value="'+esc(slot.text_color||'#ffffff')+'"></div>' +
        '</div>' +
        '<div class="wz-cta-row" style="margin-top:12px;border-top:1px solid rgba(255,255,255,.06);padding-top:12px">' +
          '<label class="wz-label">CTA Button <span style="opacity:.5;font-weight:400">(optional)</span></label>' +
          '<div style="display:grid;grid-template-columns:1fr 2fr;gap:8px;margin-top:6px">' +
            '<input type="text" class="wz-input wz-content-cta" data-idx="'+idx+'" placeholder="Button label" value="'+esc(slot.cta||'')+'">'+
            '<input type="text" class="wz-input wz-content-cta-link" data-idx="'+idx+'" placeholder="?v=product&id=… or full URL" value="'+esc(slot.cta_link||'')+'">'+
          '</div>' +
        '</div>' +
        '</div>';
    });
    if (!hasProduct && contents.length === 0) html = '<div style="text-align:center;padding:40px;color:rgba(200,204,212,.4)">Hit CREATE ROW.</div>';
    area.innerHTML = html;
  }

  function collectStep3() {
    var catInput = document.getElementById('wz-cat-name');
    if (catInput) state.categoryName = catInput.value.trim();
    document.querySelectorAll('.wz-content-title').forEach(function(el){ state.slots[+el.dataset.idx].title = el.value.trim(); });
    document.querySelectorAll('.wz-content-body').forEach(function(el){ state.slots[+el.dataset.idx].body = el.value.trim(); });
    document.querySelectorAll('.wz-content-bg').forEach(function(el){ state.slots[+el.dataset.idx].bg_color = el.value; });
    document.querySelectorAll('.wz-content-tc').forEach(function(el){ state.slots[+el.dataset.idx].text_color = el.value; });
    document.querySelectorAll('.wz-content-cta').forEach(function(el){ state.slots[+el.dataset.idx].cta = el.value.trim(); });
    document.querySelectorAll('.wz-content-cta-link').forEach(function(el){ state.slots[+el.dataset.idx].cta_link = el.value.trim(); });
  }

  function submitWizard() {
    var btn = document.getElementById('wz-next');
    btn.disabled = true; btn.textContent = 'Creating…';
    fetch('?view=store&id='+state.storeId+'&api=row_wizard', {
      method:'POST',
      headers:{'Content-Type':'application/json','X-CSRF-Token':state.csrfToken},
      body: JSON.stringify({ store_id:state.storeId, category_name:state.categoryName, slots:state.slots, _csrf:state.csrfToken })
    })
    .then(function(r){return r.json();})
    .then(function(data){
      if (data.ok) { closeWizard(); window.location.reload(); }
      else { btn.disabled=false; btn.textContent='CREATE ROW'; alert('Error: '+(data.error||'unknown')); }
    })
    .catch(function(){ btn.disabled=false; btn.textContent='CREATE ROW'; alert('Network error.'); });
  }

  function esc(s){ return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;'); }
})();
