/**
 * Employee Roster — Setup Wizard
 * Self-contained IIFE; depends on window.EMPR being set by wp_localize_script.
 */
(function () {
  'use strict';

  var W = window.EMPR;
  if (!W || !W.ajaxUrl) return;

  var AJAX        = W.ajaxUrl;
  var NONCE       = W.nonce;
  var SET         = W.settings    || {};

  // 0=welcome, 1=company, 2=locations, 3=departments, 4=employment, 5=features, 6=done
  var STEP_KEYS = ['welcome', 'company', 'locations', 'departments', 'employment', 'features', 'done'];
  var currentStep = 0;
  var saving      = false;

  /* ── tiny helpers ──────────────────────────────────────── */
  function esc(s) {
    var d = document.createElement('div');
    d.textContent = String(s == null ? '' : s);
    return d.innerHTML;
  }

  /* ── AJAX ──────────────────────────────────────────────── */
  function post(action, body) {
    var url = AJAX + '?action=' + encodeURIComponent(action) + '&nonce=' + encodeURIComponent(NONCE);
    return fetch(url, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      credentials: 'same-origin',
      body: JSON.stringify(body)
    }).then(function (r) { return r.json(); });
  }

  /* ── overlay ───────────────────────────────────────────── */
  function showWizard(startStep) {
    var overlay = document.getElementById('emr-wizard-overlay');
    if (!overlay) return;
    currentStep = (startStep !== undefined) ? startStep : 0;
    overlay.style.display = 'flex';
    requestAnimationFrame(function () { overlay.classList.add('is-open'); });
    renderStep();
  }

  function hideWizard() {
    var overlay = document.getElementById('emr-wizard-overlay');
    if (!overlay) return;
    overlay.classList.remove('is-open');
    setTimeout(function () { overlay.style.display = 'none'; }, 220);
  }

  /* ── progress dots ─────────────────────────────────────── */
  function updateProgress() {
    var totalSteps = STEP_KEYS.length - 2; // exclude welcome (0) and done (7)

    // Dots
    document.querySelectorAll('.wpr-wiz-dot').forEach(function (dot) {
      var s = parseInt(dot.dataset.step, 10);
      dot.classList.toggle('is-done',   s < currentStep);
      dot.classList.toggle('is-active', s === currentStep);
      dot.classList.toggle('is-future', s > currentStep);
    });

    // Connectors — colour those that sit between two completed dots
    document.querySelectorAll('.wpr-wiz-connector').forEach(function (conn, i) {
      conn.classList.toggle('is-done', (i + 1) < currentStep);
    });

    // Step counter ("Step 2 of 5" / hidden on welcome and done)
    var counter = document.getElementById('emr-wiz-counter');
    if (counter) {
      var key = STEP_KEYS[currentStep];
      if (key === 'welcome' || key === 'done') {
        counter.textContent = '';
      } else {
        counter.textContent = 'Step ' + currentStep + ' of ' + totalSteps;
      }
    }
  }

  /* ── step renderers ────────────────────────────────────── */
  function renderWelcome() {
    return '<div class="wpr-wiz-welcome">' +
      '<div class="wpr-wiz-welcome__icon" aria-hidden="true">' +
        '<svg viewBox="0 0 64 64" fill="none" stroke="currentColor" stroke-width="2">' +
          '<rect x="6" y="10" width="52" height="46" rx="5"/>' +
          '<line x1="6"  y1="24" x2="58" y2="24"/>' +
          '<line x1="20" y1="4"  x2="20" y2="16"/>' +
          '<line x1="44" y1="4"  x2="44" y2="16"/>' +
          '<line x1="18" y1="36" x2="28" y2="36"/>' +
          '<line x1="18" y1="44" x2="28" y2="44"/>' +
          '<line x1="36" y1="36" x2="46" y2="36"/>' +
          '<line x1="36" y1="44" x2="46" y2="44"/>' +
        '</svg>' +
      '</div>' +
      '<h2 id="emr-wiz-title" class="wpr-wiz-welcome__title">Welcome to EmpRoster!</h2>' +
      '<p class="wpr-wiz-welcome__sub">Let\'s set up your workspace in a few quick steps. You can adjust any of these settings later from the Settings page.</p>' +
      '<ul class="wpr-wiz-welcome__checklist">' +
        '<li>Company name &amp; brand colour</li>' +
        '<li>Work locations &amp; departments</li>' +
        '<li>Employment types</li>' +
        '<li>Features &amp; permissions</li>' +
      '</ul>' +
    '</div>';
  }

  function renderCompany() {
    var name  = SET.companyName  || '';
    var color = SET.primaryColor || '#2563EB';
    var ws    = String('weekStart' in SET ? SET.weekStart : 1);
    var dayNames = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
    return '<div class="wpr-wiz-step">' +
      '<h2 class="wpr-wiz-step__title" id="emr-wiz-title">Company Details</h2>' +
      '<p class="wpr-wiz-step__sub">Set your company name, brand colour, and roster week start day.</p>' +
      '<div class="wpr-wiz-form">' +
        '<div class="wpr-wiz-field wpr-wiz-field--full">' +
          '<label class="wpr-wiz-label" for="wiz-company-name">Company Name</label>' +
          '<input id="wiz-company-name" class="wpr-input" type="text" maxlength="120" placeholder="Acme Corp" value="' + esc(name) + '">' +
        '</div>' +
        '<div class="wpr-wiz-field">' +
          '<label class="wpr-wiz-label" for="wiz-primary-color">Brand Colour</label>' +
          '<div class="wpr-wiz-color-row">' +
            '<input id="wiz-primary-color" class="wpr-input" type="text" maxlength="7" placeholder="#2563EB" value="' + esc(color) + '" style="font-family:monospace">' +
            '<input id="wiz-primary-color-picker" class="wpr-wiz-color-picker" type="color" value="' + esc(color) + '" title="Pick colour">' +
          '</div>' +
        '</div>' +
        '<div class="wpr-wiz-field">' +
          '<label class="wpr-wiz-label" for="wiz-week-start">Week Starts On</label>' +
          '<select id="wiz-week-start" class="wpr-input">' +
            dayNames.map(function(n, i) { return '<option value="' + i + '"' + (ws === String(i) ? ' selected' : '') + '>' + n + '</option>'; }).join('') +
          '</select>' +
        '</div>' +
      '</div>' +
    '</div>';
  }

  function renderLocations() {
    var locs = SET.locations;
    if (!Array.isArray(locs) || locs.length === 0) {
      locs = [{ name: 'Main Location', color: '#2563EB' }];
    }

    var rows = '';
    locs.forEach(function (loc, i) { rows += locationRow(loc.name, loc.color, i); });

    var addBtn = '<button type="button" id="wiz-add-loc" class="wpr-btn wpr-btn--ghost wpr-btn--sm" style="margin-top:.5rem">+ Add Location</button>';

    return '<div class="wpr-wiz-step">' +
      '<h2 class="wpr-wiz-step__title" id="emr-wiz-title">Locations</h2>' +
      '<p class="wpr-wiz-step__sub">Define where your team works. Each location gets its own colour on the roster.</p>' +
      '<div id="wiz-loc-list" class="wpr-wiz-list">' + rows + '</div>' +
      addBtn +
    '</div>';
  }

  function locationRow(name, color, idx) {
    return '<div class="wpr-wiz-list-row" data-idx="' + esc(idx) + '">' +
      '<input class="wpr-input wpr-wiz-loc-name" type="text" placeholder="Location name" value="' + esc(name) + '" maxlength="80">' +
      '<div class="wpr-wiz-color-row">' +
        '<input class="wpr-input wpr-wiz-loc-color-text" type="text" maxlength="7" placeholder="#2563EB" value="' + esc(color) + '" style="font-family:monospace;width:100px;flex:none">' +
        '<input class="wpr-wiz-color-picker wpr-wiz-loc-color-picker" type="color" value="' + esc(color) + '" title="Pick colour">' +
      '</div>' +
      '<button type="button" class="wpr-btn wpr-btn--ghost wpr-btn--xs wpr-wiz-del-loc" title="Remove">&times;</button>' +
    '</div>';
  }

  function departmentRow(name, idx) {
    return '<div class="wpr-wiz-list-row" data-idx="' + esc(idx) + '">' +
      '<input class="wpr-input wpr-wiz-dept-name" type="text" placeholder="Department name" value="' + esc(name) + '" maxlength="80">' +
      '<button type="button" class="wpr-btn wpr-btn--ghost wpr-btn--xs wpr-wiz-del-dept" title="Remove">&times;</button>' +
    '</div>';
  }

  function renderDepartments() {
    var rawDepts = SET.departments;
    var deptArr = Array.isArray(rawDepts)
      ? rawDepts
      : String(rawDepts || 'General Department').split('\n').map(function(s) { return s.trim(); }).filter(Boolean);
    if (!deptArr.length) deptArr = ['General Department'];

    var rows = '';
    deptArr.forEach(function(name, i) { rows += departmentRow(name, i); });

    var addBtn = '<button type="button" id="wiz-add-dept" class="wpr-btn wpr-btn--ghost wpr-btn--sm" style="margin-top:.5rem">+ Add Department</button>';

    return '<div class="wpr-wiz-step">' +
      '<h2 class="wpr-wiz-step__title" id="emr-wiz-title">Departments</h2>' +
      '<p class="wpr-wiz-step__sub">Define your team departments. Staff are assigned to departments when you add them.</p>' +
      '<div id="wiz-dept-list" class="wpr-wiz-list">' + rows + '</div>' +
      addBtn +
    '</div>';
  }

  function renderEmployment() {
    var ft = (SET.jobTypeHours && SET.jobTypeHours.fulltime) ? SET.jobTypeHours.fulltime : 38;
    var pt = (SET.jobTypeHours && SET.jobTypeHours.parttime) ? SET.jobTypeHours.parttime : 24;
    return '<div class="wpr-wiz-step">' +
      '<h2 class="wpr-wiz-step__title" id="emr-wiz-title">Employment Types</h2>' +
      '<p class="wpr-wiz-step__sub">Set standard weekly hours for each employment category. These drive overtime thresholds and payroll calculations.</p>' +
      '<div class="wpr-wiz-form">' +
        '<div class="wpr-wiz-field">' +
          '<label class="wpr-wiz-label" for="wiz-hours-ft">Full-time Hours / Week</label>' +
          '<input id="wiz-hours-ft" class="wpr-input" type="number" min="1" max="168" step="1" value="' + esc(ft) + '">' +
        '</div>' +
        '<div class="wpr-wiz-field">' +
          '<label class="wpr-wiz-label" for="wiz-hours-pt">Part-time Hours / Week</label>' +
          '<input id="wiz-hours-pt" class="wpr-input" type="number" min="1" max="168" step="1" value="' + esc(pt) + '">' +
        '</div>' +
      '</div>' +
      '<p class="wpr-wiz-note"><strong>Casual</strong> employees have no fixed weekly hours — overtime is not tracked for this type.</p>' +
    '</div>';
  }

  // This build has a single tier — every feature row is a plain toggle.
  function featureRow(id, label, desc, enabled) {
    return '<label class="wpr-wiz-feature-row">' +
      '<div class="wpr-wiz-feature-row__info">' +
        '<strong>' + label + '</strong>' +
        '<span class="wpr-wiz-hint">' + desc + '</span>' +
      '</div>' +
      '<input id="' + esc(id) + '" class="wpr-wiz-toggle" type="checkbox"' + (enabled ? ' checked' : '') + '>' +
      '<span class="wpr-wiz-toggle-track"></span>' +
    '</label>';
  }

  function renderFeatures() {
    var notifOn = SET.notificationsEnabled === true;

    return '<div class="wpr-wiz-step">' +
      '<h2 class="wpr-wiz-step__title" id="emr-wiz-title">Features &amp; Permissions</h2>' +
      '<p class="wpr-wiz-step__sub">Enable the features your team needs.</p>' +
      '<div class="wpr-wiz-features">' +
        featureRow('wiz-notif', 'Email Notifications', 'Automatically notify staff when shifts are assigned or updated.', notifOn) +
      '</div>' +
    '</div>';
  }

  function renderDone() {
    return '<div class="wpr-wiz-done">' +
      '<div class="wpr-wiz-done__icon" aria-hidden="true">' +
        '<svg viewBox="0 0 64 64" fill="none" stroke="currentColor" stroke-width="2.5">' +
          '<circle cx="32" cy="32" r="28"/>' +
          '<polyline points="18,32 27,42 46,22"/>' +
        '</svg>' +
      '</div>' +
      '<h2 id="emr-wiz-title" class="wpr-wiz-done__title">You\'re all set!</h2>' +
      '<p class="wpr-wiz-done__sub">Your roster is configured and ready. You can edit any of these settings at any time from <strong>EmpRoster → Settings</strong>.</p>' +
      '<div class="wpr-wiz-done__links">' +
        '<p class="wpr-wiz-done__links-label">Suggested next steps:</p>' +
        '<a href="' + esc(adminUrl('employee-roster-staff')) + '" class="wpr-wiz-done__link">&#8594; Add your first staff member</a>' +
        '<a href="' + esc(adminUrl('employee-roster-shifts')) + '" class="wpr-wiz-done__link">&#8594; Create your first shift</a>' +
        '<a href="' + esc(adminUrl('employee-roster-settings')) + '" class="wpr-wiz-done__link">&#8594; Review all settings</a>' +
      '</div>' +
    '</div>';
  }

  function adminUrl(page) {
    var base = AJAX.replace('admin-ajax.php', 'admin.php');
    return base + '?page=' + page;
  }

  /* ── collect step data ─────────────────────────────────── */
  function g(id) { return document.getElementById(id); }

  function collectCompany() {
    return {
      company_name:  g('wiz-company-name')       ? g('wiz-company-name').value.trim()  : '',
      primary_color: g('wiz-primary-color')       ? g('wiz-primary-color').value.trim() : '',
      week_start:    g('wiz-week-start')          ? g('wiz-week-start').value            : '1'
    };
  }

  function collectLocations() {
    var locs = [];
    document.querySelectorAll('#wiz-loc-list .wpr-wiz-list-row').forEach(function (row) {
      var name  = row.querySelector('.wpr-wiz-loc-name')       ? row.querySelector('.wpr-wiz-loc-name').value.trim()        : '';
      var color = row.querySelector('.wpr-wiz-loc-color-text') ? row.querySelector('.wpr-wiz-loc-color-text').value.trim()  : '#2563EB';
      if (name) locs.push({ name: name, color: color || '#2563EB' });
    });
    return { locations: locs };
  }

  function collectDepartments() {
    var names = [];
    document.querySelectorAll('#wiz-dept-list .wpr-wiz-dept-name').forEach(function(inp) {
      var v = inp.value.trim();
      if (v) names.push(v);
    });
    return { departments: names.join('\n') };
  }

  function collectEmployment() {
    return {
      hours_fulltime: g('wiz-hours-ft') ? (parseInt(g('wiz-hours-ft').value, 10) || 38) : 38,
      hours_parttime: g('wiz-hours-pt') ? (parseInt(g('wiz-hours-pt').value, 10) || 24) : 24
    };
  }

  function collectFeatures() {
    return {
      allow_self_clock:        g('wiz-self-clock')    ? g('wiz-self-clock').checked    : false,
      payroll_enabled:         g('wiz-payroll')       ? g('wiz-payroll').checked       : false,
      notifications_enabled:   g('wiz-notif')         ? g('wiz-notif').checked         : false,
      profile_mode_enabled:    g('wiz-profile-mode')  ? g('wiz-profile-mode').checked  : true,
      public_roster_shortcode: g('wiz-public-roster') ? g('wiz-public-roster').checked : false
    };
  }

  function collectStep(key) {
    switch (key) {
      case 'company':     return collectCompany();
      case 'locations':   return collectLocations();
      case 'departments': return collectDepartments();
      case 'employment':  return collectEmployment();
      case 'features':    return collectFeatures();
      default:            return null;
    }
  }

  /* ── save / complete ───────────────────────────────────── */
  function saveStep(key, data) {
    return post('empr_wizard_save_step', { step: key, data: data });
  }

  function completeWizard() {
    return post('empr_wizard_complete', {}).then(function (res) {
      var url = (res && res.success && res.data && res.data.redirectUrl)
        ? res.data.redirectUrl
        : adminUrl('employee-roster');
      window.location.href = url;
    });
  }

  /* ── render & wire ─────────────────────────────────────── */
  function renderStep() {
    var key     = STEP_KEYS[currentStep];
    var body    = g('emr-wiz-body');
    var backBtn = g('emr-wiz-back');
    var skipBtn = g('emr-wiz-skip');
    var nextBtn = g('emr-wiz-next');
    if (!body) return;

    switch (key) {
      case 'welcome':     body.innerHTML = renderWelcome();     break;
      case 'company':     body.innerHTML = renderCompany();     break;
      case 'locations':   body.innerHTML = renderLocations();   break;
      case 'departments': body.innerHTML = renderDepartments(); break;
      case 'employment':  body.innerHTML = renderEmployment();  break;
      case 'features':    body.innerHTML = renderFeatures();    break;
      case 'done':        body.innerHTML = renderDone();        break;
    }

    if (backBtn) backBtn.style.visibility = currentStep <= 1 ? 'hidden' : 'visible';

    if (skipBtn) {
      skipBtn.style.display = (key === 'welcome' || key === 'done') ? 'none' : '';
    }

    if (nextBtn) {
      nextBtn.disabled    = false;
      nextBtn.textContent = key === 'welcome'  ? 'Get Started →' :
                            key === 'features' ? 'Finish Setup →' :
                            key === 'done'     ? 'Go to Dashboard' :
                                                 'Next →';
    }

    updateProgress();
    wireColorSync('wiz-primary-color', 'wiz-primary-color-picker');
    wireLocations();
    wireDepartments();
  }

  function wireColorSync(textId, pickerId) {
    var text   = g(textId);
    var picker = g(pickerId);
    if (!text || !picker) return;
    text.addEventListener('input', function () {
      if (/^#[0-9a-fA-F]{6}$/.test(text.value)) picker.value = text.value;
    });
    picker.addEventListener('input', function () { text.value = picker.value; });
  }

  function wireLocRowEvents(row) {
    var delBtn  = row.querySelector('.wpr-wiz-del-loc');
    var colText = row.querySelector('.wpr-wiz-loc-color-text');
    var colPick = row.querySelector('.wpr-wiz-loc-color-picker');

    if (delBtn) {
      delBtn.addEventListener('click', function () {
        row.remove();
        var addBtn = g('wiz-add-loc');
        if (addBtn) addBtn.style.display = '';
      });
    }
    if (colText && colPick) {
      colText.addEventListener('input', function () {
        if (/^#[0-9a-fA-F]{6}$/.test(colText.value)) colPick.value = colText.value;
      });
      colPick.addEventListener('input', function () { colText.value = colPick.value; });
    }
  }

  function wireLocations() {
    var list   = g('wiz-loc-list');
    var addBtn = g('wiz-add-loc');
    if (!list) return;

    list.querySelectorAll('.wpr-wiz-list-row').forEach(wireLocRowEvents);

    if (addBtn) {
      addBtn.addEventListener('click', function () {
        var rows = list.querySelectorAll('.wpr-wiz-list-row');
        var div  = document.createElement('div');
        div.innerHTML = locationRow('', '#2563EB', rows.length);
        var newRow = div.firstChild;
        list.appendChild(newRow);
        wireLocRowEvents(newRow);
        newRow.querySelector('.wpr-wiz-loc-name').focus();
      });
    }
  }

  function wireDeptControls() {
    var list   = g('wiz-dept-list');
    var addBtn = g('wiz-add-dept');
    if (!list) return;
    var count = list.querySelectorAll('.wpr-wiz-list-row').length;
    list.querySelectorAll('.wpr-wiz-list-row').forEach(function(row) {
      var del = row.querySelector('.wpr-wiz-del-dept');
      if (del) del.style.visibility = count <= 1 ? 'hidden' : '';
    });
    if (addBtn) addBtn.style.display = '';
  }

  function wireDeptRowEvents(row) {
    var delBtn = row.querySelector('.wpr-wiz-del-dept');
    if (delBtn) {
      delBtn.addEventListener('click', function() {
        row.remove();
        wireDeptControls();
      });
    }
  }

  function wireDepartments() {
    var list   = g('wiz-dept-list');
    var addBtn = g('wiz-add-dept');
    if (!list) return;
    list.querySelectorAll('.wpr-wiz-list-row').forEach(wireDeptRowEvents);
    wireDeptControls();
    if (addBtn) {
      addBtn.addEventListener('click', function() {
        var rows = list.querySelectorAll('.wpr-wiz-list-row');
        var div  = document.createElement('div');
        div.innerHTML = departmentRow('', rows.length);
        var newRow = div.firstChild;
        list.appendChild(newRow);
        wireDeptRowEvents(newRow);
        wireDeptControls();
        newRow.querySelector('.wpr-wiz-dept-name').focus();
      });
    }
  }

  /* ── navigation ────────────────────────────────────────── */
  async function handleNext() {
    if (saving) return;
    var key = STEP_KEYS[currentStep];

    if (key === 'done') {
      var btn = g('emr-wiz-next');
      if (btn) { btn.disabled = true; btn.textContent = 'Redirecting…'; }
      await completeWizard();
      return;
    }

    if (key !== 'welcome') {
      saving = true;
      var nextBtn = g('emr-wiz-next');
      var orig    = nextBtn ? nextBtn.textContent : '';
      if (nextBtn) { nextBtn.disabled = true; nextBtn.textContent = 'Saving…'; }
      try {
        var data = collectStep(key);
        if (data) await saveStep(key, data);
        // refresh local cache for downstream steps
        if (key === 'company') {
          var c = collectCompany();
          SET.companyName  = c.company_name;
          SET.primaryColor = c.primary_color;
          SET.weekStart    = c.week_start;
        }
      } catch (e) { /* continue anyway */ }
      saving = false;
      if (nextBtn) { nextBtn.disabled = false; nextBtn.textContent = orig; }
    }

    currentStep++;
    renderStep();
  }

  function handleBack() {
    if (currentStep > 0) {
      currentStep--;
      renderStep();
    }
  }

  function handleSkip() {
    currentStep++;
    renderStep();
  }

  /* ── boot ──────────────────────────────────────────────── */
  function init() {
    var overlay = document.getElementById('emr-wizard-overlay');
    if (!overlay) return;

    g('emr-wiz-next') && g('emr-wiz-next').addEventListener('click', handleNext);
    g('emr-wiz-back') && g('emr-wiz-back').addEventListener('click', handleBack);
    g('emr-wiz-skip') && g('emr-wiz-skip').addEventListener('click', handleSkip);

    // ESC closes wizard only when re-launched from settings (not on first install)
    document.addEventListener('keydown', function (e) {
      if (e.key !== 'Escape') return;
      if (overlay.style.display === 'none') return;
      if (!W.wizardNeeded || currentStep > 0) hideWizard();
    });

    // Re-launch from Settings page "Setup Wizard" button
    document.addEventListener('click', function (e) {
      if (e.target.closest('[data-launch-wizard]')) {
        currentStep = 0;
        showWizard();
      }
    });

    if (W.wizardNeeded) {
      showWizard(0);
    }
  }

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

})();
