(() => {
  'use strict';

  const config = window.SHCDShabnamFramework || {};
  const app = document.getElementById('shcd-shabnam-app');
  if (!app) return;

  let state = { ...(config.settings || {}) };
  let media = { ...(config.media || {}) };

  const $ = (selector, root = app) => root.querySelector(selector);
  const $$ = (selector, root = app) => Array.from(root.querySelectorAll(selector));
  const toast = $('#shcd-toast');
  const saveButton = $('#shcd-save-settings');
  const resetButton = $('#shcd-reset-settings');

  const normalizeHex = (value, fallback = '#000000') => {
    const text = String(value || '').trim();
    return /^#[0-9a-fA-F]{6}$/.test(text) ? text.toUpperCase() : fallback;
  };

  const showToast = (message, type = 'success') => {
    if (!toast) return;
    toast.textContent = String(message || '');
    toast.className = `shcd-toast is-visible is-${type}`;
    window.clearTimeout(showToast.timer);
    showToast.timer = window.setTimeout(() => {
      toast.className = 'shcd-toast';
    }, 3400);
  };

  const setRoute = (route, pushHash = true) => {
    const allowed = ['wizard', 'general', 'demos', 'colors', 'typography', 'header', 'auth', 'blog', 'shop', 'footer', 'health', 'performance', 'about'];
    const next = allowed.includes(route) ? route : 'general';
    $$('.shcd-nav button').forEach((button) => button.classList.toggle('is-active', button.dataset.route === next));
    $$('.shcd-view').forEach((view) => view.classList.toggle('is-active', view.dataset.view === next));
    if (pushHash && window.location.hash !== `#${next}`) {
      window.history.replaceState(null, '', `#${next}`);
    }
  };

  const syncDemoCards = () => {
    $$('.shcd-demo-card[data-demo-select]').forEach((card) => {
      const active = String(card.dataset.demoSelect || '') === String(state.home_demo || 'one');
      card.classList.toggle('is-selected', active);
      card.setAttribute('aria-pressed', active ? 'true' : 'false');
    });
  };

  const chooseDemoFromCard = (card) => {
    const demo = String(card?.dataset?.demoSelect || '');
    if (demo !== 'one') return;
    state.home_demo = demo;
    const select = $('[data-setting="home_demo"]');
    if (select) select.value = demo;
    syncDemoCards();
  };

  const renderMedia = () => {
    $$('.shcd-media-field').forEach((field) => {
      const key = field.dataset.mediaField;
      const image = $('img', field);
      const empty = $('.shcd-media-empty', field);
      const item = key === 'brand_logo_id' ? media.brandLogo : media.siteIcon;
      const url = item && item.url ? item.url : '';
      if (image) {
        image.hidden = !url;
        if (url) image.src = url;
        else image.removeAttribute('src');
      }
      if (empty) empty.hidden = Boolean(url);
    });
  };


  const updatePreview = () => {
    const root = app.style;
    root.setProperty('--preview-primary', normalizeHex(state.primary_color, '#5836C7'));
    root.setProperty('--preview-secondary', normalizeHex(state.secondary_color, '#FFD200'));
    root.setProperty('--preview-tertiary', normalizeHex(state.tertiary_color, '#FFA2E6'));
    root.setProperty('--preview-bg', normalizeHex(state.background_color, '#0D042C'));
    root.setProperty('--preview-surface', normalizeHex(state.surface_color, '#1A0C3B'));
    root.setProperty('--preview-text', normalizeHex(state.text_color, '#FFFFFF'));
    root.setProperty('--preview-muted', normalizeHex(state.muted_color, '#CFC4DB'));
  };

  const hydrate = () => {
    $$('[data-setting]').forEach((input) => {
      const key = input.dataset.setting;
      const value = state[key];
      if (input.type === 'checkbox') input.checked = Boolean(value);
      else input.value = value ?? '';
    });

    $$('[data-color-text]').forEach((input) => {
      const key = input.dataset.colorText;
      input.value = normalizeHex(state[key], input.value || '#000000');
    });
    $$('[data-color-code]').forEach((node) => {
      const key = node.dataset.colorCode;
      node.textContent = normalizeHex(state[key], node.textContent || '#000000');
    });

    renderMedia();
    updatePreview();
    syncDemoCards();
  };

  const collect = () => ({ ...state });

  const request = async (url, body = {}) => {
    const response = await fetch(url, {
      method: 'POST',
      credentials: 'same-origin',
      headers: {
        'Content-Type': 'application/json',
        'X-WP-Nonce': config.nonce || ''
      },
      body: JSON.stringify(body)
    });
    const data = await response.json().catch(() => ({}));
    if (!response.ok || !data.success) throw new Error(data.message || 'Request failed');
    return data;
  };

  $$('.shcd-nav button').forEach((button) => button.addEventListener('click', () => setRoute(button.dataset.route)));
  $$('[data-route-jump]').forEach((button) => button.addEventListener('click', () => setRoute(button.dataset.routeJump)));

  $$('.shcd-demo-card[data-demo-select]').forEach((card) => {
    card.addEventListener('click', (event) => {
      if (event.target.closest('a, button, input, select, textarea')) return;
      chooseDemoFromCard(card);
    });
    card.addEventListener('keydown', (event) => {
      if (!['Enter', ' '].includes(event.key)) return;
      if (event.target.closest('a, button, input, select, textarea')) return;
      event.preventDefault();
      chooseDemoFromCard(card);
    });
  });

  $$('[data-setting]').forEach((input) => {
    const updateState = () => {
      const key = input.dataset.setting;
      if (input.type === 'checkbox') state[key] = input.checked;
      else if (input.type === 'number') state[key] = Number.parseInt(input.value, 10) || 0;
      else state[key] = input.value;

      $$(`[data-setting="${key}"]`).forEach((peer) => {
        if (peer === input) return;
        if (peer.type === 'checkbox') peer.checked = Boolean(state[key]);
        else peer.value = state[key] ?? '';
      });

      if (input.type === 'color') {
        const value = normalizeHex(input.value, '#000000');
        $$(`[data-color-text="${key}"]`).forEach((text) => { text.value = value; });
        $$(`[data-color-code="${key}"]`).forEach((code) => { code.textContent = value; });
      }
      if (key === 'home_demo') syncDemoCards();
      updatePreview();
    };
    input.addEventListener('input', updateState);
    input.addEventListener('change', updateState);
  });

  $$('[data-color-text]').forEach((input) => {
    input.addEventListener('input', () => {
      const key = input.dataset.colorText;
      if (!/^#[0-9a-fA-F]{6}$/.test(input.value.trim())) return;
      const value = input.value.trim().toUpperCase();
      state[key] = value;
      $$(`[data-setting="${key}"]`).forEach((picker) => { picker.value = value; });
      $$(`[data-color-text="${key}"]`).forEach((peer) => { if (peer !== input) peer.value = value; });
      $$(`[data-color-code="${key}"]`).forEach((code) => { code.textContent = value; });
      updatePreview();
    });
  });

  $$('.shcd-media-field').forEach((field) => {
    const key = field.dataset.mediaField;
    const select = $('[data-media-select]', field);
    const remove = $('[data-media-remove]', field);

    select?.addEventListener('click', () => {
      if (!window.wp || !wp.media) return;
      const frame = wp.media({
        title: config.i18n?.chooseImage || 'انتخاب تصویر',
        button: { text: config.i18n?.useImage || 'استفاده از این تصویر' },
        library: { type: 'image' },
        multiple: false
      });
      frame.on('select', () => {
        const attachment = frame.state().get('selection').first().toJSON();
        state[key] = Number.parseInt(attachment.id, 10) || 0;
        const item = { id: state[key], url: attachment.sizes?.medium?.url || attachment.url || '' };
        if (key === 'brand_logo_id') media.brandLogo = item;
        else media.siteIcon = item;
        renderMedia();
      });
      frame.open();
    });

    remove?.addEventListener('click', () => {
      state[key] = 0;
      if (key === 'brand_logo_id') media.brandLogo = { id: 0, url: '' };
      else media.siteIcon = { id: 0, url: '' };
      renderMedia();
    });
  });



  // Smart setup wizard: all steps live in the same SPA screen.
  const wizard = $('[data-shcd-wizard]');
  if (wizard) {
    let wizardStep = 0;
    const wizardSteps = $$('.shcd-wizard-step', wizard);
    const progress = $('[data-wizard-progress]', wizard);
    const prev = $('[data-wizard-prev]', wizard);
    const next = $('[data-wizard-next]', wizard);
    const finish = $('[data-wizard-finish]', wizard);

    const paintWizard = () => {
      wizardSteps.forEach((step, index) => step.classList.toggle('is-active', index === wizardStep));
      if (progress) progress.style.width = `${((wizardStep + 1) / wizardSteps.length) * 100}%`;
      if (prev) prev.hidden = wizardStep === 0;
      if (next) next.hidden = wizardStep >= wizardSteps.length - 1;
      if (finish) finish.hidden = wizardStep !== wizardSteps.length - 1;
      $$('[data-wizard-demo]', wizard).forEach((button) => button.classList.toggle('is-active', button.dataset.wizardDemo === String(state.home_demo || 'one')));
    };
    prev?.addEventListener('click', () => { wizardStep = Math.max(0, wizardStep - 1); paintWizard(); });
    next?.addEventListener('click', () => { wizardStep = Math.min(wizardSteps.length - 1, wizardStep + 1); paintWizard(); });
    $$('[data-wizard-demo]', wizard).forEach((button) => button.addEventListener('click', () => {
      state.home_demo = button.dataset.wizardDemo;
      $$('[data-setting="home_demo"]').forEach((select) => { select.value = state.home_demo; });
      syncDemoCards();
      paintWizard();
    }));
    finish?.addEventListener('click', async () => {
      if (finish.disabled) return;
      state.setup_completed = true;
      finish.disabled = true;
      try {
        const data = await request(config.restUrl, collect());
        state = { ...data.settings, setup_completed: true };
        media = { ...data.media };
        hydrate();
        showToast('راه‌اندازی اولیه انجام شد. برگه‌های موجود دوباره ساخته نشدند.');
        setRoute('general');
      } catch (error) {
        showToast('ذخیره راه‌اندازی انجام نشد. دوباره تلاش کنید.', 'error');
      } finally {
        finish.disabled = false;
      }
    });
    paintWizard();
  }


  saveButton?.addEventListener('click', async () => {
    if (saveButton.disabled) return;
    saveButton.disabled = true;
    saveButton.classList.add('is-saving');
    try {
      const data = await request(config.restUrl, collect());
      state = { ...data.settings };
      media = { ...data.media };
      hydrate();
      showToast(config.i18n?.saved || 'تغییرات با موفقیت ذخیره شد.');
    } catch (error) {
      showToast(config.i18n?.error || 'ذخیره تنظیمات انجام نشد. دوباره تلاش کنید.', 'error');
    } finally {
      saveButton.disabled = false;
      saveButton.classList.remove('is-saving');
    }
  });

  resetButton?.addEventListener('click', async () => {
    if (!window.confirm(config.i18n?.resetConfirm || 'تنظیمات به مقادیر پیش‌فرض بازگردد؟')) return;
    resetButton.disabled = true;
    try {
      const data = await request(config.resetUrl, {});
      state = { ...data.settings };
      media = { ...data.media };
      hydrate();
      showToast(config.i18n?.reset || 'تنظیمات به مقادیر پیش‌فرض بازگردانده شد.');
    } catch (error) {
      showToast(config.i18n?.error || 'بازگردانی تنظیمات انجام نشد. دوباره تلاش کنید.', 'error');
    } finally {
      resetButton.disabled = false;
    }
  });

  window.addEventListener('hashchange', () => setRoute(String(window.location.hash || '').replace('#', ''), false));
  const initialRoute = String(window.location.hash || '').replace('#', '') || (state.setup_completed ? 'general' : 'wizard');
  setRoute(initialRoute, false);
  hydrate();
})();
