/**
 * Admin Theme Overrides - JavaScript styling for themed form elements
 *
 * This file contains JavaScript that applies theme styles to elements that cannot
 * be styled purely with CSS in the admin form builder (pseudo-elements, input-groups, etc.)
 *
 * Mirrors frontend/js/themes/overrides.js logic for consistent admin preview styling.
 */

/**
 * Style file upload ::file-selector-button to match theme
 * Applies minimal styling to make the button blend with the form theme
 */
jQuery(document).ready(function(jq) {
  function styleFileUploadButtons() {
    var fileButtonStylesId = 'gf-admin-file-button-styles';
    var styleElement = document.getElementById(fileButtonStylesId);
    var cssRules = '';

    // Handle themed file upload buttons (not in .gf-no-theme containers)
    var themedFileInputs = jq('input[type="file"]:not(.gf-no-theme *)');

    themedFileInputs.each(function(index) {
      var fileInput = jq(this);

      // Skip if this input is inside a .gf-no-theme container
      if (fileInput.closest('.gf-no-theme').length) {
        return; // continue to next iteration
      }

      var styles = window.getComputedStyle(fileInput[0]);
      var elem = fileInput[0];
      var inputId = elem.id || 'gf-file-input-' + index;

      // Ensure element has an ID for targeting
      if (!elem.id) {
        elem.id = inputId;
      }

      // Get text color and border radius from the input
      var textColor = styles.color;
      var borderRadius = styles.borderRadius || styles.borderTopLeftRadius;

      // Generate CSS rules for themed file input buttons
      // Note: background-color and border are handled by CSS (theme styles)
      // JavaScript only applies theme-specific properties like color and border-radius
      cssRules += '#' + inputId + '::file-selector-button {' +
        'padding: 6px 14px 6px 14px !important;' +
        'margin-left: 0px !important;' +
        'margin-right: 0.5rem !important;' +
        'color: ' + textColor + ' !important;' +
        'border-radius: ' + borderRadius + ' !important;' +
        'cursor: pointer !important;' +
        'transition: border-color 0.15s ease-in-out !important;' +
      '}';
    });

    // Create or update the style element
    if (!styleElement) {
      styleElement = document.createElement('style');
      styleElement.id = fileButtonStylesId;
      document.head.appendChild(styleElement);
    }
    styleElement.textContent = cssRules;
  }

  /**
   * Style griffinforms-phone-input-group elements to match themed input fields
   * Handles first element (flag span) and input field positioning intelligently
   * Uses event delegation on parent element since form HTML is injected via AJAX
   */
  // Helper function to convert kebab-case CSS property to camelCase JavaScript property
  function cssPropertyToCamelCase(cssProp) {
    return cssProp.replace(/-([a-z])/g, function(_, letter) {
      return letter.toUpperCase();
    });
  }

  function buildChevronDataUri(strokeColor) {
    var safeColor = strokeColor || '#6c757d';
    var svg = "<svg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'><polyline points='2,4 6,8 10,4' fill='none' stroke='" + safeColor + "' stroke-width='1.8' stroke-linecap='round' stroke-linejoin='round'/></svg>";
    return 'url("data:image/svg+xml,' + encodeURIComponent(svg) + '")';
  }

  function stylePhoneInputGroup(group) {
    var groupObj = jq(group);
    var children = groupObj.children();
    var input = groupObj.find('input[type="tel"]').first();
    if (!input.length) {
      input = groupObj.find('input, select, textarea').first();
    }
    var countrySelect = groupObj.find('select.griffinforms-phone-country-select').first();

    if (!input.length || children.length < 2) return;

    var styles = window.getComputedStyle(input[0]);
    if (countrySelect.length) {
      countrySelect[0].style.setProperty('color', styles.color, 'important');
      countrySelect[0].style.setProperty('--gf-phone-caret-image', buildChevronDataUri(styles.color));
    }
    var inputIndex = children.index(input);
    var firstChild = children.first();
    var lastChild = children.last();
    var hasElementBefore = inputIndex > 0;
    var hasElementAfter = inputIndex < children.length - 1;

    // Check if input has minimal styling (bottom border only, no radius)
    // This pattern is common for underlined/minimal input themes
    var hasTopBorder = parseFloat(styles.borderTopWidth) > 0;
    var hasLeftBorder = parseFloat(styles.borderLeftWidth) > 0;
    var hasRadius = parseFloat(styles.borderTopLeftRadius) > 0 || parseFloat(styles.borderTopRightRadius) > 0;
    var isMinimalStyle = !hasTopBorder && !hasLeftBorder && !hasRadius;

    // Helper function to apply border styles to an element
    function applyBorderStyles(element, sides) {
      var elem = element[0];
      var borderProps = ['Width', 'Style', 'Color'];
      var radiusMap = {
        'left': ['border-top-left-radius', 'border-bottom-left-radius'],
        'right': ['border-top-right-radius', 'border-bottom-right-radius']
      };

      // Apply border properties for specified sides
      jq.each(sides.borders, function(i, side) {
        var capitalSide = side.charAt(0).toUpperCase() + side.slice(1);
        jq.each(borderProps, function(j, prop) {
          var cssProp = 'border-' + side + '-' + prop.toLowerCase();
          var value = styles['border' + capitalSide + prop];

          // Only apply if value is not 'none' or '0px' (skip absent borders)
          if (value && value !== 'none' && parseFloat(value) !== 0) {
            elem.style.setProperty(cssProp, value, 'important');
          }
        });
      });

      // Zero out opposite borders
      jq.each(sides.zeroBorders, function(i, side) {
        elem.style.setProperty('border-' + side + '-width', '0', 'important');
        elem.style.setProperty('border-' + side + '-style', 'none', 'important');
      });

      // Skip radius styling for minimal (bottom-border-only) themes
      if (!isMinimalStyle) {
        // Apply border radius
        jq.each(sides.radius, function(i, side) {
          jq.each(radiusMap[side], function(j, radiusProp) {
            var camelCaseProperty = cssPropertyToCamelCase(radiusProp);
            var value = styles[camelCaseProperty];
            if (value && value !== 'none' && parseFloat(value) !== 0) {
              elem.style.setProperty(radiusProp, value, 'important');
            }
          });
        });
      }

      // Copy text color
      elem.style.setProperty('color', styles.color, 'important');

      // Set background to semi-transparent version of border color (for non-input elements)
      // Skip background for minimal style themes and for select elements (use theme CSS instead)
      if (elem !== input[0] && !isMinimalStyle && elem.tagName !== 'SELECT') {
        var borderColor = styles.borderTopColor;
        var rgbaMatch = borderColor.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*[\d.]+)?\)/);
        if (rgbaMatch) {
          var r = rgbaMatch[1];
          var g = rgbaMatch[2];
          var b = rgbaMatch[3];
          elem.style.setProperty('background-color', 'rgba(' + r + ', ' + g + ', ' + b + ', 0.1)', 'important');
        }
      }
    }

    // Style first element if it's not the input
    if (firstChild[0] !== input[0]) {
      // For minimal style, remove all borders/background - keep only text color
      if (isMinimalStyle) {
        var elem = firstChild[0];
        elem.style.setProperty('border', 'none', 'important');
        elem.style.setProperty('background', 'transparent', 'important');
        elem.style.setProperty('color', styles.color, 'important');
      } else {
        if (countrySelect.length && firstChild[0] === countrySelect[0]) {
          applyBorderStyles(firstChild, {
            borders: ['top', 'bottom', 'left'],
            zeroBorders: ['right'],
            radius: ['left'],
            zeroRadius: ['right']
          });
          firstChild[0].style.setProperty('border-top-right-radius', '0', 'important');
          firstChild[0].style.setProperty('border-bottom-right-radius', '0', 'important');
          // Share input border style with the select so the divider matches theme
          var borderWidth = styles.borderRightWidth;
          var borderStyle = styles.borderRightStyle;
          var borderColor = styles.borderRightColor;
          var fallbackColor = borderColor || styles.borderTopColor || styles.borderColor;
          var fallbackWidth = styles.borderBottomWidth || styles.borderTopWidth;
          var fallbackStyle = styles.borderBottomStyle || styles.borderTopStyle;
          var useWidth = (borderWidth && parseFloat(borderWidth) > 0) ? borderWidth : fallbackWidth;
          var useStyle = (borderStyle && borderStyle !== 'none') ? borderStyle : fallbackStyle;
          if (!useStyle || useStyle === 'none') {
            useStyle = 'solid';
          }
          if (!useWidth || parseFloat(useWidth) === 0) {
            useWidth = '1px';
          }
          if (fallbackColor) {
            firstChild[0].style.setProperty('--gf-phone-border-color', fallbackColor);
          }
          firstChild[0].style.setProperty('--gf-phone-border-width', useWidth);
          firstChild[0].style.setProperty('--gf-phone-border-style', useStyle);
          if (fallbackColor) {
            firstChild[0].style.setProperty('--gf-phone-border-color', fallbackColor);
            firstChild[0].style.setProperty('border-right-color', fallbackColor, 'important');
            firstChild[0].style.setProperty('box-shadow', 'inset -' + useWidth + ' 0 0 ' + fallbackColor, 'important');
          }
          firstChild[0].style.setProperty('border-right-width', useWidth, 'important');
          firstChild[0].style.setProperty('border-right-style', useStyle, 'important');
        } else {
          applyBorderStyles(firstChild, {
            borders: ['top', 'bottom', 'left'],
            zeroBorders: ['right'],
            radius: ['left'],
            zeroRadius: ['right']
          });
        }
      }
    }

    // Style last element if it's not the input
    if (lastChild[0] !== input[0] && lastChild[0] !== firstChild[0]) {
      // For minimal style, remove all borders/background - keep only text color
      if (isMinimalStyle) {
        var elem = lastChild[0];
        elem.style.setProperty('border', 'none', 'important');
        elem.style.setProperty('background', 'transparent', 'important');
        elem.style.setProperty('color', styles.color, 'important');
      } else {
        applyBorderStyles(lastChild, {
          borders: ['top', 'bottom', 'right'],
          zeroBorders: ['left'],
          radius: ['right'],
          zeroRadius: ['left']
        });
      }
    }

    // Style input field based on its position
    var inputElem = input[0];
    if (hasElementBefore && hasElementAfter) {
      // Input has elements on both sides - zero all borders
      inputElem.style.setProperty('border-left-width', '0', 'important');
      inputElem.style.setProperty('border-right-width', '0', 'important');
      inputElem.style.setProperty('border-left-style', 'none', 'important');
      inputElem.style.setProperty('border-right-style', 'none', 'important');
      inputElem.style.setProperty('border-top-left-radius', '0', 'important');
      inputElem.style.setProperty('border-bottom-left-radius', '0', 'important');
      inputElem.style.setProperty('border-top-right-radius', '0', 'important');
      inputElem.style.setProperty('border-bottom-right-radius', '0', 'important');
    } else if (hasElementBefore) {
      // Input has element before - zero left radius only
      inputElem.style.setProperty('border-left-width', '0', 'important');
      inputElem.style.setProperty('border-left-style', 'none', 'important');
      inputElem.style.setProperty('border-top-left-radius', '0', 'important');
      inputElem.style.setProperty('border-bottom-left-radius', '0', 'important');
    } else if (hasElementAfter) {
      // Input has element after - zero right border
      inputElem.style.setProperty('border-right-width', '0', 'important');
      inputElem.style.setProperty('border-right-style', 'none', 'important');
      inputElem.style.setProperty('border-top-right-radius', '0', 'important');
      inputElem.style.setProperty('border-bottom-right-radius', '0', 'important');
    }
  }

  // Function to find and style all phone input groups
  function processPhoneInputGroups() {
    var groups = jq('.griffinforms-phone-input-group');
    console.log('Processing phone input groups:', groups.length);
    groups.each(function() {
      stylePhoneInputGroup(this);
    });
  }

  // Function to process all themed form elements
  function processThemedElements() {
    // Only process if form has a valid theme assigned
    if (!hasValidTheme()) {
      return;
    }
    styleFileUploadButtons();
    processPhoneInputGroups();
  }

  // Check if the form has a valid theme ID
  // Scoped to presentation area parent element to handle AJAX-injected forms
  function hasValidTheme() {
    var presentationArea = document.querySelector('#griffinforms-app-presentationarea');
    if (!presentationArea) {
      return false;
    }
    // Query form container within the presentation area (for AJAX-injected content)
    var formContainer = presentationArea.querySelector('.griffinforms-app-formlayout-form');
    if (!formContainer) {
      return false;
    }
    var themeId = formContainer.getAttribute('data-gf-theme-id');
    return themeId && parseInt(themeId, 10) > 0;
  }

  // Process all themed elements on page load
  console.log('Admin overrides.js loaded and ready');
  processThemedElements();

  // Listen for custom event fired when form HTML is received via AJAX
  document.addEventListener('form-html-received', function() {
    console.log('form-html-received event detected');
    // Delay slightly to ensure DOM is fully updated
    setTimeout(function() {
      processThemedElements();
    }, 50);
  });

  // Also use MutationObserver as fallback for other dynamic content
  if (window.MutationObserver) {
    var presentationArea = document.querySelector('#griffinforms-app-presentationarea');
    if (presentationArea) {
      var observer = new MutationObserver(function() {
        processThemedElements();
      });

      observer.observe(presentationArea, {
        childList: true,
        subtree: true,
        attributes: false
      });
    }
  }
});
