jQuery(function ($) {
  // Copy shortcodes
  $(document).on('click', '.dabl-rr-copy', function () {
    const val = $(this).data('copy') || '';
    if (!val) return;
    const b = $(this);
    const old = b.text();

    function flashCopied() {
      b.text('Copied');
      setTimeout(() => b.text(old), 900);
    }

    // Clipboard API fails on some local dev setups (non-https). Use a fallback.
    function fallbackCopy(text) {
      const $tmp = $('<textarea readonly></textarea>')
        .css({ position: 'absolute', left: '-9999px', top: '0', opacity: 0 })
        .val(text);
      $('body').append($tmp);
      $tmp[0].select();
      $tmp[0].setSelectionRange(0, 99999);
      let ok = false;
      try {
        ok = document.execCommand('copy');
      } catch (e) {
        ok = false;
      }
      $tmp.remove();
      return ok;
    }

    if (navigator.clipboard && navigator.clipboard.writeText) {
      navigator.clipboard
        .writeText(val)
        .then(flashCopied)
        .catch(() => {
          if (fallbackCopy(val)) flashCopied();
        });
    } else {
      if (fallbackCopy(val)) flashCopied();
    }
  });

  // Design color picker sync (color input has NO name; it only updates the hex input)
  function normalizeHex(v) {
    if (!v) return '';
    v = ('' + v).trim();
    if (v[0] !== '#') v = '#' + v;
    if (/^#[0-9a-fA-F]{3}$/.test(v)) {
      v = '#' + v[1] + v[1] + v[2] + v[2] + v[3] + v[3];
    }
    if (!/^#[0-9a-fA-F]{6}$/.test(v)) return '';
    return v.toUpperCase();
  }

  $(document).on('input change', '.dabl-rr-color', function () {
    const target = $(this).data('target');
    const v = normalizeHex($(this).val());
    if (!target || !v) return;
    $('#' + target).val(v);
  });

  $(document).on('input change', '.dabl-rr-hex', function () {
    const id = $(this).attr('id');
    const v = normalizeHex($(this).val());
    if (!id) return;
    if (v) {
      $(this).val(v);
      $('.dabl-rr-color[data-target="' + id + '"]').val(v);
    }
  });

  // Hours of operation: disable open/close when day is set to Closed
  function syncClosedRow($row) {
    const closed = $row.find('.dabl-rr-day-closed').is(':checked');
    $row.find('.dabl-rr-day-open, .dabl-rr-day-close').prop('disabled', closed);
  }

  $(document).on('change', '.dabl-rr-day-closed', function () {
    syncClosedRow($(this).closest('tr'));
  });

  // Initial sync
  $('.dabl-rr-day-closed').each(function () {
    syncClosedRow($(this).closest('tr'));
  });


  // Block reservations UI (Availability tab)
  function blocksEls() {
    return {
      hidden: $('.dabl-rr-blocks-json').first(),
      tbody: $('#dabl-rr-blocks-tbody').first(),
      start: $('#dabl-rr-block-start'),
      end: $('#dabl-rr-block-end'),
      type: $('#dabl-rr-block-type'),
      from: $('#dabl-rr-block-from'),
      to: $('#dabl-rr-block-to'),
      add: $('#dabl-rr-block-add')
    };
  }

  function readBlocks() {
    var el = blocksEls();
    if (!el.hidden.length) return [];
    try {
      var v = el.hidden.val() || '[]';
      var arr = JSON.parse(v);
      return Array.isArray(arr) ? arr : [];
    } catch (e) {
      return [];
    }
  }

  function writeBlocks(arr) {
    var el = blocksEls();
    if (!el.hidden.length) return;
    el.hidden.val(JSON.stringify(arr || []));
  }

  function renderBlocks() {
    var el = blocksEls();
    if (!el.tbody.length) return;
    var blocks = readBlocks();

    el.tbody.empty();
    blocks.forEach(function (b, idx) {
      var modeKey = (b && b.mode) ? b.mode : 'full';
      var modeLabel = (modeKey === 'range') ? 'Time range' : 'Full day';
      var timeLabel = (modeKey === 'range') ? ((b.from || '') + '–' + (b.to || '')) : '';
      var $tr = $('<tr>').attr('data-idx', idx);
      $('<td>').text(b.start || '').appendTo($tr);
      $('<td>').text(b.end || '').appendTo($tr);
      $('<td>').text(modeLabel).appendTo($tr);
      $('<td>').text(timeLabel).appendTo($tr);
      var $rm = $('<button type="button" class="button dabl-rr-block-remove">Remove</button>');
      $('<td>').append($rm).appendTo($tr);
      el.tbody.append($tr);
    });
  }

  function toggleBlockTimeInputs() {
    var el = blocksEls();
    if (!el.type.length) return;
    var mode = el.type.val() || 'full';
    $('.dabl-rr-block-time').toggle(mode === 'range');
  }

  // Init block UI if present
  if ($('.dabl-rr-blocks-json').length) {
    toggleBlockTimeInputs();
    renderBlocks();

    $(document).on('change', '#dabl-rr-block-type', toggleBlockTimeInputs);

    $(document).on('click', '#dabl-rr-block-add', function () {
      var el = blocksEls();
      var start = (el.start.val() || '').trim();
      var end = (el.end.val() || '').trim();
      var mode = (el.type.val() || 'full').trim();
      var from = (el.from.val() || '').trim();
      var to = (el.to.val() || '').trim();

      if (!start) { alert('Please choose a start date.'); return; }
      if (!end) end = start;

      var row = { start: start, end: end, mode: (mode === 'range') ? 'range' : 'full' };
      if (row.mode === 'range') {
        if (!from || !to) { alert('Please choose a From and To time.'); return; }
        row.from = from;
        row.to = to;
      }

      var blocks = readBlocks();
      blocks.push(row);
      writeBlocks(blocks);
      renderBlocks();

      // reset end date to start for convenience
      el.end.val('');
    });

    $(document).on('click', '.dabl-rr-block-remove', function () {
      var idx = parseInt($(this).closest('tr').attr('data-idx'), 10);
      if (isNaN(idx)) return;
      var blocks = readBlocks();
      blocks.splice(idx, 1);
      writeBlocks(blocks);
      renderBlocks();
    });
  }

  // Floorplan image uploader (Tables tab)
  function setFloorplan(url) {
    $('.dabl-rr-floorplan-url').val(url || '');
    var img = $('.dabl-rr-floorplan-preview');
    if (img.length && url) img.attr('src', url);
  }

  $(document).on('click', '.dabl-rr-floorplan-clear', function (e) {
    e.preventDefault();
    $('.dabl-rr-floorplan-url').val('');
    // Keep preview as-is (placeholder will return on reload)
    // but if current preview matches custom URL, clear it to placeholder by reloading src from data-placeholder
    var ph = $('.dabl-rr-floorplan-preview').data('placeholder');
    if (ph) $('.dabl-rr-floorplan-preview').attr('src', ph);
  });

  $(document).on('click', '.dabl-rr-floorplan-upload', function (e) {
    e.preventDefault();
    if (typeof wp === 'undefined' || !wp.media) return;

    var frame = wp.media({
      title: 'Select floorplan image',
      button: { text: 'Use this image' },
      multiple: false
    });

    frame.on('select', function () {
      var attachment = frame.state().get('selection').first();
      if (!attachment) return;
      var a = attachment.toJSON();
      if (a && a.url) {
        $('.dabl-rr-floorplan-url').val(a.url);
        $('.dabl-rr-floorplan-preview').attr('src', a.url);
      }
    });

    frame.open();
  });

  // Unsaved changes warning
  var isDirty = false;
  $('.dabl-rr-wrap form :input').on('change input', function () {
    isDirty = true;
  });

  $('.dabl-rr-wrap form').on('submit', function () {
    isDirty = false;
  });

  $(window).on('beforeunload', function () {
    if (isDirty) {
      return 'You have unsaved changes. Are you sure you want to leave?';
    }
  });


  // Gradient preview (Design tab)
  function updateGradientPreview() {
    var start = $('#dabl-rr-form_bg_gradient_start').val() || '#ffffff';
    var end = $('#dabl-rr-form_bg_gradient_end').val() || '#f3f4f6';
    var angle = parseInt($('.dabl-rr-gradient-angle-number').val() || '135', 10);
    var type = $('.dabl-rr-gradient-type').val() || 'linear';
    var bg = (type === 'radial')
      ? 'radial-gradient(circle,' + start + ',' + end + ')'
      : 'linear-gradient(' + angle + 'deg,' + start + ',' + end + ')';
    $('.dabl-rr-gradient-preview').css('background', bg);
    // hide angle controls for radial
    if (type === 'radial') {
      $('.dabl-rr-gradient-angle-range, .dabl-rr-gradient-angle-number').prop('disabled', true);
    } else {
      $('.dabl-rr-gradient-angle-range, .dabl-rr-gradient-angle-number').prop('disabled', false);
    }
  }

  $(document).on('input change', '.dabl-rr-gradient-angle-range', function(){
    $('.dabl-rr-gradient-angle-number').val($(this).val());
    updateGradientPreview();
  });
  $(document).on('input change', '.dabl-rr-gradient-angle-number', function(){
    $('.dabl-rr-gradient-angle-range').val($(this).val());
    updateGradientPreview();
  });
  $(document).on('change', '.dabl-rr-gradient-type', function(){
    updateGradientPreview();
  });
  $(document).on('input change', '#dabl-rr-form_bg_gradient_start, #dabl-rr-form_bg_gradient_end', function(){
    updateGradientPreview();
  });

  // Run once on load
  updateGradientPreview();

});