
(function () {
  'use strict';

  var API = '/api/instinctor/v1/demo/start';
  var STEP_MS = 2200;            
  var FINAL_HOLD_MS = 1500;      

  
  var STEPS = [
    'Reading your name',
    'Designing a hero for {name}',
    'Framing your best work in the gallery',
    'Wiring up online booking',
    'Writing a welcome in your voice',
    'Choosing a palette that suits {name}'
  ];
  var FINAL_STEP = 'Bringing {name} to life';

  function initEntry(form) {
    var input = form.querySelector('[data-demo-name]');
    var cityEl = form.querySelector('[data-demo-city]');
    var urlEl = form.querySelector('[data-demo-url]');
    var tradeEl = form.querySelector('[data-demo-trade]');
    var btn = form.querySelector('[data-demo-go]');
    var err = form.querySelector('[data-demo-error]');
    var host = document.querySelector('[data-demo-entry]');
    var tradeDefault = (host && host.getAttribute('data-trade')) || 'salon';
    var busy = false;

    form.addEventListener('submit', function (e) {
      e.preventDefault();
      if (busy) return;
      var name = (input && input.value ? input.value : '').trim();
      var city = (cityEl && cityEl.value ? cityEl.value : '').trim();
      var url = (urlEl && urlEl.value ? urlEl.value : '').trim();
      var trade = (tradeEl && tradeEl.value ? tradeEl.value : '').trim() || tradeDefault;
      if (err) err.textContent = '';
      if (!name) {
        if (err) err.textContent = 'Type your salon name to see your site.';
        if (input) input.focus();
        return;
      }
      busy = true;
      if (btn) { btn.setAttribute('disabled', 'disabled'); btn.textContent = 'Building your site…'; }
      try { sessionStorage.setItem('instinctor_demo_name', name); } catch (_e) {}

      var urlPromise = fetch(API, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
        body: JSON.stringify({ trade: trade, name: name, city: city, url: url })
      }).then(function (r) {
        return r.json().then(function (d) {
          if (r.ok && d && d.url) return d.url;
          var code = (d && d.error) || 'error';
          throw new Error(code);
        });
      });

      runMontage(name, urlPromise);
    });
  }

  function runMontage(name, urlPromise) {
    var esc = function (s) { return String(s).replace(/[&<>"]/g, function (c) {
      return { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]; }); };
    var fill = function (t) { return t.replace(/\{name\}/g, esc(name)); };

    var overlay = document.createElement('div');
    overlay.className = 'demo-build';
    overlay.setAttribute('role', 'status');
    overlay.setAttribute('aria-live', 'polite');
    var ticks = STEPS.map(function () { return '<span class="demo-build-tick"></span>'; }).join('');
    overlay.innerHTML =
      '<div class="demo-build-inner">' +
        '<p class="demo-build-eyebrow">Building your site</p>' +
        '<h2 class="demo-build-name">' + esc(name) + '</h2>' +
        '<p class="demo-build-status" data-status>&nbsp;</p>' +
        '<div class="demo-build-ticks" data-ticks>' + ticks + '</div>' +
        '<p class="demo-build-error" data-build-error></p>' +
      '</div>';
    document.body.appendChild(overlay);
    
    void overlay.offsetWidth;
    overlay.classList.add('is-on');

    var statusEl = overlay.querySelector('[data-status]');
    var tickEls = overlay.querySelectorAll('[data-ticks] .demo-build-tick');
    var errEl = overlay.querySelector('[data-build-error]');
    var failed = false;

    urlPromise.catch(function () {  });

    function setStatus(text) {
      if (!statusEl) return;
      statusEl.style.opacity = '0';
      setTimeout(function () { statusEl.textContent = fill(text); statusEl.style.opacity = '1'; }, 200);
    }

    function step(i) {
      if (failed) return;
      if (i >= STEPS.length) { finalStep(); return; }
      setStatus(STEPS[i]);
      var tick = tickEls[i];
      if (tick) { tick.style.setProperty('--tick-ms', STEP_MS + 'ms'); tick.classList.add('active'); }
      setTimeout(function () {
        if (tick) { tick.classList.remove('active'); tick.classList.add('done'); }
        step(i + 1);
      }, STEP_MS);
    }

    function finalStep() {
      setStatus(FINAL_STEP);
      
      var timer = new Promise(function (res) { setTimeout(res, FINAL_HOLD_MS); });
      Promise.all([timer, urlPromise]).then(function (vals) {
        setStatus('Your site is ready.');
        setTimeout(function () { window.location.assign(vals[1]); }, 500);
      }).catch(function (e) {
        failed = true;
        var msg = (e && e.message === 'rate_limited')
          ? 'You have tried a few times. Give it a minute, then reload and go again.'
          : 'We could not finish building your site. Reload and try once more.';
        if (errEl) errEl.textContent = msg;
        if (statusEl) statusEl.textContent = '';
      });
    }

    step(0);
  }

  function initDemoPage() {

  }

  function boot() {
    var form = document.querySelector('[data-demo-form]');
    if (form) { initEntry(form); return; }
    initDemoPage();
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', boot);
  } else {
    boot();
  }
})();
