
(function () {
  'use strict';
  if (typeof window === 'undefined' || typeof localStorage === 'undefined') return;

  

  
  
  var KILL = false;
  if (KILL) {
    try {
      ['impap', 'impaplog', 'impscene'].forEach(function (k) { localStorage.removeItem(k); });
      for (var i = localStorage.length - 1; i >= 0; i--) {
        var k2 = localStorage.key(i);
        if (k2 && k2.indexOf('imp_tour_') === 0) localStorage.removeItem(k2);
      }
      document.cookie = 'impap=;path=/;max-age=0;samesite=lax';
    } catch (e) {}
    
    try {
      if (/[?&](autopilot|play)=/.test(location.search)) {
        history.replaceState(null, '', location.pathname);
      }
    } catch (e2) {}
    if (window.console) console.log('[autopilot] KILL switch on: run state cleared, nothing will start.');
    return;
  }

  (function trackRecorder() {
    var RQ = new URLSearchParams(location.search).get('record');
    var KEY = 'imptrack', ONK = 'imptrack_on', T0K = 'imptrack_t0';
    if (RQ === '1') {
      try {
        localStorage.setItem(KEY, '[]');
        localStorage.setItem(ONK, '1');
        localStorage.setItem(T0K, String(Date.now()));
      } catch (e) {}
      try { history.replaceState(null, '', location.pathname); } catch (e) {}
    } else if (RQ === 'stop') {
      try { localStorage.removeItem(ONK); } catch (e) {}
      return;
    } else if (RQ === 'dump') {
      try { console.log(localStorage.getItem(KEY) || '[]'); } catch (e) {}
      return;
    }
    var on = false;
    try { on = localStorage.getItem(ONK) === '1'; } catch (e) {}
    if (!on) return;

    

    var LIMIT_MS = 25 * 60 * 1000;
    try {
      var startedAt = parseInt(localStorage.getItem(T0K), 10) || 0;
      if (startedAt && Date.now() - startedAt > LIMIT_MS) {
        localStorage.removeItem(ONK);
        return;
      }
    } catch (e) {}

    

    try { document.cookie = 'impap=1;path=/;max-age=7200;samesite=lax'; } catch (eRc) {}

    var t0 = 0;
    try { t0 = parseInt(localStorage.getItem(T0K), 10) || Date.now(); } catch (e) { t0 = Date.now(); }
    var buf = [];
    try { buf = JSON.parse(localStorage.getItem(KEY) || '[]'); } catch (e) { buf = []; }

    var now = function () { return Date.now() - t0; };
    var flushT = null;
    
    function mergeInto(mine) {
      var stored = [];
      try { stored = JSON.parse(localStorage.getItem(KEY) || '[]'); } catch (e) { stored = []; }
      if (!stored.length) return mine;
      var seen = {}, all = stored.concat(mine), out = [];
      for (var i = 0; i < all.length; i++) {
        var e = all[i];

        var k = e.t + '|' + e.k + '|' + (e.x || '') + ',' + (e.y || '') + '|'
              + (e.f || '') + '|' + (e.p || e.sel || e.key || '');
        if (seen[k]) continue;
        seen[k] = 1;
        out.push(e);
      }
      out.sort(function (a, b) { return a.t - b.t; });
      return out;
    }
    function flush() {
      clearTimeout(flushT);
      flushT = setTimeout(function () {
        try {
          buf = mergeInto(buf);
          localStorage.setItem(KEY, JSON.stringify(buf.slice(-6000)));
        } catch (e) {}
      }, 400);
    }
    function push(rec) { buf.push(rec); flush(); }

    push({ t: now(), k: 'nav', p: location.pathname });

    function selectorFor(el) {
      if (!el || el === document.body || el.nodeType !== 1) return '';
      if (el.id && !/^\d|cs-|imp-el-/.test(el.id)) return '#' + el.id;
      var parts = [];
      for (var n = el, depth = 0; n && n.nodeType === 1 && n !== document.body && depth < 5; n = n.parentElement, depth++) {
        var seg = n.tagName.toLowerCase();
        var cls = (n.getAttribute('class') || '').trim().split(/\s+/)
          .filter(function (c) { return c && !/^(is-|in$|on$|active|hover)/.test(c) && !/\d{4,}/.test(c); });
        if (cls.length) { seg += '.' + cls.slice(0, 2).join('.'); }
        else if (n.parentElement) {
          var sibs = Array.prototype.filter.call(n.parentElement.children, function (x) { return x.tagName === n.tagName; });
          if (sibs.length > 1) seg += ':nth-of-type(' + (sibs.indexOf(n) + 1) + ')';
        }
        parts.unshift(seg);
        try { if (document.querySelectorAll(parts.join(' > ')).length === 1) break; } catch (e) {}
      }
      return parts.join(' > ');
    }

    var lastMove = 0;
    document.addEventListener('mousemove', function (e) {
      var t = now();
      if (t - lastMove < 45) return;              
      lastMove = t;
      push({ t: t, k: 'm',
             x: +(e.clientX / Math.max(1, window.innerWidth)).toFixed(4),
             y: +(e.clientY / Math.max(1, window.innerHeight)).toFixed(4) });
    }, { passive: true });

    var lastScroll = 0;
    window.addEventListener('scroll', function () {
      var t = now();
      if (t - lastScroll < 45) return;
      lastScroll = t;
      var max = Math.max(1, document.documentElement.scrollHeight - window.innerHeight);
      push({ t: t, k: 's', f: +(window.scrollY / max).toFixed(5) });
    }, { passive: true });

    document.addEventListener('click', function (e) {
      push({ t: now(), k: 'c', sel: selectorFor(e.target),
             x: +(e.clientX / Math.max(1, window.innerWidth)).toFixed(4),
             y: +(e.clientY / Math.max(1, window.innerHeight)).toFixed(4),
             txt: (e.target.textContent || '').trim().slice(0, 30) });
    }, true);

    document.addEventListener('keydown', function (e) {
      
      if (e.key === '`' || (e.key >= '1' && e.key <= '9' && (e.ctrlKey || e.altKey))) {
        var tag = e.key === '`' ? '' : e.key;
        var max = Math.max(1, document.documentElement.scrollHeight - window.innerHeight);
        var near = '';
        try {
          var hs = document.querySelectorAll('h1,h2,h3,.impulse-kinetic-block');
          for (var i = 0; i < hs.length; i++) {
            var r = hs[i].getBoundingClientRect();
            if (r.top < window.innerHeight * 0.6) near = (hs[i].textContent || '').trim().slice(0, 48);
          }
        } catch (err) {}
        push({ t: now(), k: 'mark', tag: tag,
               f: +(window.scrollY / max).toFixed(4), p: location.pathname, near: near });
        try {
          var fl = document.createElement('div');
          fl.textContent = tag ? ('MARK ' + tag) : 'MARK';
          fl.style.cssText = 'position:fixed;left:50%;top:12px;transform:translateX(-50%);z-index:2147483647;'
            + 'background:#c0392b;color:#fff;font:700 12px/1 Arial,sans-serif;padding:6px 12px;border-radius:4px;'
            + 'pointer-events:none;letter-spacing:1px';
          document.body.appendChild(fl);
          setTimeout(function () { fl.remove(); }, 700);
        } catch (err) {}
        return;
      }
      if (e.key && e.key.length === 1) return;    
      if (e.key === 'Enter' || e.key === 'Tab') push({ t: now(), k: 'key', key: e.key });
    }, true);

    window.addEventListener('beforeunload', function () {
      try { localStorage.setItem(KEY, JSON.stringify(mergeInto(buf).slice(-6000))); } catch (e) {}
    });

    
    
    var b = null;
    var upT = null, upN = 0;
    function upload() {
      clearTimeout(upT);
      upT = setTimeout(function () {
        try {
          buf = mergeInto(buf);            
          fetch('/api/instinctor/v1/track/save', {
            method: 'POST', headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ track: buf })
          }).then(function () { upN = buf.length; }).catch(function () {});
        } catch (e) {}
      }, 1500);
    }
    setInterval(function () {
      if (now() > LIMIT_MS) {                       
        try { localStorage.removeItem(ONK); } catch (e) {}
        if (b && b.parentNode) b.textContent = 'REC ENDED';
        return;
      }
      if (buf.length !== upN) upload();
    }, 4000);
    window.addEventListener('beforeunload', function () {
      try {
        navigator.sendBeacon('/api/instinctor/v1/track/save',
          new Blob([JSON.stringify({ track: buf })], { type: 'application/json' }));
      } catch (e) {}
    });

    b = document.createElement('div');
    b.textContent = 'REC';
    b.style.cssText = 'position:fixed;left:8px;top:8px;z-index:2147483647;background:#c0392b;color:#fff;'
      + 'font:700 11px/1 Arial,sans-serif;letter-spacing:1px;padding:5px 8px;border-radius:3px;'
      + 'pointer-events:none;opacity:0.85';
    (document.body || document.documentElement).appendChild(b);
    var n0 = buf.length;
    setInterval(function () { b.textContent = 'REC ' + Math.round(now() / 1000) + 's / ' + (buf.length - n0); }, 1000);
  })();

  

  
  
  var WAVES = {
    instudio: [
      { n: 'Velvet & Vine', t: 'Hair salon doing cuts, color, balayage and blowouts', c: 'Austin', s: 'velvet-and-vine', e: '/instudio', a: '2210 South Lamar Blvd' },
      { n: 'Polished & Co', t: 'Nail studio doing gel manicures, extensions and custom nail art', c: 'Denver', s: 'polished-and-co', e: '/instudio', a: '1440 Larimer Street' },
      { n: 'Fade District', t: 'Barbershop doing classic cuts, skin fades and hot towel shaves', c: 'Chicago', s: 'fade-district', e: '/instudio', a: '1122 North Milwaukee Avenue' },
      { n: 'Still Waters Spa', t: 'Day spa offering facials, body treatments and relaxation massage', c: 'Portland', s: 'still-waters-spa', e: '/instudio', a: '834 NW 23rd Avenue' },
      { n: 'Arch & Ink', t: 'Brow studio doing lamination, microblading and lash lifts', c: 'Miami', s: 'arch-and-ink', e: '/instudio', a: '2740 Coral Way' },
      { n: 'Blush & Bloom', t: 'Makeup studio for weddings, events and photo shoots', c: 'Nashville', s: 'blush-and-bloom', e: '/instudio', a: '509 Church Street' },
      { n: 'Wink Lash Bar', t: 'Lash studio doing classic and volume extensions and lash lifts', c: 'Scottsdale', s: 'wink-lash-bar', e: '/instudio', a: '7014 East Camelback Road' },
      { n: 'Golden Hour Tan', t: 'Tanning salon with modern beds and spray tans for every skin tone', c: 'San Diego', s: 'golden-hour-tan', e: '/instudio', a: '3985 Fifth Avenue' },
      { n: 'Bare Method', t: 'Waxing studio doing full body waxing and smooth skin care', c: 'Charlotte', s: 'bare-method', e: '/instudio', a: '1600 East Boulevard' },
    ],
    instructor: [
      { n: 'Chord & Note', t: 'Guitar lessons for kids and adults, beginner to advanced', c: 'Nashville', s: 'chord-and-note', e: '/instructor', a: '118 16th Avenue South' , sq: 'guitar lessons near me', staff: 'solo', cq: 'Do you teach beginners, and do you have Saturday slots?', on: 'Daniel Reyes' },
      { n: 'Ivory Keys Studio', t: 'Piano lessons for all ages, classical and modern styles', c: 'Boston', s: 'ivory-keys-studio', e: '/instructor', a: '286 Newbury Street' },
      { n: 'Iron Tiger Dojo', t: 'Karate school teaching kids and adults, discipline and self-defense', c: 'Phoenix', s: 'iron-tiger-dojo', e: '/instructor', a: '4145 North 32nd Street' },
      { n: 'Steady Roots Yoga', t: 'Yoga studio with small classes, beginners welcome, all levels', c: 'Boulder', s: 'steady-roots-yoga', e: '/instructor', a: '1738 Pearl Street' },
      { n: 'Bright Path Tutoring', t: 'Tutoring service for math, reading and test prep, all grades', c: 'Madison', s: 'bright-path-tutoring', e: '/instructor', a: '702 State Street' , sq: 'online math tutor for algebra', staff: 'solo', cq: 'Can you help a 7th grader with algebra twice a week?', on: 'Alison Park' },
      { n: 'Clearway Driving', t: 'Driving school teaching new drivers, road test prep and refreshers', c: 'Boise', s: 'clearway-driving', e: '/instructor', a: '1015 West Main Street' , sq: 'driving school near me', staff: 'solo', cq: 'How many lessons does a first time driver usually need?', on: 'Tom Berrigan' },
    ],
    installer: [
      { n: 'Northwind Comfort', t: 'HVAC company installing and repairing heating and cooling systems', c: 'Minneapolis', s: 'northwind-comfort', e: '/installer', a: '2818 Hennepin Avenue', j: 'Furnace is 20 years old and struggling, want a quote on a replacement.' , sq: 'furnace repair near me', staff: 'small', cq: 'How soon can you look at a furnace that will not start?' },
      { n: 'True Level Plumbing', t: 'Plumbing company fixing leaks, drains, water heaters and repipes', c: 'Dallas', s: 'true-level-plumbing', e: '/installer', a: '3699 McKinney Avenue', j: 'Water heater is leaking, probably needs a replacement this week.' , sq: 'emergency plumber near me', staff: 'small', cq: 'My water heater is leaking. Can someone come today?' },
      { n: 'Amp & Ohm Electric', t: 'Licensed electricians doing panels, wiring, lighting and EV chargers', c: 'Seattle', s: 'amp-and-ohm', e: '/installer', a: '1916 Pike Place', j: 'Need an EV charger installed in the garage, panel might need an upgrade.' , sq: 'electrician near me', staff: 'small', cq: 'Do you install EV chargers, and do you handle the permit?' },
      { n: 'Ridgeline Roofing', t: 'Roofing company doing repairs, replacements and storm damage work', c: 'Tampa', s: 'ridgeline-roofing', e: '/installer', a: '1600 East 8th Avenue', j: 'Lost some shingles in the last storm, would like an inspection and quote.' , sq: 'roof repair near me', staff: 'small', cq: 'We lost shingles in the storm. Do you do free inspections?' },
      { n: 'Fresh Coat Painting', t: 'Painting company for interiors and exteriors, homes and offices', c: 'Atlanta', s: 'fresh-coat-painting', e: '/installer', a: '675 Ponce De Leon Avenue', j: 'Want the living room and two bedrooms repainted before we move in.' },
      { n: 'Evergreen Lawns', t: 'Landscaping company doing lawn care, planting and yard cleanups', c: 'Raleigh', s: 'evergreen-lawns', e: '/installer', a: '410 Glenwood Avenue', j: 'Backyard needs a full cleanup and new sod, roughly half an acre.' },
      { n: 'Spotless Crew', t: 'Cleaning company for homes and offices, weekly and one-time deep cleans', c: 'Columbus', s: 'spotless-crew', e: '/installer', a: '641 North High Street', j: 'Looking for a deep clean before listing the house, three bedrooms.' , sq: 'house cleaning service near me', staff: 'small', cq: 'What does a deep clean for a 3 bedroom house cost?' },
      { n: 'Hartley & Sons', t: 'Handyman services for repairs, assembly and small home projects', c: 'St Louis', s: 'hartley-and-sons', e: '/installer', a: '4204 Manchester Avenue', j: 'Have a list of small fixes: a door, two shelves and a leaky faucet.' , sq: 'handyman near me', staff: 'small', cq: 'Can you mount a 65 inch TV on drywall this week?' },
      { n: 'Keyway Locksmith', t: 'Locksmith doing lockouts, rekeying and smart lock installs', c: 'Las Vegas', s: 'keyway-locksmith', e: '/installer', a: '1120 South Main Street', j: 'Just bought a house, want every lock rekeyed and a smart lock on the front.' },
      { n: 'BrightJet Washing', t: 'Pressure washing driveways, siding, decks and storefronts', c: 'Charlotte', s: 'brightjet-washing', e: '/installer', a: '2000 South Boulevard', j: 'Driveway and back deck need a good wash before a family party.' },
      { n: 'SunSide Solar', t: 'Solar installation company for homes, panels and battery backup', c: 'San Diego', s: 'sunside-solar', e: '/installer', a: '2820 Historic Decatur Road', j: 'Interested in panels and a battery, average bill is around 220 a month.' },
      { n: 'Haul Away Bros', t: 'Junk removal and hauling for homes, garages and cleanouts', c: 'Houston', s: 'haul-away-bros', e: '/installer', a: '2410 Washington Avenue', j: 'Garage full of old furniture and boxes, need it cleared this weekend.' },
      { n: 'Groundbreak Excavation', t: 'Excavation and grading for driveways, pads and drainage', c: 'Boise', s: 'groundbreak-excavation', e: '/installer', a: '1505 West Grove Street', j: 'Need a pad graded for a 30 by 40 shop and better drainage out back.' },
      { n: 'Solid Pour Concrete', t: 'Concrete driveways, patios and foundations poured and finished right', c: 'Omaha', s: 'solid-pour-concrete', e: '/installer', a: '1120 Howard Street', j: 'Want a quote on a new driveway, the old one is cracked through.' },
      { n: 'Blacktop Brothers', t: 'Asphalt paving and sealcoating for driveways and small lots', c: 'Cleveland', s: 'blacktop-brothers', e: '/installer', a: '2058 East 4th Street', j: 'Parking area for six cars needs repaving and striping.' },
      { n: 'Torchline Welding', t: 'Mobile welding and metal fabrication for gates, rails and repairs', c: 'Tulsa', s: 'torchline-welding', e: '/installer', a: '324 East 3rd Street', j: 'Driveway gate hinge cracked, needs welding on site.' },
      { n: 'TearDown Pros', t: 'Demolition for interiors, garages and small structures, debris hauled', c: 'Detroit', s: 'teardown-pros', e: '/installer', a: '1420 Washington Blvd', j: 'Old detached garage needs to come down and get hauled away.' },
      { n: 'Swift Movers', t: 'Moving company for homes and apartments, local and long distance', c: 'Austin', s: 'swift-movers', e: '/installer', a: '979 Springdale Road', j: 'Moving a two bedroom apartment across town at the end of the month.' },
    ],
    ingine: [
      { n: 'Torque & Tune', t: 'Auto repair shop doing diagnostics, brakes, oil changes and tires', c: 'Detroit', s: 'torque-and-tune', e: '/ingine', a: '2934 Russell Street', j: 'Check engine light is on and the brakes squeal, need a look this week.' },
      { n: 'Hookline Towing', t: '24 hour towing and roadside assistance, jump starts and lockouts', c: 'Memphis', s: 'hookline-towing', e: '/ingine', a: '409 South Main Street', j: 'Car will not start in my driveway, need a tow to a shop.' },
      { n: 'Mirror Finish', t: 'Car detailing studio doing interior deep cleans and ceramic coating', c: 'Orlando', s: 'mirror-finish', e: '/ingine', a: '2417 East Central Blvd', j: 'Want a full interior detail and ceramic coating on a black SUV.' },
    ],
    other: [
      { n: 'Kneaded Relief', t: 'Licensed massage therapist, deep tissue, sports and prenatal massage', c: 'Madison', s: 'kneaded-relief', e: '/make-a-site', a: '316 West Washington Avenue' , sq: 'massage therapist near me', staff: 'solo', cq: 'Do you do prenatal massage, and what does a session cost?' },
      { n: 'Align Physical Therapy', t: 'Physical therapy clinic helping with recovery, pain and mobility', c: 'Omaha', s: 'align-physical', e: '/make-a-site', a: '4915 Dodge Street' },
      { n: 'Bright Smile Dental', t: 'Family dentist, cleanings, fillings, whitening and gentle care', c: 'Tucson', s: 'bright-smile-dental', e: '/make-a-site', a: '2502 East Speedway Blvd' },
      { n: 'The Tidy Pup', t: 'Dog grooming studio, baths, trims and nail care for all breeds', c: 'Sacramento', s: 'the-tidy-pup', e: '/make-a-site', a: '1801 L Street' },
      { n: 'Happy Trails Walks', t: 'Dog walking and pet sitting while you work or travel', c: 'Kansas City', s: 'happy-trails-walks', e: '/make-a-site', a: '4111 Pennsylvania Avenue' },
      { n: 'Blackline Car Service', t: 'Private chauffeur and airport car service, clean cars, on time', c: 'Newark', s: 'blackline-cars', e: '/make-a-site', a: '744 Broad Street' },
      { n: 'Press & Fold', t: 'Dry cleaning and wash and fold laundry with quick turnaround', c: 'Baltimore', s: 'press-and-fold', e: '/make-a-site', a: '1035 Light Street' },
      { n: 'Golden Hour Photo', t: 'Wedding and portrait photographer, natural light and honest prices', c: 'Savannah', s: 'golden-hour-photo', e: '/make-a-site', a: '24 East Broughton Street', sq: 'wedding photographer near me', staff: 'solo', cq: 'Do you shoot weddings, and what do your packages start at?', j: 'Wedding on October 18, about six hours of coverage. What would it cost?', on: 'Sarah Whitfield' },

      

      

      

      

      

      { n: 'Field & Main', t: 'Print and sign shop doing business cards, banners, yard signs, vehicle lettering, plaques and custom orders for local businesses', c: 'Madison', s: 'field-and-main', e: '/make-a-site', a: '318 East Wilson Street', sq: 'print shop near me', staff: 'small', cq: 'Can you print 500 business cards by Friday?', j: 'Three banners for a weekend market stall, plus 500 business cards. What would that come to?' },

      

      { n: 'True North Auto', t: 'Auto repair shop doing brakes, oil changes, tires, engine diagnostics and suspension work', c: 'Columbus', s: 'true-north-auto', e: '/make-a-site', a: '412 East Rich Street', sq: 'auto repair near me', staff: 'small', cq: 'How much is a front brake job on a 2019 CR-V?', j: 'Front brakes grinding on a 2019 Honda CR-V. What would pads and rotors come to?' },
    ],
  };

  
  function _pick(w, slugs) {
    return slugs.map(function (s) {
      for (var i = 0; i < WAVES[w].length; i++) if (WAVES[w][i].s === s) return WAVES[w][i];
      return null;
    }).filter(Boolean);
  }

  WAVES.flagship = [].concat(_pick('other', ['field-and-main']));
  
  WAVES.auto = [].concat(_pick('other', ['true-north-auto']));
  WAVES.wave1 = [].concat(
    _pick('other', ['golden-hour-photo']),
    _pick('installer', ['hartley-and-sons', 'true-level-plumbing', 'amp-and-ohm',
                        'northwind-comfort', 'spotless-crew', 'ridgeline-roofing']),
    _pick('instructor', ['chord-and-note', 'bright-path-tutoring', 'clearway-driving'])
  );

  var QUEUE = [].concat(WAVES.instudio, WAVES.instructor, WAVES.installer, WAVES.ingine, WAVES.other);

  var KEY = 'impap';
  function load() { try { return JSON.parse(localStorage.getItem(KEY) || 'null'); } catch (e) { return null; } }
  function save(s) { try { localStorage.setItem(KEY, JSON.stringify(s)); } catch (e) {} }
  function stop() { try { localStorage.removeItem(KEY); } catch (e) {} }

  var qs = new URLSearchParams(location.search);

  

  
  var AP_MAILBOX = 'sergey.tiden';
  function apEmail(slug) { return AP_MAILBOX + '+ap-' + slug + '@gmail.com'; }

  var ap = qs.get('autopilot');
  if (ap === 'stop') { stop(); return; }
  if (ap === '1' || ap === 'go' || (ap && WAVES[ap])) {
    var wq = (ap && WAVES[ap]) ? WAVES[ap] : QUEUE;

    
    var fromN = parseInt(qs.get('from'), 10);
    var startI = (fromN > 0 && fromN <= wq.length) ? fromN - 1 : 0;

    

    
    var toN = parseInt(qs.get('to'), 10);
    if (toN > 0 && toN <= wq.length && toN >= startI + 1) {
      wq = wq.slice(startI, toN);
      startI = 0;
    }
    var st = { on: 1, i: startI, phase: 'home', warm: 1, q: wq };
    if (qs.get('captions') === '1') st.cap = 1;

    

    

    st.nb = (qs.get('beats') || '').toLowerCase() === 'off' ? 1 : 0;

    st.intro = (qs.get('intro') || '').toLowerCase() === 'search' ? 1 : 0;

    

    st.wm = Math.max(0, parseInt(qs.get('warm'), 10) || 14);
    var dm = (qs.get('dash') || 'full').toLowerCase();
    st.dm = (dm === 'short' || dm === 'off') ? dm : 'full';

    
    
    if ((qs.get('open') || '').toLowerCase() === 'entry') {
      st.oe = 1;                          
      st.phase = 'entry';
      save(st);
      location.href = (st.q[st.i] && st.q[st.i].e) || '/make-a-site';
      return;
    }
    save(st);
    location.href = '/';
    return;
  }

  var S = load();
  if (!S || !S.on || !S.q || S.i >= S.q.length) return;
  var CUR = S.q[S.i];

  

  

  try { document.cookie = 'impap=1;path=/;max-age=7200;samesite=lax'; } catch (eCk) {}
  (function hideScrollbars() {
    if (document.getElementById('impap-noscroll')) return;
    var st = document.createElement('style');
    st.id = 'impap-noscroll';
    st.textContent = 'html{scrollbar-width:none;-ms-overflow-style:none}'
      + 'body{scrollbar-width:none;-ms-overflow-style:none}'
      + '::-webkit-scrollbar{width:0!important;height:0!important;display:none!important}';
    (document.head || document.documentElement).appendChild(st);
  })();

  

  

  function sleep(ms) { return new Promise(function (r) { setTimeout(r, ms); }); }

  function log(msg) {
    try {
      var L = JSON.parse(localStorage.getItem('impaplog') || '[]');
      L.push(new Date().toISOString().slice(11, 19) + '  ' + location.pathname.slice(0, 28) + '  ' + msg);
      localStorage.setItem('impaplog', JSON.stringify(L.slice(-200)));
    } catch (e) {}
  }
  function jitter(base) { return base + Math.random() * base * 0.7; }

  
  var _cur = null;
  function cursor() {
    if (_cur && _cur.isConnected) return _cur;

    
    
    try {
      var stale = document.querySelectorAll('#impap-cur');
      for (var s = 0; s < stale.length; s++) stale[s].remove();
    } catch (e) {}
    var st = document.createElement('style');
    st.textContent = '#impap-cur{position:fixed;z-index:2147483647;width:19px;height:19px;'
      + 'pointer-events:none;transition:none;left:60%;top:70%;visibility:hidden}'
      + '#impap-cur svg{display:block;filter:drop-shadow(0 1px 1.5px rgba(0,0,0,0.5))}'
      + '.impap-ring{position:fixed;z-index:2147483646;width:14px;height:14px;margin:-7px 0 0 -7px;border-radius:50%;'
      + 'border:3px solid #e0322c;pointer-events:none;animation:impapPulse 700ms ease-in-out forwards}'
      + '@keyframes impapPulse{0%{transform:scale(0.5);opacity:0.95}70%{transform:scale(2.6);opacity:0.55}100%{transform:scale(3.4);opacity:0}}';
    document.head.appendChild(st);
    var d = document.createElement('div');
    d.id = 'impap-cur';

    
    d.innerHTML = '<svg width="19" height="19" viewBox="0 0 24 24">'
      + '<path d="M5.5 3.2v16.2l4.1-4.0 2.4 5.6 2.6-1.1-2.4-5.5 5.8-0.6z" '
      + 'fill="#fff" stroke="#1d2327" stroke-width="1.4" stroke-linejoin="round"/></svg>';
    document.body.appendChild(d);
    _cur = d;
    return d;
  }
  var _curTok = 0;
  function cursorTo(el, ms) {
    return new Promise(function (res) {

      
      
      var r = el.getBoundingClientRect();

      if (!r.width && !r.height) return res();
      var c = cursor();
      var tok = ++_curTok;

      var tx = r.left + r.width / 2 - 4, ty = r.top + r.height / 2 - 4;
      var fx = parseFloat(c.style.left) || window.innerWidth * 0.6;
      var fy = parseFloat(c.style.top) || window.innerHeight * 0.7;
      var t0 = performance.now(), dur = ms || Math.min(900, Math.max(450, Math.hypot(tx - fx, ty - fy) / 1.4));

      

      
      c.style.visibility = 'visible';   
      var settledOnce = false;
      var finish = function () { if (settledOnce) return; settledOnce = true; c.style.left = tx + 'px'; c.style.top = ty + 'px'; res(); };
      setTimeout(finish, dur + 400);
      (function step(now) {
        if (tok !== _curTok) return finish();   
        var k = Math.min(1, (now - t0) / dur), e = ease(k);
        var cx = fx + (tx - fx) * e, cy = fy + (ty - fy) * e;
        c.style.left = cx + 'px';
        c.style.top = cy + 'px';

        

        
        
        try {
          var ev = new MouseEvent('mousemove', { bubbles: true, clientX: cx, clientY: cy, view: window });
          var under = document.elementFromPoint(cx, cy);
          (under || document).dispatchEvent(ev);
          window.dispatchEvent(new MouseEvent('mousemove', { bubbles: false, clientX: cx, clientY: cy, view: window }));
        } catch (err) {}
        k < 1 ? requestAnimationFrame(step) : finish();
      })(t0);
    });
  }
  function cursorToXY(x, y, ms) {
    var d = document.createElement('div');
    d.style.cssText = 'position:fixed;left:' + x + 'px;top:' + y + 'px;width:1px;height:1px;pointer-events:none';
    document.body.appendChild(d);
    return cursorTo(d, ms).then(function () { d.remove(); });
  }

  

  function searchIntro(q, leadMs) {
    if (!q) return Promise.resolve();
    return new Promise(function (done) {
      var wrap = document.createElement('div');
      wrap.id = 'impap-intro';
      wrap.innerHTML =
        '<div class="impap-intro-in">'
        + '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" '
        + 'stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">'
        + '<circle cx="11" cy="11" r="8"></circle><path d="m21 21-4.3-4.3"></path></svg>'
        + '<span class="impap-intro-q"></span><i class="impap-intro-caret"></i>'
        + '</div>';
      var st = document.createElement('style');
      st.textContent =
        '#impap-intro{position:fixed;inset:0;z-index:2147483000;background:#f2f3f5;'
        + 'display:flex;align-items:center;justify-content:center;'
        + 'transition:opacity 620ms ease-in-out}'
        + '#impap-intro.out{opacity:0}'
        + '#impap-intro .impap-intro-in{display:flex;align-items:center;gap:14px;width:min(620px,86vw);'
        + 'background:#fff;border:1px solid #e0e0e0;border-radius:999px;padding:18px 26px;'
        + 'box-shadow:0 2px 10px rgba(0,0,0,0.06);font:400 20px/1.2 -apple-system,BlinkMacSystemFont,'
        + '"Segoe UI",Roboto,Arial,sans-serif;color:#1d2327}'
        + '#impap-intro svg{width:22px;height:22px;color:#999;flex:0 0 auto}'
        + '#impap-intro .impap-intro-caret{width:1.5px;height:24px;background:#1d2327;'
        + 'animation:impapCaret 1s steps(1) infinite}'
        + '@keyframes impapCaret{0%,49%{opacity:1}50%,100%{opacity:0}}';
      document.head.appendChild(st);
      document.body.appendChild(wrap);

      var field = wrap.querySelector('.impap-intro-in');
      var out = wrap.querySelector('.impap-intro-q');

      (async function () {

        
        await sleep(leadMs || 900);
        await cursorTo(field, 800);          
        await sleep(320);
        for (var i = 0; i < q.length; i++) {
          out.textContent = q.slice(0, i + 1);
          
          await sleep(q[i] === ' ' ? 120 : 52 + Math.floor(Math.random() * 58));
        }
        await sleep(1500);                   
        wrap.classList.add('out');
        await sleep(660);
        wrap.remove();
        st.remove();
        done();
      })();
    });
  }

  function clickPulse() {
    var c = cursor();
    var ring = document.createElement('div');
    ring.className = 'impap-ring';
    
    ring.style.left = (parseFloat(c.style.left) + 3) + 'px';
    ring.style.top = (parseFloat(c.style.top) + 3) + 'px';
    document.body.appendChild(ring);
    setTimeout(function () { ring.remove(); }, 750);
  }
  function cursorClick(el) {
    return cursorTo(el).then(function () { clickPulse(); return sleep(260); });
  }

  
  
  var CAPS = {
    entry:     ['START',          'Type what you do. That is the whole setup.'],
    hero:      ['YOUR SITE',      'Built for your business, not a template.'],
    services:  ['SERVICES',       'Your menu and prices. Edit anything.'],
    work:      ['YOUR WORK',      'Industry photos now, your photos later.'],
    reviews:   ['REVIEWS',        'Request them from clients by text.'],
    gift:      ['SECTIONS',       'Hide what you do not need. One click.'],
    hours:     ['HOURS AND MAP',  'Type your address. The map follows.'],
    booking:   ['BOOKING',        'Clients book right on your site.'],
    quote:     ['QUOTES',         'Job requests land in your dashboard.'],
    swatch:    ['YOUR COLORS',    'One click recolors everything.'],
    publish:   ['PUBLISH FREE',   'An email, a phone, your address. No card.'],
    dashboard: ['YOUR DASHBOARD', 'Bookings, messages, edits. One place.'],

    'd:edit':      ['EDIT YOUR SITE',  'Change any text or photo, on the page itself.'],
    'd:bookings':  ['BOOKINGS',        'Every appointment, and who booked it.'],
    'd:quotes':    ['QUOTES',          'Job requests, priced and sent from here.'],
    'd:chat':      ['MESSAGES',        'Every conversation your site collected.'],
    'd:clients':   ['CLIENTS',         'Who got in touch, and when.'],
    'd:reviews':   ['REVIEWS',         'Ask by text, land on your review page.'],
    'd:settings':  ['SETTINGS',        'Hours, address, phone. Set once.'],
    'd:team':      ['YOUR TEAM',       'Staff, and what each of them does.'],
    'd:qr':        ['YOUR QR CODE',    'For the window, the van, the card.'],
    'd:assistant': ['SMART CHAT',      'Answers your customers day and night.'],
    'd:help':      ['HELP',            'Plain answers, no jargon.'],
    live:      ['LIVE',           'Your own address on instinctor.com.']
  };
  var _capEl = null;
  function captionEl() {
    if (_capEl) return _capEl;
    var st = document.createElement('style');
    st.textContent = '#impap-cap{position:fixed;left:28px;bottom:28px;z-index:2147483200;max-width:380px;'
      + 'background:rgba(14,15,18,0.85);border-radius:12px;padding:13px 17px;pointer-events:none;'
      + 'opacity:0;transform:translateY(10px);transition:opacity 300ms ease-in-out,transform 300ms ease-in-out}'
      + '#impap-cap.in{opacity:1;transform:none}'
      + '#impap-cap .l{font:700 13px/1 Arial,Helvetica,sans-serif;letter-spacing:3px;color:#fff;margin:0 0 6px}'
      + '#impap-cap .t{font:400 15px/1.4 Arial,Helvetica,sans-serif;color:rgba(255,255,255,0.85);margin:0}'
      + '@media (max-width:600px){#impap-cap{left:14px;right:14px;bottom:90px;max-width:none}}';
    document.head.appendChild(st);
    var d = document.createElement('div');
    d.id = 'impap-cap';
    d.innerHTML = '<p class="l"></p><p class="t"></p>';
    document.body.appendChild(d);
    _capEl = d;
    return d;
  }
  function caption(key) {
    if (!S || !S.cap) return;
    var c = CAPS[key];
    if (!c) { captionHide(); return; }
    var el = captionEl();
    el.querySelector('.l').textContent = c[0];
    el.querySelector('.t').textContent = c[1];
    el.classList.add('in');
  }
  function captionHide() { if (_capEl) _capEl.classList.remove('in'); }

  
  function swatchPlay() {
    var chips = document.querySelectorAll('.imp-color-chip');
    if (chips.length < 2) return sleep(0);
    caption('swatch');
    var a = chips[1], b = chips[2] || chips[1], orig = chips[0];

    
    
    var t0 = performance.now();
    return cursorClick(a)
      .then(function () { a.click(); return sleep(1100); })
      .then(function () { return cursorClick(b); })
      .then(function () { b.click(); return sleep(1200); })
      .then(function () { return cursorClick(orig); })
      .then(function () { orig.click(); return sleep(900); })
      .then(function () {
        log('swatch played ' + Math.round(performance.now() - t0) + 'ms, back on the generated palette');
      });
  }

  
  
  function type(el, text) {
    return new Promise(function (res) {
      el.focus();
      el.value = '';
      var i = 0;
      (function step() {
        if (i >= text.length) { el.dispatchEvent(new Event('change', { bubbles: true })); return res(); }
        el.value += text[i++];
        el.dispatchEvent(new Event('input', { bubbles: true }));
        setTimeout(step, jitter(42));
      })();
    });
  }

  
  function ease(t) { return -(Math.cos(Math.PI * t) - 1) / 2; }
  function glide(to, ms) {
    return new Promise(function (res) {
      var from = window.scrollY, d = to - from, t0 = performance.now();
      (function step(now) {
        var k = Math.min(1, (now - t0) / ms);
        window.scrollTo({ top: from + d * ease(k), behavior: 'instant' });
        k < 1 ? requestAnimationFrame(step) : res();
      })(t0);
    });
  }

  

  

  var TIMING = { speed: 260, liveSpeed: 175, dwell: 3.0, hero: 4.5, services: 5.5, work: 5.0, reviews: 4.0, hours: 3.0, booking: 6.0, quote: 6.0, gift: 0.2, team: 0.2 };
  var T = (S && S.t) ? Object.assign({}, TIMING, S.t) : TIMING;
  function sectionKind(el, idx) {
    if (idx === 0) return 'hero';
    function has(sel) { try { return !!el.querySelector(sel); } catch (e) { return false; } }
    if (has('.impulse-booking-block'))   return 'booking';
    if (has('.impulse-estimate-block'))  return 'quote';
    if (has('[class*="impulse-pl-"]'))   return 'services';
    if (has('.impulse-flip-box'))        return 'services';   
    if (has('.impulse-team-block'))      return 'team';
    if (has('.impulse-carousel'))        return 'work';
    if (has('.impulse-grid[data-images-lightbox]')) return 'work';   
    if (has('.impulse-marquee'))         return 'reviews';
    if (has('.imp-hours-rows,.imp-addr-ph')) return 'hours';
    if (/give the gift|gift card/i.test(el.textContent || '')) return 'gift';
    if (/(who (we are|i am)|about)/i.test((el.textContent || '').slice(0, 300))) return 'about';
    if (/how it works|three easy steps|how a job goes/i.test((el.textContent || '').slice(0, 300))) return 'steps';
    if (/why (us|me)/i.test((el.textContent || '').slice(0, 200))) return 'steps';
    return 'dwell';
  }

  
  
  var STOP_BLOCKS = '.impulse-booking-block,.impulse-estimate-block,[class*="impulse-pl-"],'
    + '.impulse-carousel,.impulse-marquee,.impulse-team-block,.impulse-grid,'
    + '.impulse-google-map,.imp-hours-rows,.impulse-reviews-card,.impulse-gallery';
  function isStop(v) {
    if (v.h >= window.innerHeight * 0.3) return true;
    try { return !!v.el.querySelector(STOP_BLOCKS); } catch (e) { return true; }
  }
  function sections() {
    var seen = [];
    return Array.prototype.slice.call(document.querySelectorAll('section.impulse-section'))
      .map(function (s) { var r = s.getBoundingClientRect(); return { el: s, top: r.top + window.scrollY, h: r.height }; })
      .filter(function (v) {
        if (v.h < 40) return false;
        if (!isStop(v)) return false;
        if (seen.some(function (t) { return Math.abs(t - v.top) < 48; })) return false;
        seen.push(v.top); return true;
      })
      .sort(function (a, b) { return a.top - b.top; });
  }
  function centerTarget(sec) {
    var vh = window.innerHeight;
    var max = document.documentElement.scrollHeight - vh;
    var t = sec.h < vh ? sec.top - (vh - sec.h) / 2 : sec.top;
    return Math.max(0, Math.min(t, max));
  }
  
  function centerTargetEl(el) {
    var r = el.getBoundingClientRect();
    return centerTarget({ top: r.top + window.scrollY, h: r.height });
  }
  
  function glideTo(el, ms) {
    return new Promise(function (res) {
      var from = window.scrollY, t0 = performance.now();
      (function step(now) {
        var k = Math.min(1, (now - t0) / ms);
        window.scrollTo({ top: from + (centerTargetEl(el) - from) * ease(k), behavior: 'instant' });
        k < 1 ? requestAnimationFrame(step) : res();
      })(t0);
    });
  }

  

  function scrollFlow(pxPerSec) {
    document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important');
    document.body.style.setProperty('scroll-behavior', 'auto', 'important');
    var maxNow = function () { return Math.max(0, document.documentElement.scrollHeight - window.innerHeight); };

    
    function settled(tries) {
      if (maxNow() > window.innerHeight * 0.6 || tries > 40) return sleep(0);
      return sleep(100).then(function () { return settled(tries + 1); });
    }
    return settled(0).then(function () {
      return new Promise(function (res) {
        var from = window.scrollY, t0 = performance.now();
        var ms = Math.max(9000, (maxNow() - from) / ((pxPerSec || 190) / 1000));
        (function step(now) {
          var k = Math.min(1, (now - t0) / ms);
          window.scrollTo({ top: from + (maxNow() - from) * ease(k), behavior: 'instant' });
          k < 1 ? requestAnimationFrame(step) : res();
        })(t0);
      });
    });
  }

  

  

  

  var SPEED_MULT = {
    hero: 0.6, services: 0.42, work: 0.45, reviews: 0.5, booking: 0.45, quote: 0.45,
    hours: 0.55, about: 0.5, steps: 0.5,
    
    team: 2.0, gift: 2.4, dwell: 2.0
  };
  function scrollThrough() {
    
    document.documentElement.style.setProperty('scroll-behavior', 'auto', 'important');
    document.body.style.setProperty('scroll-behavior', 'auto', 'important');
    document.documentElement.style.setProperty('overflow-anchor', 'none');
    document.body.style.setProperty('overflow-anchor', 'none');
    var plan = sections().map(function (v, i) { return { el: v.el, kind: sectionKind(v.el, i) }; });
    var done = {};                      
    var BASE = T.speed;                 
    return new Promise(function (res) {
      var last = performance.now(), held = false, vel = BASE;
      var pos = window.scrollY, stalled = 0;   
      var tick = function () { setTimeout(function () { frame(performance.now()); }, 16); };
      function frame(now) {
        var dt = Math.min(64, now - last); last = now;
        if (held) { pos = window.scrollY; tick(); return; }
        var max = document.documentElement.scrollHeight - window.innerHeight;
        var y = pos;
        if (y >= max - 2) return res();

        var mid = y + window.innerHeight / 2, cur = null, curIdx = -1;
        for (var i = 0; i < plan.length; i++) {
          var r = plan[i].el.getBoundingClientRect();
          var top = r.top + y;
          if (mid >= top && mid < top + r.height) { cur = plan[i]; curIdx = i; break; }
        }
        var kind = cur ? cur.kind : 'dwell';
        
        var want = BASE * (SPEED_MULT[kind] || 1);
        vel += (want - vel) * Math.min(1, dt / 260);
        pos = Math.min(max, y + vel * dt / 1000);
        window.scrollTo({ top: pos, behavior: 'instant' });

        

        
        
        var real = window.scrollY;
        if (Math.abs(real - pos) > 180) {
          log('scroll desync ' + Math.round(pos - real) + 'px, resyncing');
          pos = real;
          stalled++;

          if (stalled > 90) { log('scroll blocked, ending pass'); return res(); }
        } else { stalled = 0; }

        if (cur && !done[curIdx]) {
          var beat = beatFor(kind, cur.el);
          if (beat) {
            done[curIdx] = 1;
            held = true;
            if (S.phase === 'demo') caption(kind);

            
            var t0b = performance.now();

      
      
      var beatCap = { quote: 16000, booking: 16000, services: 15000, hours: 16000 }[kind] || 4000;
            Promise.race([beat, sleep(beatCap)]).then(function () {
                log(kind + ' beat ' + Math.round(performance.now() - t0b) + 'ms');
                captionHide(); held = false; last = performance.now();
            });
          }
        }
        tick();
      }
      frame(last);
    });
  }

  function beatFor(kind, el) {
    if (S.nb) return null;                          
    var onDemo = S.phase === 'demo';
    var onLive = S.phase === 'live' || S.phase === 'published';

    

    
    if (onDemo) {
      if (kind === 'services') {

        
        
        var steps = [];
        if (!S.swDone && document.querySelectorAll('.imp-color-chip').length >= 2) {
          S.swDone = 1; steps.push(function () { return swatchPlay(); });
        }
        if (!S.flipDone && el.querySelector('.impulse-flip-box')) {
          S.flipDone = 1; steps.push(function () { return flipTease(el); });
        }
        if (!steps.length) return null;
        save(S);
        return steps.reduce(function (p, f) { return p.then(f); }, Promise.resolve());
      }
      if (kind === 'hours' && typeof window.__impapAddress === 'function') return window.__impapAddress(el);
      return null;
    }
    if (onLive) {
      if (kind === 'booking' && typeof window.__impapBooking === 'function') return window.__impapBooking(el);
      if (kind === 'quote' && typeof window.__impapQuote === 'function') return window.__impapQuote(el);
    }
    return null;
  }

  
  
  function flipTease(sec) {
    var boxes = sec.querySelectorAll('.impulse-flip-box');
    if (!boxes.length) return sleep(0);

    

    var seq = new Promise(function (r) {
      try { boxes[0].scrollIntoView({ behavior: 'smooth', block: 'center' }); } catch (e) {}
      setTimeout(r, 900);
    });
    Array.prototype.slice.call(boxes, 0, 2).forEach(function (b) {
      seq = seq.then(function () { return cursorTo(b, 700); })
        .then(function () { b.dispatchEvent(new MouseEvent('mouseenter', { bubbles: true })); return sleep(1500); })
        .then(function () { b.dispatchEvent(new MouseEvent('mouseleave', { bubbles: true })); return sleep(450); });
    });
    return seq;
  }

  function chatDemo() {
    return Promise.race([(async function () {
      var bar = document.getElementById('instinctor-chat-bar');
      var field = document.getElementById('instinctor-ghost-input');
      if (!bar || !field) return;
      caption('chat');
      await cursorClick(bar);
      try { bar.click(); } catch (e) {}
      await sleep(900);
      field = document.getElementById('instinctor-ghost-input');
      if (!field) return;
      var q = CUR.cq || 'Are you available this Saturday, and what would it cost?';
      await cursorTo(field, 600);
      await type(field, q);
      await sleep(400);
      var before = document.querySelectorAll('.instinctor-ghost-bubble.left').length;
      if (window.InstinctorChat && window.InstinctorChat.ghostSend) window.InstinctorChat.ghostSend();
      
      for (var w = 0; w < 36; w++) {
        await sleep(500);
        if (document.querySelectorAll('.instinctor-ghost-bubble.left').length > before) break;
      }
      await sleep(2400);                     
      captionHide();
    })().catch(function () {}), sleep(32000)]);
  }

  

  
  
  function onLoad(fn) {
    if (document.readyState === 'complete') { setTimeout(fn, 0); return; }
    window.addEventListener('load', fn);
  }

  
  
  function rowFlash(row) {
    var st = document.createElement('style');
    st.id = 'impap-rowflash';
    st.textContent =
      '@keyframes impap-land{0%{background:#fff6d8;box-shadow:inset 3px 0 0 #d9a441}'
      + '100%{background:transparent;box-shadow:inset 3px 0 0 rgba(217,164,65,0)}}'
      + '.impap-landed{animation:impap-land 2600ms ease-in-out 1 forwards}';
    document.head.appendChild(st);
    var target = row.closest('tr') || row;
    target.classList.add('impap-landed');
  }

  function smsOverlay() {
    var wrap = document.createElement('div');
    wrap.id = 'impap-sms';
    var biz = CUR.n || 'your business';
    var job = (CUR.j || 'New job request.').slice(0, 92);
    wrap.innerHTML =
      '<div class="impap-phone">'
      + '<div class="impap-phone-top"><span class="impap-ph-time">21:47</span></div>'
      + '<div class="impap-sms-card">'
      +   '<div class="impap-sms-head">Messages <span>now</span></div>'
      +   '<div class="impap-sms-from">' + biz + ' website</div>'
      +   '<div class="impap-sms-body">New quote request from Mark Reynolds (555-120-4118). &quot;' + job + '&quot;</div>'
      + '</div>'
      + '</div>';
    var st = document.createElement('style');
    st.id = 'impap-sms-css';
    st.textContent =
      '#impap-sms{position:fixed;inset:0;z-index:2147483200;background:rgba(14,15,18,0.86);display:flex;'
      + 'align-items:center;justify-content:center;opacity:0;transition:opacity 480ms ease-in-out}'
      + '#impap-sms.in{opacity:1}'
      + '.impap-phone{width:340px;height:640px;border-radius:38px;background:#101216;border:3px solid #2a2e35;'
      + 'box-shadow:0 30px 80px rgba(0,0,0,0.6);position:relative;overflow:hidden;'
      + 'font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Arial,sans-serif}'
      + '.impap-phone-top{height:44px;display:flex;align-items:center;justify-content:center}'
      + '.impap-ph-time{color:#cfd3d9;font-size:14px;font-weight:600;letter-spacing:0.4px}'
      + '.impap-sms-card{margin:10px 12px;background:#1d2127;border-radius:16px;padding:13px 15px;'
      + 'transform:translateY(-16px);opacity:0;transition:transform 520ms ease-in-out,opacity 520ms ease-in-out}'
      + '#impap-sms.in .impap-sms-card{transform:translateY(0);opacity:1;transition-delay:420ms}'
      + '.impap-sms-head{color:#8b929c;font-size:12px;display:flex;justify-content:space-between;margin-bottom:7px}'
      + '.impap-sms-from{color:#fff;font-size:14px;font-weight:700;margin-bottom:4px}'
      + '.impap-sms-body{color:#d7dbe0;font-size:14px;line-height:1.45}';
    document.head.appendChild(st);
    document.body.appendChild(wrap);
    requestAnimationFrame(function () { wrap.classList.add('in'); });
    return sleep(5600).then(function () {
      wrap.classList.remove('in');
      return sleep(520);
    }).then(function () { wrap.remove(); st.remove(); });
  }

  function slate(text, next) {
    var d = document.createElement('div');
    d.style.cssText = 'position:fixed;inset:0;z-index:2147483647;background:#0e0f12;display:flex;' +
      'align-items:center;justify-content:center;color:#fff;font:600 44px/1.2 Arial,Helvetica,sans-serif;' +
      'letter-spacing:0.02em;opacity:0;transition:opacity .4s ease-in-out';
    d.textContent = text;
    document.body.appendChild(d);
    requestAnimationFrame(function () { d.style.opacity = '1'; });
    setTimeout(next, 1700);
  }
  function advance() {
    S.i++;
    if (S.i >= S.q.length) {
      slate('That is all of them.', function () { stop(); });
      return;
    }
    delete S.swDone; delete S.flipDone;
    delete S.dashQ; delete S.dashI;   
    delete S.introPlayed;             
    var nx = S.q[S.i];

    
    
    S.phase = S.oe ? 'entry' : 'home';
    save(S);
    var dest = S.oe ? (nx.e || '/make-a-site') : '/';
    slate(nx.n + ' - ' + nx.t.split(',')[0], function () { location.href = dest; });
  }

  
  
  function typeEditable(el, text) {
    
    el.dispatchEvent(new MouseEvent('mousedown', { bubbles: true, cancelable: true }));
    return sleep(120).then(function () {

      
      try { el.focus(); } catch (e) {}
      return sleep(200);
    }).then(function () {
      return new Promise(function (res) {
        var i = 0;
        (function step() {
          if (i >= text.length) return res();
          i++;
          el.textContent = text.slice(0, i);
          el.dispatchEvent(new Event('input', { bubbles: true }));
          setTimeout(step, jitter(46));
        })();
      });
    }).then(function () { el.blur(); return sleep(400); });
  }
  window.__impapAddress = function (sec) {

    

    
    var ph = sec.querySelector('[data-demo-address]')
          || sec.querySelector('.imp-addr-ph:not([data-demo-hours])');
    if (!ph) return sleep(0);
    var addr = CUR.a || (String(140 + (S.i * 7) % 800) + ' Maple Avenue');

    

    
    
    var mapEl = document.querySelector('.impulse-google-map, iframe[src*="maps.google"]');
    try {
      var aR = ph.getBoundingClientRect(), y = window.scrollY;
      var top = aR.top + y, bot = aR.bottom + y;
      if (mapEl) {
        var mR = mapEl.getBoundingClientRect();
        top = Math.min(top, mR.top + y); bot = Math.max(bot, mR.bottom + y);
      }
      var max = document.documentElement.scrollHeight - window.innerHeight;
      var want = Math.max(0, Math.min(max, (top + bot) / 2 - window.innerHeight / 2));
      window.scrollTo({ top: want, behavior: 'smooth' });
    } catch (e) {}
    return sleep(700)
      .then(function () { return cursorClick(ph); })
      .then(function () { return typeEditable(ph, addr); })
      .then(function () {

        
        ['keydown', 'keypress', 'keyup'].forEach(function (t) {
          ph.dispatchEvent(new KeyboardEvent(t, {
            key: 'Enter', code: 'Enter', keyCode: 13, which: 13, bubbles: true, cancelable: true
          }));
        });
        try { ph.blur(); } catch (e) {}

        

        
        try { if (typeof window.__impSyncMap === 'function') window.__impSyncMap(addr); } catch (e) {}
        return sleep(600);
      })
      .then(function () {

        

        
        return sleep(4200);
      });
  };
  window.__impapBooking = function (sec) {
    var box = sec.querySelector('.impulse-booking-block');
    if (!box) return sleep(0);
    function q(s) { return box.querySelector(s); }

    function waitFor(sel, ms) {
      return new Promise(function (res) {
        var t0 = performance.now();
        (function poll() {
          var found = box.querySelector(sel);
          if (found || performance.now() - t0 > (ms || 6000)) return res(found || null);
          setTimeout(poll, 120);
        })();
      });
    }
    function waitEnabled(el) {

      

      return new Promise(function (res) {
        var t0 = performance.now();
        (function poll() {
          var dim = false;
          try { dim = parseFloat(getComputedStyle(el).opacity) < 0.9; } catch (e) {}
          if ((!el.disabled && !dim) || performance.now() - t0 > 5000) return res();
          setTimeout(poll, 150);
        })();
      });
    }
    function clickIf(el, pause) {

      
      return el ? waitEnabled(el).then(function () { return cursorClick(el); }).then(function () { el.click(); return sleep(pause || 700); }) : sleep(0);
    }

    

    
    var p = waitFor('.ibk-service', 8000).then(function (svc) {
      if (!svc || !svc.options || svc.options.length < 2) return sleep(0);
      return cursorClick(svc).then(function () {
        svc.selectedIndex = 1;
        svc.dispatchEvent(new Event('change', { bubbles: true }));
        return sleep(800);
      });
    });

    

    

    

    function pickDay() {
      var b = box.querySelector('.ibk-cal-grid');
      if (!b) return sleep(0);
      var days = [].slice.call(b.querySelectorAll('button:not([disabled])'));
      if (!days.length) return sleep(0);
      var today = new Date().getDate();
      var ahead = days.filter(function (d) { return parseInt(d.textContent, 10) > today; });
      var order = ahead.concat(days.slice().reverse());       
      var i = 0;
      function attempt() {
        if (i >= order.length || i >= 6) return sleep(0);      
        var d = order[i++];
        return cursorClick(d).then(function () {
          d.click();
          return sleep(500);
        }).then(function () {
          
          if (box.querySelector('.ibk-selected-day') || box.querySelector('.ibk-slots-grid button')) return sleep(200);
          return attempt();
        });
      }
      return attempt();
    }
    return p
      .then(function () { return waitFor('.ibk-cal-grid button:not([disabled])', 8000).then(pickDay); })

      

      .then(function () { return waitFor('.ibk-slots-grid button:not([disabled])', 8000).then(function (b) { return clickIf(b, 700); }); })
      .then(function () { return clickIf(q('.ibk-next-btn'), 900); })
      .then(function () {
        var nm = q('.ibk-name'), em = q('.ibk-email');
        var pr = sleep(0);
        if (nm) pr = pr.then(function () { return cursorClick(nm); }).then(function () { return type(nm, 'Anna Reyes'); });
        if (em) pr = pr.then(function () { return cursorClick(em); }).then(function () { return type(em, 'anna@gmail.com'); });
        return pr;
      })
      .then(function () { return clickIf(q('.ibk-submit-btn') || q('.ibk-next-btn'), 1400); });
  };
  window.__impapQuote = function (sec) {
    var box = sec.querySelector('.impulse-estimate-block');
    if (!box) return sleep(0);

    
    try { box.scrollIntoView({ behavior: 'smooth', block: 'end' }); } catch (eSv) {}
    var pre = sleep(1400);
    function q(s) { return box.querySelector(s); }
    var nm = q('.ime-name'), phn = q('.ime-phone'), msg = q('.ime-note');   
    var job = CUR.j || 'Looking to get this done in the next couple of weeks. What would it cost?';
    var p = pre;
    if (nm) p = p.then(function () { return cursorClick(nm); }).then(function () { return type(nm, 'Mark Reynolds'); });
    if (phn) p = p.then(function () { return cursorClick(phn); }).then(function () { return type(phn, '5551204118'); });
    if (msg) p = p.then(function () { return cursorClick(msg); }).then(function () { return type(msg, job); });
    var btn = q('.ime-btn');

    return btn ? p.then(function () { return cursorClick(btn); }).then(function () { btn.click(); return sleep(1600); }) : p;
  };

  window.__impapHideShow = function (sec) {

    
    var inner = sec.querySelector('.impulse-container') || sec;
    inner.dispatchEvent(new MouseEvent('mouseover', { bubbles: true }));
    return sleep(450).then(function () {
      var hideBtn = document.querySelector('.imp-sec-tools.show button');
      if (!hideBtn) return sleep(0);
      return cursorClick(hideBtn).then(function () {
        hideBtn.click();
        return sleep(1500);
      }).then(function () {
        var showAll = document.querySelector('#imp-restore.in button');
        if (!showAll) return sleep(0);
        return cursorClick(showAll).then(function () {
          showAll.click();
          return sleep(900);
        });
      });
    });
  };

  var path = location.pathname;

  
  
  var norm = function (p) { return String(p || '').replace(/\/+$/, '') || '/'; };
  var isEntry = !!document.querySelector('[data-demo-name]')
    && (norm(path) === norm(CUR.e) || norm(path) === '/make-a-site');
  var isDemo = /^\/demo\//.test(path);
  var isDash = /^\/dashboard/.test(path);

  
  if (S.on && isDash) {

    

    

    (function () {
      var s = document.createElement('style');
      s.id = 'impap-noupsell';

      
      s.textContent = '.up-chip,.pro-nudge,.net-card,.welcome,.nudge,.sc{display:none !important}';
      (document.head || document.documentElement).appendChild(s);

      

      
      var sweep = function () {
        document.querySelectorAll('a[href^="/upgrade"]').forEach(function (a) {
          var box = a.closest('p, .hint, .nudge, .pro-nudge') || a;
          box.style.display = 'none';
        });
      };
      document.addEventListener('DOMContentLoaded', sweep);
      window.addEventListener('load', sweep);
    })();
    var _fixEmail = function () {
      var re = /[a-z0-9._%-]+\+ap-[a-z0-9-]+@gmail\.com/gi;
      document.querySelectorAll('input, textarea').forEach(function (f) {
        if (re.test(f.value)) f.value = f.value.replace(re, 'your-email@gmail.com');
        re.lastIndex = 0;
      });
      var w = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
      var t;
      while ((t = w.nextNode())) {
        if (re.test(t.nodeValue)) t.nodeValue = t.nodeValue.replace(re, 'your-email@gmail.com');
        re.lastIndex = 0;
      }
    };
    window.addEventListener('load', function () { _fixEmail(); setTimeout(_fixEmail, 1200); });
  }

  var isLive = path.replace(/^\/+|\/+$/g, '') === CUR.s || (S.liveSlug && path.replace(/^\/+|\/+$/g, '') === S.liveSlug);

  
  var isHome = norm(path) === '/' && !document.querySelector('[data-demo-name]');

  

  if (S.on && !isHome && !isEntry && !isDemo && !isDash && !isLive) {
    setTimeout(function () {
      var q = (S && S.dashQ) || [];
      if (S.phase === 'dash' && S.dashI < q.length) {
        var nx = q[S.dashI]; S.dashI++; save(S);
        log('recover: unmodelled ' + path + ' -> ' + nx); location.href = nx;
      } else {
        S.phase = 'live'; save(S);
        log('recover: unmodelled ' + path + ' -> live');
        location.href = '/' + (S.liveSlug || CUR.s);
      }
    }, 2500);
    return;
  }
  if (isHome && S.phase === 'home') {
    window.addEventListener('load', function () {
      (async function () {
        if (S.warm) { delete S.warm; save(S); await sleep((S.wm || 14) * 1000); }
        else await sleep(2400);                          

        var vw = window.innerWidth, vh = window.innerHeight;
        await cursorToXY(vw * 0.18, vh * 0.42, 900);
        await cursorToXY(vw * 0.82, vh * 0.55, 1300);
        await cursorToXY(vw * 0.35, vh * 0.38, 1100);
        var btn = document.querySelector('a[href="/make-a-site"]');
        if (!btn) { S.phase = 'entry'; save(S); location.href = CUR.e; return; }
        await cursorClick(btn);
        S.phase = 'entry'; save(S);
        btn.click();
      })();
    });
    return;
  }

  if (isEntry && S.phase === 'entry') {
    window.addEventListener('load', function () {
      (async function () {

        
        if (S.intro === undefined && CUR.sq && !S.introPlayed) { S.intro = 1; save(S); }
        if (S.intro) {

          var lead = 900;
          if (S.warm) { delete S.warm; save(S); lead = (S.wm || 14) * 1000; }
          await searchIntro(CUR.sq || '', lead);

          
          S.introPlayed = CUR.s; save(S);
        } else if (S.warm) { delete S.warm; save(S); await sleep((S.wm || 14) * 1000); }   
        else await sleep(1400);
        var name = document.querySelector('[data-demo-name]');
        var trade = document.querySelector('[data-demo-trade]');
        var city = document.querySelector('[data-demo-city]');
        var mail = document.querySelector('[data-demo-email]');
        var phn = document.querySelector('[data-demo-phone]');
        var go = document.querySelector('[data-demo-go]');
        if (!name || !trade || !go) return;
        caption('entry');
        await cursorClick(name); await type(name, CUR.n); await sleep(300);
        await cursorClick(trade); await type(trade, CUR.t); await sleep(300);
        if (city) { await cursorClick(city); await type(city, CUR.c); await sleep(250); }

        

        var showEm = 'your-email@gmail.com';
        if (mail) { await cursorClick(mail); await type(mail, showEm); await sleep(250); }
        if (phn) { await cursorClick(phn); await type(phn, '(512) 555-01' + String(30 + (S.i % 60))); await sleep(250); }

        
        var chip = document.querySelector('.demo-chip[data-demo-staff="' + (CUR.staff || 'solo') + '"]')
            || document.querySelector('.demo-chip[data-demo-staff]');
        if (chip && !S.nb) { await cursorClick(chip); chip.click(); await sleep(650); }

        var ownerIn = document.querySelector('[data-demo-owner]');
        if (ownerIn && !ownerIn.hidden && CUR.on && !S.nb) {
          await cursorClick(ownerIn); await type(ownerIn, CUR.on); await sleep(350);
        }

        var archChip = CUR.arche ? document.querySelector('.demo-chip[data-demo-arche="' + CUR.arche + '"]') : null;
        if (archChip && !S.nb) { await cursorClick(archChip); archChip.click(); await sleep(650); }
        await cursorClick(go);
        captionHide();
        S.phase = 'demo'; save(S);
        if (mail) mail.value = apEmail(CUR.s);
        go.click();
        if (mail) mail.value = showEm;   
      })();
    });
    return;
  }

  if (isDemo && S.phase === 'demo') {
    
    var pid = (path.match(/\/demo\/(\d+)-/) || [])[1];
    if (pid) { try { localStorage.setItem('imp_tour_' + pid, '1'); } catch (e) {} }
    window.addEventListener('load', function () {
      (async function () {
        caption('hero');
        await sleep(1900);                               

        
        
        var hvw = window.innerWidth, hvh = window.innerHeight;

        await cursorToXY(hvw * 0.24, hvh * 0.40, 1400);
        await cursorToXY(hvw * 0.72, hvh * 0.45, 1600);
        await cursorToXY(hvw * 0.50, hvh * 0.48, 900);
        await sleep(900);
        await scrollThrough();
        await sleep(600);
        var fab = document.querySelector('#imp-cp-claimfab,[data-publish]');
        if (!fab) return;
        captionHide();
        var em = document.getElementById('imp-pub-email');
        var ph = document.getElementById('imp-pub-phone');
        var sl = document.getElementById('imp-pub-slug');
        var go = document.getElementById('imp-pub-go');
        if (!em || !go) return;
        var slug = CUR.s;

        

        
        var realEmail = apEmail(slug);
        var showEmail = 'your-email@gmail.com';
        em.value = showEmail;
        if (ph) ph.value = '(512) 555-01' + String(30 + (S.i % 60));
        await cursorClick(fab);
        fab.click();                                     
        await sleep(900);
        caption('publish');
        
        await cursorClick(em); await sleep(500);
        if (ph) { await cursorClick(ph); await sleep(400); }
        if (sl) {
          await cursorClick(sl); await sleep(400);
          if (!sl.value) { await type(sl, slug); await sleep(300); }   
        }
        await cursorClick(go);

        
        
        var realSlug = (sl && sl.value ? String(sl.value) : slug)
          .trim().toLowerCase().replace(/[^a-z0-9-]/g, '');
        S.phase = 'published'; S.liveSlug = realSlug || slug; save(S);
        log('publishing as /' + (realSlug || slug));
        em.value = realEmail;
        go.click();
        em.value = showEmail;   

        await sleep(4000);

        
        var msg = document.getElementById('imp-pub-msg');
        if (msg && /err/.test(msg.className || '') && (msg.textContent || '').trim()) {
          slug = CUR.s + '-' + (Math.floor(Math.random() * 90) + 10);
          if (sl) { await type(sl, slug); await sleep(300); }
          S.liveSlug = slug; save(S);
          em.value = apEmail(slug);   
          go.click();
          em.value = showEmail;
        }
      })();
    });
    return;
  }

  
  if (isDash && S.phase === 'inboxshot') {

    

    onLoad(function () {
      (async function () {
        await sleep(1800);
        var row = document.querySelector('table tbody tr, table tr td, .quote-row, .dash-list a, main li');
        if (row) {
          try { row.scrollIntoView({ behavior: 'smooth', block: 'center' }); } catch (e) {}
          await sleep(800);
          rowFlash(row);
          if (!S.nb) await cursorTo(row, 900);
        }
        await sleep(4200);                     
        await smsOverlay();
        await sleep(700);
        advance();
      })();
    });
    return;
  }

  if (isDash && (S.phase === 'published' || S.phase === 'demo' || S.phase === 'dash')) {
    window.addEventListener('load', function () {
      (async function () {

        

        ['.welcome', '.net-card', '.pro-nudge', '.up-chip', '.sc'].forEach(function (sel) {
          document.querySelectorAll(sel).forEach(function (n) { n.style.display = 'none'; });
        });
        
        try { if (location.search) history.replaceState(null, '', location.pathname); } catch (e) {}

        

        var seg = (location.pathname.replace(/\/+$/, '').split('/')[2] || '');

        
        setTimeout(function () {
          try {
            var q0 = (S && S.dashQ) || [];
            if (S.dashI < q0.length) { var nx = q0[S.dashI]; S.dashI++; save(S); log('watchdog -> ' + nx); location.href = nx; }
            else { S.phase = 'live'; save(S); log('watchdog -> live'); location.href = '/' + (S.liveSlug || CUR.s); }
          } catch (eW) {}
        }, 14000);
        if ((S.dm || 'full') === 'off') {          
          captionHide();
          S.phase = 'live'; save(S);
          location.href = '/' + (S.liveSlug || CUR.s);
          return;
        }
        if (S.phase !== 'dash') {
          
          S.phase = 'dash';
          S.dashQ = Array.prototype.slice.call(document.querySelectorAll('a.tile'))
            .map(function (a) { return a.getAttribute('href') || ''; })
            .filter(function (h) { return /^\/dashboard\/[a-z-]+$/.test(h) && !/\/(help|pro)$/.test(h); })

            

            
            
            .slice(0, 8);

          

          log('dash queue built: ' + S.dashQ.length + ' -> ' + S.dashQ.join(' '));
          if ((S.dm || 'full') === 'short') S.dashQ = [];   
          S.dashI = 0; save(S);
          caption('dashboard');
          await sleep(2600);
          var tiles = Array.prototype.slice.call(document.querySelectorAll('a.tile')).slice(0, 5);
          for (var ti = 0; ti < tiles.length; ti++) { await cursorTo(tiles[ti], 520); await sleep(300); }
        } else {

          

          caption('d:' + seg);
          var tabT0 = performance.now();
          await Promise.race([(async function () {
            await sleep(600);
            var back = document.querySelector('a.tile, .top a[href="/dashboard"]');
            if (back && !S.nb) await cursorTo(back, 500);
            await sleep(2400);
            
            var _noScroll = /\/(reviews)$/.test(seg ? '/' + seg : location.pathname);
            if (!_noScroll && document.documentElement.scrollHeight - window.innerHeight > 140) await scrollFlow(170);
          })().catch(function () {}), sleep(6000)]);
          log('tab ' + seg + ' ' + Math.round(performance.now() - tabT0) + 'ms');
        }

        var q = (S && S.dashQ) || [];
        if (S.dashI < q.length) {
          var next = q[S.dashI];
          log('dash -> ' + next + ' (' + (S.dashI + 1) + '/' + q.length + ')');
          S.dashI++; save(S);
          captionHide();
          location.href = next;
          return;
        }
        captionHide();
        await sleep(600);
        S.phase = 'live'; save(S);
        location.href = '/' + (S.liveSlug || CUR.s);
      })();
    });
    return;
  }

  if (isLive && (S.phase === 'live' || S.phase === 'published')) {

    
    
    onLoad(function () {

      
      var _liveDone = false;
      setTimeout(function () {
        if (_liveDone) return;
        try {
          log('watchdog: live pass stalled -> inbox');
          S.phase = 'inboxshot'; save(S);
          location.href = '/dashboard/quotes';
        } catch (eL) {}
      }, 75000);
      (async function () {

        
        
        caption('live');
        await sleep(2000);                     
        captionHide();

        
        
        await scrollFlow(850);
        window.scrollTo({ top: document.documentElement.scrollHeight, behavior: 'smooth' });
        await sleep(1200);
        
        var leadBox = document.querySelector('.impulse-estimate-block, .impulse-booking-block');
        if (leadBox && !S.nb) {
          var leadSec = leadBox.closest('.impulse-screen') || leadBox.closest('.impulse-section') || leadBox.parentElement;
          var isQuote = leadBox.classList.contains('impulse-estimate-block');
          var fn = isQuote ? window.__impapQuote : window.__impapBooking;
          if (typeof fn === 'function') { try { await fn(leadSec); } catch (eF) {} }
        }
        await sleep(700);
        await chatDemo();

        _liveDone = true;
        S.phase = 'inboxshot'; save(S);
        location.href = '/dashboard/quotes';
      })();
    });
    return;
  }

  

})();

(function trackPlayer() {
  var PQ = new URLSearchParams(location.search).get('play');
  var SK = 'impplay';
  if (PQ === 'stop') { try { localStorage.removeItem(SK); } catch (e) {} return; }

  var st = null;
  try { st = JSON.parse(localStorage.getItem(SK) || 'null'); } catch (e) { st = null; }
  if (PQ !== '1' && !st) return;

  var qs = new URLSearchParams(location.search);
  if (PQ === '1') {

    var speed0 = parseFloat(qs.get('speed') || '1') || 1;
    var from0  = (parseFloat(qs.get('from') || '0') || 0) * 1000;
    
    var vars0 = {
      biz:   qs.get('biz')   || 'Polished Nail Bar',
      trade: qs.get('trade') || 'Nail salon doing gel manicures, pedicures and nail art',
      city:  qs.get('city')  || 'Austin, TX',

        

        
        slug: qs.get('slug') || ('nail-bar-' + Date.now().toString(36)),
        email: qs.get('email') || ('owner+' + Date.now().toString(36) + '@instinctor-qa.test'),
      phone: qs.get('phone') || '(215) 555 0142',
      address: qs.get('address') || '1200 Congress Ave, Austin, TX'
    };
    fetch('/api/instinctor/v1/track/load', { cache: 'no-store' })
      .then(function (r) { return r.json(); })
      .then(function (tk) {
        if (!tk || !tk.length) { alert('No track to play.'); return; }
        try {
          localStorage.setItem(SK, JSON.stringify({ t0: Date.now() - from0, speed: speed0, track: tk, vars: vars0 }));
        } catch (e) { alert('Track too large for localStorage.'); return; }
        location.replace(location.pathname);
      })
      .catch(function () { alert('Could not load the track.'); });
    return;
  }

  var track = st.track || [], speed = st.speed || 1, t0 = st.t0, vars = st.vars || {};
  if (!track.length) return;
  var now = function () { return (Date.now() - t0) * speed; };

  var cur = document.createElement('div');
  cur.style.cssText = 'position:fixed;left:0;top:0;z-index:2147483646;width:22px;height:22px;'
    + 'margin:-11px 0 0 -11px;border-radius:50%;background:rgba(255,255,255,0.92);'
    + 'box-shadow:0 0 0 2px rgba(0,0,0,0.35),0 3px 12px rgba(0,0,0,0.4);pointer-events:none;'

    

    
    + 'transition:transform 90ms ease-in-out,left 70ms linear,top 70ms linear';
  var badge = document.createElement('div');
  badge.style.cssText = 'position:fixed;left:8px;top:8px;z-index:2147483647;background:#1d2327;color:#fff;'
    + 'font:600 11px/1 Arial,sans-serif;padding:5px 9px;border-radius:3px;pointer-events:none;opacity:0.8';
  function mount() {
    if (!document.body) return;
    if (!cur.isConnected)   document.body.appendChild(cur);
    if (!badge.isConnected) document.body.appendChild(badge);
  }
  if (document.body) mount(); else document.addEventListener('DOMContentLoaded', mount);

  function place(x, y) { cur.style.left = x + 'px'; cur.style.top = y + 'px'; }
  function pulse() {
    cur.style.transform = 'scale(0.6)';
    setTimeout(function () { cur.style.transform = 'scale(1)'; }, 130);
  }

  function target(e) {
    var el = null;

    
    
    if (e.sel && typeof e.idx === 'number') {
      try { el = document.querySelectorAll(e.sel)[e.idx] || null; } catch (err) { el = null; }
    }
    if (!el && e.sel) { try { el = document.querySelector(e.sel); } catch (err) { el = null; } }
    if (!el && typeof e.x === 'number') {
      el = document.elementFromPoint(e.x * window.innerWidth, e.y * window.innerHeight);
    }
    return el;
  }

  function fire(el) {
    if (!el) return false;
    var r = el.getBoundingClientRect();
    var cx = r.left + r.width / 2, cy = r.top + r.height / 2;
    ['mousedown', 'mouseup', 'click'].forEach(function (type) {
      el.dispatchEvent(new MouseEvent(type, {
        bubbles: true, cancelable: true, view: window, clientX: cx, clientY: cy
      }));
    });
    if (/^(INPUT|TEXTAREA|SELECT)$/.test(el.tagName)) { try { el.focus(); } catch (err) {} }
    return true;
  }

  var i = 0, pendingNav = '', navAt = 0;
  var lastMx = window.innerWidth / 2, lastMy = window.innerHeight / 2;
  var navFrom = '';
  
  while (i < track.length && track[i].t < now() - 400
         && track[i].k !== 'type' && track[i].k !== 'c' && track[i].k !== 'chat') i++;

  var tick = setInterval(function () {
    var t = now();
    if (i >= track.length) {
      clearInterval(tick);
      badge.textContent = 'done';
      try { localStorage.removeItem(SK); } catch (e) {}
      setTimeout(function () { cur.remove(); badge.remove(); }, 1500);
      return;
    }
    badge.textContent = (t / 1000).toFixed(1) + 's  ' + i + '/' + track.length;

    while (i < track.length && track[i].t <= t) {
      var e = track[i++];
      if (e.k === 'm') {
        var mx = e.x * window.innerWidth, my = e.y * window.innerHeight;
        place(mx, my);
        
        var under = document.elementFromPoint(mx, my) || document.documentElement;
        var init = { bubbles: true, cancelable: true, view: window,
                     clientX: mx, clientY: my, screenX: mx, screenY: my,
                     movementX: mx - lastMx, movementY: my - lastMy };
        lastMx = mx; lastMy = my;
        try { under.dispatchEvent(new MouseEvent('mousemove', init)); } catch (err) {}
        if (window.PointerEvent) {
          try {
            var pinit = {}; for (var kk in init) pinit[kk] = init[kk];
            pinit.pointerId = 1; pinit.pointerType = 'mouse'; pinit.isPrimary = true;
            under.dispatchEvent(new PointerEvent('pointermove', pinit));
          } catch (err) {}
        }
      } else if (e.k === 's') {
        var max = Math.max(1, document.documentElement.scrollHeight - window.innerHeight);
        window.scrollTo({ top: e.f * max, behavior: 'instant' });
      } else if (e.k === 'c') {
        if (typeof e.x === 'number') place(e.x * window.innerWidth, e.y * window.innerHeight);
        pulse();
        fire(target(e));
      } else if (e.k === 'type') {
        
        (function (spec) {
          var el = null;
          try {
            el = spec.sel ? document.querySelector(spec.sel)
               : document.querySelector('input[placeholder^="' + spec.ph + '"], textarea[placeholder^="' + spec.ph + '"]');
          } catch (err) { el = null; }
          if (!el) return;
          var r = el.getBoundingClientRect();
          place(r.left + Math.min(80, r.width / 2), r.top + r.height / 2);
          try { el.focus(); } catch (err) {}

          var isBox = /^(INPUT|TEXTAREA)$/.test(el.tagName);
          var txt = String(vars[spec.v] || spec.text || ''), n = 0;
          var typer = setInterval(function () {
            if (n >= txt.length) {
              clearInterval(typer);
              if (!isBox) el.dispatchEvent(new Event('blur', { bubbles: true }));
              return;
            }
            n++;
            var part = txt.slice(0, n);
            if (isBox) el.value = part; else el.textContent = part;
            el.dispatchEvent(new Event('input', { bubbles: true }));
          }, Math.max(22, Math.min(60, 1500 / Math.max(10, txt.length))));
        })(e);
      } else if (e.k === 'gallery') {
        
        (function (spec) {
          if (spec.act === 'close') {
            var c = document.querySelector('.imp-swap-close');
            if (c) { pulse(); c.click(); }
            return;
          }
          var hero = null;
          try { 

            
            hero = document.querySelector(spec.sel || 'section[data-depth-image]'); } catch (err) {}
          if (!hero) return;
          var r = hero.getBoundingClientRect();
          place(r.left + r.width * 0.5, r.top + Math.min(r.height * 0.5, window.innerHeight * 0.45));
          hero.dispatchEvent(new MouseEvent('mouseover', { bubbles: true, view: window }));

          
          
          setTimeout(function () {
            pulse();
            var cta = document.getElementById('imp-swap-cta');

            
            if (cta && getComputedStyle(cta).display !== 'none') {
              cta.dispatchEvent(new MouseEvent('mouseover', { bubbles: true, view: window }));
              var r2 = cta.getBoundingClientRect();
              place(r2.left + r2.width / 2, r2.top + r2.height / 2);
              cta.click();
              return;
            }
            hero.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window }));
          }, 120);
        })(e);
      } else if (e.k === 'chat') {
        
        (function (spec) {
          var box = document.getElementById('instinctor-ghost-input');
          if (!box) return;
          var r = box.getBoundingClientRect();
          place(r.left + Math.min(60, r.width / 2), r.top + r.height / 2);
          try { box.focus(); } catch (err) {}
          var txt = String(spec.text || ''), n = 0;
          var typer = setInterval(function () {
            if (n >= txt.length) {
              clearInterval(typer);
              pulse();
              setTimeout(function () {
                try {
                  if (window.InstinctorChat && InstinctorChat.ghostSend) InstinctorChat.ghostSend();
                } catch (err) {}
              }, 260);
              return;
            }
            n++;
            box.value = txt.slice(0, n);
            box.dispatchEvent(new Event('input', { bubbles: true }));
          }, Math.max(28, Math.min(70, 1400 / Math.max(8, txt.length))));
        })(e);
      } else if (e.k === 'key') {
        var a = document.activeElement;
        if (a) a.dispatchEvent(new KeyboardEvent('keydown', { key: e.key, bubbles: true }));
      } else if (e.k === 'nav') {
        pendingNav = e.p || '';
        navAt = t;
        navFrom = location.pathname;   
      }
    }

    
    if (pendingNav && t - navAt > 2500) {
      var here = location.pathname.replace(/\/+$/, '');
      var want = pendingNav.replace(/\/+$/, '');
      var oneOff = /^\/demo\//.test(want);   
      pendingNav = '';

      

      
      
      if (want && here !== want && !oneOff && here === navFrom) { location.href = want; return; }
    }
  }, 16);

  window.addEventListener('beforeunload', function () {

    

    try { localStorage.setItem(SK, JSON.stringify({ t0: t0, speed: speed, track: track, vars: vars })); } catch (e) {}
  });
})();

(function sceneBoot() {
  var want = new URLSearchParams(location.search).has('scene');
  if (!want) { try { want = !!localStorage.getItem('impscene'); } catch (e) {} }
  if (!want) return;
  var s = document.createElement('script');
  s.src = '/instinctor-assets/js/impulse-scene.js?v=' + (window.INSTINCTOR_VER || Date.now());
  (document.head || document.documentElement).appendChild(s);
})();
