/**
 * Campaign Dates - Sync with WordPress Publish Box
 *
 * Updates the WordPress publish date UI when campaign start date changes.
 */
(function ($) {
  // Keep track of the last value we applied to avoid spamming editPost()
  let lastApplied = null;

  // Convert various input formats to a WP-friendly post "date" string: YYYY-MM-DDTHH:mm:ss
  function toWpDateString(val) {
    if (!val) return null;

    // Normalize: allow "YYYY-MM-DD HH:mm" and "YYYY-MM-DDTHH:mm"
    let v = String(val).trim().replace(' ', 'T');

    // Add seconds if missing (common for <input type="datetime-local">)
    if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/.test(v)) {
      v += ':00';
    }

    // Basic validation
    if (!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}$/.test(v)) {
      return null;
    }

    return v;
  }

  // Update Gutenberg publish date in realtime based on the campaign start date field
  function syncPublishDateWithCampaignStart(campaignStartRaw) {
    const dateString = toWpDateString(campaignStartRaw);

    if (!dateString) {
      console.warn('Invalid campaign start date value:', campaignStartRaw);
      return;
    }

    // Ensure this is running inside WP admin + block editor context
    if (!window.wp || !wp.data) {
      console.warn('wp.data not available (not in block editor context)');
      return;
    }

    const editorSelect = wp.data.select('core/editor');
    const editorDispatch = wp.data.dispatch('core/editor');

    // Current edited value (what the UI shows), not necessarily what's saved
    const currentEditedDate = editorSelect.getEditedPostAttribute('date');

    // Avoid infinite loops / redundant dispatches
    if (lastApplied === dateString || currentEditedDate === dateString) {
      return;
    }
    lastApplied = dateString;

    // This updates the "Publish" date shown in the sidebar immediately
    editorDispatch.editPost({ date: dateString });
  }

  // TODO: should we make general and expose?
  //   window.syncPublishDateWithCampaignStart = syncPublishDateWithCampaignStart;

  // ---- Your onchange (included) ----
  $(document).on('change', '#campaign_start_date', function () {
    syncPublishDateWithCampaignStart($(this).val());
  });
 

})(jQuery);