
(function () {
  'use strict';

  var API = '/api/instinctor/v1/demo/start';

  

  
  function utmFromSearch() {
    try {
      var q = new URLSearchParams(location.search), out = {}, any = false;
      ['source', 'medium', 'campaign', 'term', 'content'].forEach(function (k) {
        var v = q.get('utm_' + k);
        if (v) { out[k] = String(v).slice(0, 120); any = true; }
      });
      return any ? out : null;
    } catch (e) { return null; }
  }
  (function stashUtm() {
    var u = utmFromSearch();
    if (!u) return;
    try { sessionStorage.setItem('imp_utm', JSON.stringify(u)); } catch (e) {}
  })();
  function utmVal() {
    var u = utmFromSearch();
    if (u) return u;
    try { return JSON.parse(sessionStorage.getItem('imp_utm') || 'null'); } catch (e) { return null; }
  }

  var STEP_MS = 1500;            
  var FINAL_HOLD_MS = 800;       

  
  
  try {
    if (localStorage.getItem('impap')) { STEP_MS = 600; FINAL_HOLD_MS = 320; }
  } catch (eAp) {}

  
  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';

  
  
  var LONG_STEPS = [
    'Bringing {name} to life',
    'Writing your copy, line by line',
    'Placing your photos',
    'Tuning colors and spacing',
    'Setting up booking and contact',
    'Still building. Good sites take a minute',
    'Nearly there'
  ];

  

  
  
  function describeProblem(s) {
    s = String(s || '').replace(/\s+/g, ' ').trim();
    if (!s) return 'empty_description';
    if (s.length < 20) return 'short_description';
    if (s.split(' ').length < 3) return 'short_description';
    if ((s.match(/\p{L}/gu) || []).length < 10) return 'short_description';
    return '';
  }

  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 emailEl = form.querySelector('[data-demo-email]');
    var phoneEl = form.querySelector('[data-demo-phone]');
    var btn = form.querySelector('[data-demo-go]');
    var err = form.querySelector('[data-demo-error]');
    var busy = false;

    

    
    
    if (tradeEl && err) {
      var hintTimer = null;
      tradeEl.addEventListener('input', function () {
        if (hintTimer) clearTimeout(hintTimer);
        if (err.getAttribute('data-hint') === '1') { err.textContent = ''; err.removeAttribute('data-hint'); err.style.color = ''; }
        hintTimer = setTimeout(function () {
          var v = (tradeEl.value || '').replace(/\s+/g, ' ').trim();
          if (v.length > 0 && describeProblem(v) !== '' && !err.textContent) {
            err.setAttribute('data-hint', '1');
            err.style.color = '#9aa0aa';
            err.textContent = 'A little more, please: a sentence or two about what you do makes your site much better.';
          }
        }, 1100);
      });
      tradeEl.addEventListener('blur', function () {
        if (err.getAttribute('data-hint') === '1') { err.textContent = ''; err.removeAttribute('data-hint'); err.style.color = ''; }
      });
    }

    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();
      if (err) err.textContent = '';
      if (!name) {
        if (err) err.textContent = 'Type your business name to see your site.';
        if (input) input.focus();
        return;
      }
      var problem = describeProblem(trade);
      if (problem) {
        if (err) {
          err.textContent = problem === 'empty_description'
            ? 'Tell us what you do, in a sentence. It is what your site gets built from.'
            : 'A few more words, please. What you do, and what makes you you: that is what your site gets built from.';
        }
        if (tradeEl) tradeEl.focus();
        return;
      }

      function staffVal() {
        var el = document.querySelector('[data-demo-staff].is-on');
        return el ? (el.getAttribute('data-demo-staff') || '') : '';
      }

      
      function hoursVal() {
        var on = document.querySelectorAll('[data-demo-day].is-on');
        if (!on.length) return null;
        var days = Array.prototype.map.call(on, function (d) { return d.getAttribute('data-demo-day'); });
        var o = document.querySelector('[data-demo-open]');
        var c = document.querySelector('[data-demo-close]');
        var open  = o && o.value ? o.value : '09:00';
        var close = c && c.value ? c.value : '17:00';
        if (close <= open) return null;
        return { days: days, open: open, close: close };
      }
      function ownerNameVal() {
        var el = document.querySelector('[data-demo-owner]');
        return el && el.value ? el.value.trim() : '';

      }
      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, utm: utmVal(), ref: (document.referrer || '').slice(0, 200), email: (emailEl && emailEl.value ? emailEl.value : '').trim(), phone: (phoneEl && phoneEl.value ? phoneEl.value : '').trim(), staff: staffVal(), owner_name: ownerNameVal(), hours: hoursVal(), archetype: (function () { var a = document.querySelector('[data-demo-arche].is-on'); return a ? a.getAttribute('data-demo-arche') : ''; })() })
      }).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 wireDayChips() {
    var days = document.querySelectorAll('[data-demo-day]');
    Array.prototype.forEach.call(days, function (d) {
      d.addEventListener('click', function () {
        var on = !d.classList.contains('is-on');
        d.classList.toggle('is-on', on);
        d.setAttribute('aria-pressed', on ? 'true' : 'false');
      });
    });
  })();

  (function wireArcheChips() {
    var chips = document.querySelectorAll('[data-demo-arche]');
    if (!chips.length) return;
    Array.prototype.forEach.call(chips, function (c) {
      c.addEventListener('click', function () {
        var was = c.classList.contains('is-on');
        Array.prototype.forEach.call(chips, function (o) {
          o.classList.remove('is-on');
          o.setAttribute('aria-pressed', 'false');
        });

        if (!was) { c.classList.add('is-on'); c.setAttribute('aria-pressed', 'true'); }
      });
    });
  })();

  (function wireStaffChips() {
    var chips = document.querySelectorAll('[data-demo-staff]');
    if (!chips.length) return;
    var owner = document.querySelector('[data-demo-owner]');
    Array.prototype.forEach.call(chips, function (c) {
      c.addEventListener('click', function () {
        Array.prototype.forEach.call(chips, function (o) {
          o.classList.remove('is-on');
          o.setAttribute('aria-pressed', 'false');
        });
        c.classList.add('is-on');
        c.setAttribute('aria-pressed', 'true');
        if (owner) {
          var solo = c.getAttribute('data-demo-staff') === 'solo';
          owner.hidden = !solo;
          if (solo) { try { owner.focus(); } catch (e) {} } else { owner.value = ''; }
        }
      });
    });
  })();

  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';

    
    
    try { document.body.classList.add('demo-building'); } catch (e) {}
    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 = text.replace(/\{name\}/g, name); statusEl.style.opacity = '1'; }, 200);
    }

    
    
    var siteReady = false;
    urlPromise.then(function () { siteReady = true; }, function () {});

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

    function finalStep() {
      setStatus(FINAL_STEP);

      var lastTick = tickEls[tickEls.length - 1];
      if (lastTick && !siteReady) { lastTick.classList.remove('done'); lastTick.classList.add('pulse'); }
      var li = 0;
      var rot = setInterval(function () {
        if (failed || siteReady) return;
        li = (li + 1) % LONG_STEPS.length;
        setStatus(LONG_STEPS[li]);
      }, 3800);
      function settle() {
        clearInterval(rot);
        if (lastTick) { lastTick.classList.remove('pulse'); lastTick.classList.add('done'); }
      }
      
      var timer = new Promise(function (res) { setTimeout(res, FINAL_HOLD_MS); });
      Promise.all([timer, urlPromise]).then(function (vals) {
        settle();
        setStatus('Your site is ready.');

        setTimeout(function () { window.location.assign(vals[1] + (vals[1].indexOf('?') >= 0 ? '&' : '?') + 'built=1'); }, 500);
      }).catch(function (e) {
        settle();
        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();
  }
})();
