Review and analyse all of the codes to improve them further accordingly.

Make sure all of the CORS headers are always set properly and correctly on all of requests, responses, requested resources, etc. 

ensure it handles all of the requests, responses and preflight or option with extreme accuracy. 

Ensure all of the CORS headers are settled With Extreme accuracy and carefulness on all requests or responses or requested resources as they should with their appropriate and authentic values so that user won't encounter any CORS Policy restrictions error on any requests or response or requested resources.

make it extremely Highly customisable with lots of features, like user can easily change on which resources types or methods CORS headers should be settled, etc.

In default settings set all of the appropriate CORS headers with valid and appropriate values on all resources or content types of responses.

make sure user can customise on which web page or domain's request or responses the CORS headers are being set, etc.

make sure before browser recieves the response all of the CORS headers are always settled successful on responses or resources or request.

show the real time authentic feedback on which domain or webpage this extension is working right now.

Make this extension practically feasible.

Make sure it should work flawlessly in real-world scenarios.

improve the code quality.

don't add unnecessary complexity.

always and handle all of the possible or potential consequences or edge cases or errors or bottlenecks flawlessly.

Make sure that the CORS headers value is valid and authentic.

don't add rate limit.

don't add unnecessary logging.

Keep it straightforward, fast, reliable and powerful.

Send the fully working chrome extension's full codes.

// background.js

// Import necessary modules if any (Currently not using separate modules)
// If you decide to modularize further, use import statements here.

// Default Configuration Object
const defaultConfig = {
  enabled: false,
  responseHeaders: [
    { name: "Access-Control-Allow-Origin", value: "*", enabled: true, priority: 100 },
    { name: "Access-Control-Allow-Methods", value: "GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS", enabled: true, priority: 90 },
    { name: "Access-Control-Allow-Headers", value: "*", enabled: true, priority: 80 },
    { name: "Access-Control-Allow-Credentials", value: "true", enabled: true, priority: 70 },
    { name: "Access-Control-Expose-Headers", value: "*", enabled: true, priority: 60 },
    { name: "Access-Control-Max-Age", value: "86400", enabled: true, priority: 50 },
    { name: "Cross-Origin-Opener-Policy", value: "same-origin", enabled: true, priority: 40 },
    { name: "Cross-Origin-Resource-Policy", value: "cross-origin", enabled: true, priority: 30 },
    { name: "Cross-Origin-Embedder-Policy", value: "require-corp", enabled: true, priority: 20 },
    { name: "Timing-Allow-Origin", value: "*", enabled: true, priority: 10 }
  ],
  requestHeaders: [
    { name: "Origin", value: "null", enabled: true, priority: 100 },
    { name: "Access-Control-Request-Method", value: "*", enabled: true, priority: 90 },
    { name: "Access-Control-Request-Headers", value: "*", enabled: true, priority: 80 }
  ],
  urlRules: [
    { pattern: "*://*/*", enabled: true, resourceTypes: [
      "main_frame",
      "sub_frame",
      "stylesheet",
      "script",
      "image",
      "font",
      "object",
      "xmlhttprequest",
      "ping",
      "csp_report",
      "media",
      "websocket",
      "webtransport",
      "webbundle",
      "other"
    ], priority: 100 }
  ],
  advanced: {
    enablePreflightCaching: true,
    preflightMaxAge: 86400,
    allowCredentials: true,
    allowPrivateNetwork: true,
    enableDebugHeaders: false
  }
};

// CORSHandler Class
class CORSHandler {
  constructor() {
    this.currentConfig = null;
    this.ruleIdCounter = 1000; // Starting ID for dynamic rules to avoid conflicts
    this.initialize();
  }

  // Initialize the handler by loading config and setting up rules
  async initialize() {
    await this.loadConfig();
    await this.updateRules(this.currentConfig);
    this.setupListeners();
  }

  // Load configuration from storage or use default
  async loadConfig() {
    try {
      const result = await chrome.storage.local.get('corsConfig');
      this.currentConfig = result.corsConfig ? this.deepClone(result.corsConfig) : this.deepClone(defaultConfig);
    } catch (error) {
      console.error('Error loading configuration:', error);
      this.currentConfig = this.deepClone(defaultConfig);
    }
  }

  // Deep clone utility to prevent reference issues
  deepClone(obj) {
    return JSON.parse(JSON.stringify(obj));
  }

  // Setup event listeners
  setupListeners() {
    // Listen for messages from popup or other parts
    chrome.runtime.onMessage.addListener(this.handleMessage.bind(this));

    // Listen for navigation events to update badge
    chrome.webNavigation.onCompleted.addListener(this.handleNavigation.bind(this));

    // Listen for tab activation to update badge
    chrome.tabs.onActivated.addListener(this.handleTabChange.bind(this));

    // Listen for link updates within tabs
    chrome.tabs.onUpdated.addListener(this.handleTabUpdate.bind(this));
  }

  // Handle incoming messages
  async handleMessage(message, sender, sendResponse) {
    switch (message.type) {
      case 'updateRules':
        await this.updateRules(message.config);
        break;
      case 'getStatus':
        const activeRules = await this.getActiveRules();
        sendResponse({
          enabled: this.currentConfig.enabled,
          activeOrigin: this.activeOrigin || 'N/A',
          activeRules: activeRules.length
        });
        break;
      default:
        console.warn('Unknown message type:', message.type);
    }
    // Return true to indicate asynchronous response
    return true;
  }

  // Handle navigation completion to update badge
  async handleNavigation(details) {
    if (details.frameId === 0) { // Main frame
      this.activeOrigin = new URL(details.url).origin;
      await this.updateBadge();
    }
  }

  // Handle tab activation to update badge
  async handleTabChange(activeInfo) {
    try {
      const tab = await chrome.tabs.get(activeInfo.tabId);
      if (tab.url) {
        this.activeOrigin = new URL(tab.url).origin;
        await this.updateBadge();
      }
    } catch (error) {
      console.error('Error handling tab change:', error);
      this.activeOrigin = null;
      await this.updateBadge();
    }
  }

  // Handle tab updates (like URL changes)
  async handleTabUpdate(tabId, changeInfo, tab) {
    if (changeInfo.url && tab.active) {
      this.activeOrigin = new URL(changeInfo.url).origin;
      await this.updateBadge();
    }
  }

  // Update CORS rules based on config
  async updateRules(config) {
    if (!config || typeof config !== 'object') {
      console.error('Invalid configuration provided');
      return;
    }

    try {
      // Remove existing dynamic rules
      const existingRules = await chrome.declarativeNetRequest.getDynamicRules();
      const ruleIdsToRemove = existingRules.map(rule => rule.id);
      if (ruleIdsToRemove.length > 0) {
        await chrome.declarativeNetRequest.updateDynamicRules({
          removeRuleIds: ruleIdsToRemove,
          addRules: []
        });
      }

      if (!config.enabled) {
        await this.updateIcon(false);
        await this.updateBadge();
        return;
      }

      // Create new rules based on config
      const newRules = this.createRules(config);
      if (newRules.length > 0) {
        await chrome.declarativeNetRequest.updateDynamicRules({
          addRules: newRules
        });

        this.updateIcon(true);
        this.updateBadge();
      }
    } catch (error) {
      console.error('Error updating rules:', error);
    }
  }

  // Create dynamic rules from configuration
  createRules(config) {
    const rules = [];

    // Sort headers by priority descending
    const sortedResponseHeaders = config.responseHeaders
      .filter(header => header.enabled)
      .sort((a, b) => b.priority - a.priority);
    
    const sortedRequestHeaders = config.requestHeaders
      .filter(header => header.enabled)
      .sort((a, b) => b.priority - a.priority);

    config.urlRules.forEach(urlRule => {
      if (!urlRule.enabled) return;

      // Prepare response headers modifications
      const responseHeaders = sortedResponseHeaders.map(header => ({
        header: header.name,
        operation: "set",
        value: this.processHeaderValue(header.name, header.value)
      }));

      // Prepare request headers modifications
      const requestHeaders = sortedRequestHeaders.map(header => ({
        header: header.name,
        operation: "set",
        value: this.processHeaderValue(header.name, header.value)
      }));

      // Create rule for modifying headers
      rules.push({
        id: this.ruleIdCounter++,
        priority: urlRule.priority,
        action: {
          type: "modifyHeaders",
          responseHeaders: responseHeaders,
          requestHeaders: requestHeaders
        },
        condition: {
          urlFilter: this.convertPatternToFilter(urlRule.pattern),
          resourceTypes: urlRule.resourceTypes
        }
      });

      // Special handling for OPTIONS (preflight) requests if caching is enabled
      if (config.advanced.enablePreflightCaching) {
        rules.push({
          id: this.ruleIdCounter++,
          priority: urlRule.priority + 1,
          action: {
            type: "modifyHeaders",
            responseHeaders: [
              ...responseHeaders,
              {
                header: "Access-Control-Max-Age",
                operation: "set",
                value: config.advanced.preflightMaxAge.toString()
              }
            ]
          },
          condition: {
            urlFilter: this.convertPatternToFilter(urlRule.pattern),
            requestMethods: ["OPTIONS"],
            resourceTypes: ["xmlhttprequest", "fetch", "websocket"]
          }
        });
      }
    });

    return rules;
  }

  // Convert wildcard URL patterns to Chrome's declarativeNetRequest URL filter syntax
  convertPatternToFilter(pattern) {
    // Chrome declarativeNetRequest uses simple substring matching.
    // Therefore, convert patterns like "*://*.example.com/*" to "*://*.example.com/*"
    // No conversion needed; but additional processing can be added if necessary.
    return pattern;
  }

  // Process header values based on header name and config
  processHeaderValue(name, value) {
    name = name.toLowerCase();
    switch (name) {
      case 'access-control-allow-origin':
        // If credentials are allowed, set to activeOrigin instead of '*'
        if (this.currentConfig.advanced.allowCredentials) {
          return this.activeOrigin || 'null'; // 'null' for Originless requests
        }
        return value;
      case 'access-control-allow-credentials':
        return this.currentConfig.advanced.allowCredentials.toString();
      case 'access-control-allow-private-network':
        return this.currentConfig.advanced.allowPrivateNetwork.toString();
      default:
        return value;
    }
  }

  // Get active dynamic rules
  async getActiveRules() {
    try {
      return await chrome.declarativeNetRequest.getDynamicRules();
    } catch (error) {
      console.error('Error fetching active rules:', error);
      return [];
    }
  }

  // Update extension icon based on enabled state
  async updateIcon(enabled) {
    const iconState = enabled ? "-on" : "-off";
    try {
      await chrome.action.setIcon({
        path: {
          "16": `icons/icon16${iconState}.png`,
          "48": `icons/icon48${iconState}.png`,
          "128": `icons/icon128${iconState}.png`
        }
      });
    } catch (error) {
      console.error('Error setting icon:', error);
    }
  }

  // Update badge to show number of active rules
  async updateBadge() {
    try {
      if (!this.currentConfig.enabled) {
        await chrome.action.setBadgeText({ text: "" });
        return;
      }

      const activeRules = await this.getActiveRules();
      await chrome.action.setBadgeText({
        text: activeRules.length.toString()
      });
      await chrome.action.setBadgeBackgroundColor({
        color: "#4CAF50"
      });
    } catch (error) {
      console.error('Error updating badge:', error);
    }
  }
}

// Initialize the CORS handler
new CORSHandler();

// Handle installation and startup events
chrome.runtime.onInstalled.addListener(async () => {
  try {
    const result = await chrome.storage.local.get('corsConfig');
    const config = result.corsConfig ? JSON.parse(JSON.stringify(result.corsConfig)) : JSON.parse(JSON.stringify(defaultConfig));
    await chrome.storage.local.set({ corsConfig: config });
    // Rules will be updated by CORSHandler initialization
  } catch (error) {
    console.error('Error during installation:', error);
  }
});

chrome.runtime.onStartup.addListener(async () => {
  try {
    const result = await chrome.storage.local.get('corsConfig');
    const config = result.corsConfig ? JSON.parse(JSON.stringify(result.corsConfig)) : JSON.parse(JSON.stringify(defaultConfig));
    // Rules will be updated by CORSHandler initialization
  } catch (error) {
    console.error('Error during startup:', error);
  }
});

{
  "manifest_version": 3,
  "name": "Enhanced CORS Handler Pro",
  "version": "2.0",
  "description": "Advanced CORS handling with full customization and real-time feedback",
  "permissions": [
    "declarativeNetRequest",
    "activeTab",
    "storage",
    "webNavigation"
  ],
  "host_permissions": [
    "<all_urls>"
  ],
  "action": {
    "default_popup": "popup.html",
    "default_icon": {
      "16": "icons/icon16-off.png",
      "48": "icons/icon48-off.png",
      "128": "icons/icon128-off.png"
    }
  },
  "background": {
    "service_worker": "background.js",
    "type": "module"
  },
  "icons": {
    "16": "icons/icon16-off.png",
    "48": "icons/icon48-off.png",
    "128": "icons/icon128-off.png"
  }
}

/* popup.css */

body {
  margin: 0;
  padding: 0;
  background-color: #ffffff;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
}

.container {
  width: 100%;
  max-width: 450px;
  padding: 16px;
  box-sizing: border-box;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.toggle-container {
  display: flex;
  align-items: center;
  gap: 8px;
}

.switch {
  position: relative;
  display: inline-block;
  width: 50px;
  height: 26px;
}

.switch input {
  opacity: 0;
  width: 0;
  height: 0;
}

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  transition: .4s;
  border-radius: 26px;
}

.slider:before {
  position: absolute;
  content: "";
  height: 20px;
  width: 20px;
  left: 3px;
  bottom: 3px;
  background-color: white;
  transition: .4s;
  border-radius: 50%;
}

input:checked + .slider {
  background-color: #2196F3;
}

input:checked + .slider:before {
  transform: translateX(24px);
}

.tab-container {
  display: flex;
  gap: 8px;
  margin-bottom: 16px;
  overflow-x: auto;
}

.tab-button {
  padding: 8px 16px;
  border: none;
  background: #f0f0f0;
  cursor: pointer;
  border-radius: 4px;
  flex-shrink: 0;
  transition: background-color 0.3s, color 0.3s;
}

.tab-button.active {
  background: #2196F3;
  color: white;
}

.tab-content {
  display: none;
  padding: 16px;
  background: #f8f8f8;
  border-radius: 4px;
  max-height: 300px;
  overflow-y: auto;
}

.tab-content.active {
  display: block;
}

.header-item, .url-rule-item {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;
  position: relative;
}

.header-item input[type="text"], .url-rule-item input[type="text"] {
  padding: 6px;
  border: 1px solid #ddd;
  border-radius: 4px;
  flex: 1;
  min-width: 0; /* Prevents overflowing in flex containers */
}

.header-item input[type="text"].invalid, .url-rule-item input[type="text"].invalid {
  border-color: #ff4444;
}

.header-item .error-message, .url-rule-item .error-message {
  color: #ff4444;
  font-size: 12px;
  position: absolute;
  top: 100%;
  left: 0;
  white-space: nowrap;
}

.remove-button {
  padding: 4px 8px;
  background: #ff4444;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  flex-shrink: 0;
  height: 30px;
}

.add-header, .add-rule {
  width: 100%;
  padding: 8px;
  margin-top: 12px;
  background: #2196F3;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.add-header:hover, .add-rule:hover {
  background: #1976D2;
}

.footer {
  margin-top: 20px;
  display: flex;
  justify-content: space-between;
}

.footer button {
  flex: 1;
  padding: 10px 0;
  margin: 0 4px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

#saveButton {
  background: #4CAF50;
  color: white;
}

#saveButton:hover {
  background: #43A047;
}

#resetDefault {
  background: #f0f0f0;
  color: #333;
}

#resetDefault:hover {
  background: #e0e0e0;
}

.disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.advanced-settings {
  margin-top: 20px;
  padding: 16px;
  background: #f8f8f8;
  border-radius: 4px;
}

.setting-item {
  margin-bottom: 12px;
}

.setting-item label {
  display: flex;
  align-items: center;
  gap: 8px;
}

.status-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.status-item .status-label {
  font-weight: bold;
}

.status-item .status-value.enabled {
  color: #4CAF50;
}

.status-item .status-value.disabled {
  color: #ff4444;
}

.debug-panel {
  margin-top: 16px;
  padding: 12px;
  background: #f0f0f0;
  border-radius: 4px;
  font-family: monospace;
  font-size: 12px;
  max-height: 150px;
  overflow-y: auto;
}

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Enhanced CORS Handler Pro Settings</title>
  <link rel="stylesheet" href="popup.css">
</head>
<body>
  <div class="container">
    <div class="header">
      <h2>Enhanced CORS Handler Pro</h2>
      <div class="toggle-container">
        <label class="switch" aria-label="Enable or disable CORS Handler">
          <input type="checkbox" id="globalToggle">
          <span class="slider"></span>
        </label>
        <span id="statusText">Disabled</span>
      </div>
    </div>

    <div class="settings-container">
      <div class="tab-container" role="tablist">
        <button class="tab-button active" data-tab="response" role="tab" aria-selected="true">Response Headers</button>
        <button class="tab-button" data-tab="request" role="tab" aria-selected="false">Request Headers</button>
        <button class="tab-button" data-tab="rules" role="tab" aria-selected="false">URL Rules</button>
        <button class="tab-button" data-tab="advanced" role="tab" aria-selected="false">Advanced Settings</button>
      </div>

      <!-- Response Headers Tab -->
      <div class="tab-content active" id="response" role="tabpanel">
        <div class="header-list" id="responseHeaders">
          <!-- Dynamically populated -->
        </div>
        <button class="add-header" id="addResponseHeader">+ Add Response Header</button>
      </div>

      <!-- Request Headers Tab -->
      <div class="tab-content" id="request" role="tabpanel">
        <div class="header-list" id="requestHeaders">
          <!-- Dynamically populated -->
        </div>
        <button class="add-header" id="addRequestHeader">+ Add Request Header</button>
      </div>

      <!-- URL Rules Tab -->
      <div class="tab-content" id="rules" role="tabpanel">
        <div class="url-rules" id="urlRules">
          <!-- Dynamically populated -->
        </div>
        <button class="add-rule" id="addUrlRule">+ Add URL Rule</button>
      </div>

      <!-- Advanced Settings Tab -->
      <div class="tab-content" id="advanced" role="tabpanel">
        <div class="advanced-settings">
          <h3>Advanced Settings</h3>
          <div class="setting-item">
            <label>
              <input type="checkbox" id="enablePreflightCaching">
              Enable Preflight Caching
            </label>
          </div>
          <div class="setting-item">
            <label>
              <input type="checkbox" id="allowCredentials">
              Allow Credentials
            </label>
          </div>
          <div class="setting-item">
            <label>
              <input type="checkbox" id="allowPrivateNetwork">
              Allow Private Network Access
            </label>
          </div>
          <div class="setting-item">
            <label>
              <input type="checkbox" id="enableDebugHeaders">
              Enable Debug Headers
            </label>
          </div>
          <div class="setting-item">
            <label>
              Preflight Max Age (seconds)
              <input type="number" id="preflightMaxAge" min="0" max="86400">
            </label>
          </div>
        </div>
      </div>
    </div>

    <div class="footer">
      <button id="saveButton">Save Changes</button>
      <button id="resetDefault">Reset to Default</button>
    </div>
  </div>
  <script src="popup.js"></script>
</body>
</html>

// popup.js

// Default Configuration Object (Should match background.js defaultConfig)
const defaultConfig = {
  enabled: false,
  responseHeaders: [
    { name: "Access-Control-Allow-Origin", value: "*", enabled: true },
    { name: "Access-Control-Allow-Methods", value: "GET, PUT, POST, DELETE, HEAD, OPTIONS, PATCH", enabled: true },
    { name: "Access-Control-Allow-Headers", value: "*", enabled: true },
    { name: "Access-Control-Allow-Credentials", value: "false", enabled: true },
    { name: "Access-Control-Expose-Headers", value: "*", enabled: true },
    { name: "Access-Control-Max-Age", value: "1728000", enabled: true },
    { name: "Cross-Origin-Resource-Policy", value: "cross-origin", enabled: true },
    { name: "Cross-Origin-Embedder-Policy", value: "credentialless", enabled: true }
  ],
  requestHeaders: [
    { name: "Origin", value: "https://allowed-origin.com", enabled: true },
    { name: "Access-Control-Request-Method", value: "*", enabled: true },
    { name: "Access-Control-Request-Headers", value: "*", enabled: true }
  ],
  urlRules: [
    { pattern: "*://*/*", enabled: true }
  ],
  advanced: {
    enablePreflightCaching: true,
    preflightMaxAge: 86400,
    allowCredentials: false,
    allowPrivateNetwork: false,
    enableDebugHeaders: false
  }
};

let currentConfig = null;
let hasValidationErrors = false;

// Utility function for deep cloning
function deepClone(obj) {
  return JSON.parse(JSON.stringify(obj));
}

// Load configuration from storage or use default
async function loadConfig() {
  try {
    const result = await chrome.storage.local.get('corsConfig');
    currentConfig = result.corsConfig ? deepClone(result.corsConfig) : deepClone(defaultConfig);
    renderUI();
  } catch (error) {
    console.error('Error loading configuration:', error);
    currentConfig = deepClone(defaultConfig);
    renderUI();
  }
}

// Save configuration to storage and update extension rules
async function saveConfig() {
  if (hasValidationErrors) {
    alert("Please fix validation errors before saving.");
    return;
  }

  // Additional cross-field validation
  if (!validateCrossHeaders()) {
    alert("Invalid configuration: 'Access-Control-Allow-Origin' cannot be '*' when 'Allow Credentials' is enabled. Please adjust accordingly.");
    return;
  }

  try {
    await chrome.storage.local.set({ corsConfig: currentConfig });
    await updateExtensionRules();
    showSaveSuccess();
  } catch (error) {
    console.error('Error saving configuration:', error);
    showSaveError();
  }
}

// Validate cross-header dependencies
function validateCrossHeaders() {
  const allowOriginHeader = currentConfig.responseHeaders.find(header => header.name.toLowerCase() === 'access-control-allow-origin' && header.enabled);
  const allowCredentialsHeader = currentConfig.responseHeaders.find(header => header.name.toLowerCase() === 'access-control-allow-credentials' && header.enabled);

  if (allowOriginHeader && allowCredentialsHeader) {
    if (allowOriginHeader.value.trim() === '*' && allowCredentialsHeader.value.toLowerCase() === 'true') {
      return false;
    }
  }
  return true;
}

// Update extension rules by sending a message to background script
async function updateExtensionRules() {
  const message = {
    type: 'updateRules',
    config: currentConfig
  };
  await chrome.runtime.sendMessage(message);
}

// Render the entire UI based on current configuration
function renderUI() {
  initializeGlobalToggle();
  renderHeaderList('responseHeaders');
  renderHeaderList('requestHeaders');
  renderUrlRules();
  initializeAdvancedSettings();
  toggleEnableControls(currentConfig.enabled);
}

// Initialize the global toggle switch
function initializeGlobalToggle() {
  const globalToggle = document.getElementById('globalToggle');
  globalToggle.checked = currentConfig.enabled;
  document.getElementById('statusText').textContent = currentConfig.enabled ? 'Enabled' : 'Disabled';
}

// Render headers (response or request) dynamically
function renderHeaderList(type) {
  const container = document.getElementById(type);
  container.innerHTML = '';

  currentConfig[type].forEach((header, index) => {
    const headerItem = createHeaderItem(header, index, type);
    container.appendChild(headerItem);
  });
}

// Create a header item DOM element
function createHeaderItem(header, index, type) {
  const div = document.createElement('div');
  div.className = type === 'urlRules' ? 'url-rule-item' : 'header-item';

  // Enabled Checkbox
  const enabledCheckbox = document.createElement('input');
  enabledCheckbox.type = 'checkbox';
  enabledCheckbox.checked = header.enabled;
  enabledCheckbox.setAttribute('aria-label', `Enable ${type === 'responseHeaders' || type === 'requestHeaders' ? 'Header' : 'URL Rule'}`);
  enabledCheckbox.onchange = () => {
    currentConfig[type][index].enabled = enabledCheckbox.checked;
    validateAllInputs();
    toggleEnableControls(currentConfig.enabled);
  };

  // Name or Pattern Input
  const nameInput = document.createElement('input');
  nameInput.type = 'text';
  nameInput.value = type === 'urlRules' ? header.pattern : header.name;
  nameInput.placeholder = type === 'urlRules' ? 'URL Pattern (e.g., *://*.example.com/*)' : 'Header Name';
  nameInput.setAttribute('aria-label', type === 'urlRules' ? 'URL Pattern' : 'Header Name');
  nameInput.oninput = () => {
    if (type === 'urlRules') {
      currentConfig[type][index].pattern = nameInput.value;
    } else {
      currentConfig[type][index].name = nameInput.value;
    }
    validateInput(nameInput, type, index, 'name');
    validateAllInputs();
  };

  // Value Input for Headers
  let valueInput = null;
  if (type !== 'urlRules') {
    valueInput = document.createElement('input');
    valueInput.type = 'text';
    valueInput.value = header.value;
    valueInput.placeholder = 'Header Value';
    valueInput.setAttribute('aria-label', 'Header Value');
    valueInput.oninput = () => {
      currentConfig[type][index].value = valueInput.value;
      validateInput(valueInput, type, index, 'value');
      validateAllInputs();
    };
  }

  // Remove Button
  const removeButton = document.createElement('button');
  removeButton.textContent = '×';
  removeButton.className = 'remove-button';
  removeButton.setAttribute('aria-label', 'Remove Item');
  removeButton.onclick = () => {
    currentConfig[type].splice(index, 1);
    renderHeaderList(type);
    validateAllInputs();
  };

  // Append elements
  div.appendChild(enabledCheckbox);
  div.appendChild(nameInput);
  if (valueInput) div.appendChild(valueInput);
  div.appendChild(removeButton);

  // Error Message Container
  const errorMsg = document.createElement('div');
  errorMsg.className = 'error-message';
  errorMsg.style.display = 'none';
  div.appendChild(errorMsg);

  return div;
}

// Render URL Rules dynamically
function renderUrlRules() {
  renderHeaderList('urlRules');
}

// Initialize advanced settings inputs
function initializeAdvancedSettings() {
  const adv = currentConfig.advanced;
  document.getElementById('enablePreflightCaching').checked = adv.enablePreflightCaching;
  document.getElementById('allowCredentials').checked = adv.allowCredentials;
  document.getElementById('allowPrivateNetwork').checked = adv.allowPrivateNetwork;
  document.getElementById('enableDebugHeaders').checked = adv.enableDebugHeaders;
  document.getElementById('preflightMaxAge').value = adv.preflightMaxAge;

  // Event Listeners for Advanced Settings
  document.getElementById('enablePreflightCaching').onchange = (e) => {
    currentConfig.advanced.enablePreflightCaching = e.target.checked;
    validateAllInputs();
  };

  document.getElementById('allowCredentials').onchange = (e) => {
    currentConfig.advanced.allowCredentials = e.target.checked;
    validateAllInputs();
  };

  document.getElementById('allowPrivateNetwork').onchange = (e) => {
    currentConfig.advanced.allowPrivateNetwork = e.target.checked;
    validateAllInputs();
  };

  document.getElementById('enableDebugHeaders').onchange = (e) => {
    currentConfig.advanced.enableDebugHeaders = e.target.checked;
    // Optionally, implement debug header functionality
  };

  document.getElementById('preflightMaxAge').oninput = (e) => {
    currentConfig.advanced.preflightMaxAge = e.target.value;
    validateInput(e.target, 'advanced', null, 'preflightMaxAge');
  };
}

// Toggle enabling/disabling controls based on global toggle
function toggleEnableControls(enabled) {
  const addButtons = document.querySelectorAll('.add-header, .add-rule');
  addButtons.forEach(button => {
    if (enabled) {
      button.disabled = false;
      button.classList.remove('disabled');
    } else {
      button.disabled = true;
      button.classList.add('disabled');
    }
  });

  const inputs = document.querySelectorAll('.header-item input[type="text"], .url-rule-item input[type="text"], .advanced-settings input[type="number"]');
  inputs.forEach(input => {
    if (enabled) {
      input.disabled = false;
      input.classList.remove('disabled');
    } else {
      input.disabled = true;
      input.classList.add('disabled');
    }
  });

  const checkboxes = document.querySelectorAll('.header-item input[type="checkbox"], .url-rule-item input[type="checkbox"], .advanced-settings input[type="checkbox"]');
  checkboxes.forEach(checkbox => {
    if (enabled) {
      checkbox.disabled = false;
      checkbox.classList.remove('disabled');
    } else {
      checkbox.disabled = true;
      checkbox.classList.add('disabled');
    }
  });

  const saveButton = document.getElementById('saveButton');
  const resetButton = document.getElementById('resetDefault');

  if (enabled) {
    saveButton.classList.remove('disabled');
    resetButton.classList.remove('disabled');
  } else {
    saveButton.classList.add('disabled');
    resetButton.classList.add('disabled');
  }
}

// Event Listeners for Add Buttons
document.getElementById('addResponseHeader').addEventListener('click', () => {
  currentConfig.responseHeaders.push({ name: '', value: '', enabled: true });
  renderHeaderList('responseHeaders');
});

document.getElementById('addRequestHeader').addEventListener('click', () => {
  currentConfig.requestHeaders.push({ name: '', value: '', enabled: true });
  renderHeaderList('requestHeaders');
});

document.getElementById('addUrlRule').addEventListener('click', () => {
  currentConfig.urlRules.push({ pattern: '*://*/*', enabled: true });
  renderUrlRules();
});

// Event Listeners for Save and Reset Buttons
document.getElementById('saveButton').addEventListener('click', saveConfig);

document.getElementById('resetDefault').addEventListener('click', () => {
  currentConfig = deepClone(defaultConfig);
  renderUI();
  saveConfig();
});

// Tab Handling
document.querySelectorAll('.tab-button').forEach(button => {
  button.addEventListener('click', () => {
    document.querySelectorAll('.tab-button').forEach(b => {
      b.classList.remove('active');
      b.setAttribute('aria-selected', 'false');
    });
    document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));

    button.classList.add('active');
    button.setAttribute('aria-selected', 'true');
    const activeTab = document.getElementById(button.dataset.tab);
    activeTab.classList.add('active');
  });
});

// Initialize on DOM Content Loaded
document.addEventListener('DOMContentLoaded', loadConfig);

// Validation Functions

// Validate individual input (name or value)
function validateInput(inputElement, type, index, field) {
  const header = field === 'pattern' ? currentConfig[type][index] : currentConfig[type][index];
  const errorMsg = inputElement.parentElement.querySelector('.error-message');

  if (type === 'urlRules') {
    if (!validateURLPattern(header.pattern)) {
      inputElement.classList.add('invalid');
      errorMsg.textContent = 'Invalid URL pattern.';
      errorMsg.style.display = 'block';
      hasValidationErrors = true;
      return;
    }
  } else if (field === 'name') {
    if (!validateHeaderName(header.name)) {
      inputElement.classList.add('invalid');
      errorMsg.textContent = 'Invalid header name.';
      errorMsg.style.display = 'block';
      hasValidationErrors = true;
      return;
    }
  } else if (field === 'value') {
    if (!validateHeaderValue(header.name, header.value)) {
      inputElement.classList.add('invalid');
      errorMsg.textContent = 'Invalid header value.';
      errorMsg.style.display = 'block';
      hasValidationErrors = true;
      return;
    }
  } else if (field === 'preflightMaxAge') {
    if (!validateMaxAge(header.preflightMaxAge)) {
      inputElement.classList.add('invalid');
      errorMsg.textContent = 'Must be a number between 0 and 86400.';
      errorMsg.style.display = 'block';
      hasValidationErrors = true;
      return;
    }
  }

  // If validation passes
  inputElement.classList.remove('invalid');
  errorMsg.textContent = '';
  errorMsg.style.display = 'none';
}

// Validate all inputs to set the global validation flag
function validateAllInputs() {
  hasValidationErrors = false;

  // Validate Response Headers
  currentConfig.responseHeaders.forEach((header, index) => {
    if (header.enabled) {
      const container = document.getElementById('responseHeaders');
      const headerElement = container.children[index];
      const nameInput = headerElement.querySelector('input[type="text"]');
      const valueInput = headerElement.querySelectorAll('input[type="text"]')[1];
      const errorMsg = headerElement.querySelector('.error-message');

      // Validate name
      if (!validateHeaderName(header.name)) {
        nameInput.classList.add('invalid');
        errorMsg.textContent = 'Invalid header name.';
        errorMsg.style.display = 'block';
        hasValidationErrors = true;
      } else {
        nameInput.classList.remove('invalid');
        errorMsg.textContent = '';
        errorMsg.style.display = 'none';
      }

      // Validate value
      if (!validateHeaderValue(header.name, header.value)) {
        valueInput.classList.add('invalid');
        errorMsg.textContent = 'Invalid header value.';
        errorMsg.style.display = 'block';
        hasValidationErrors = true;
      } else {
        valueInput.classList.remove('invalid');
        errorMsg.textContent = '';
        errorMsg.style.display = 'none';
      }
    }
  });

  // Validate Request Headers
  currentConfig.requestHeaders.forEach((header, index) => {
    if (header.enabled) {
      const container = document.getElementById('requestHeaders');
      const headerElement = container.children[index];
      const nameInput = headerElement.querySelector('input[type="text"]');
      const valueInput = headerElement.querySelectorAll('input[type="text"]')[1];
      const errorMsg = headerElement.querySelector('.error-message');

      // Validate name
      if (!validateHeaderName(header.name)) {
        nameInput.classList.add('invalid');
        errorMsg.textContent = 'Invalid header name.';
        errorMsg.style.display = 'block';
        hasValidationErrors = true;
      } else {
        nameInput.classList.remove('invalid');
        errorMsg.textContent = '';
        errorMsg.style.display = 'none';
      }

      // Validate value
      if (!validateHeaderValue(header.name, header.value)) {
        valueInput.classList.add('invalid');
        errorMsg.textContent = 'Invalid header value.';
        errorMsg.style.display = 'block';
        hasValidationErrors = true;
      } else {
        valueInput.classList.remove('invalid');
        errorMsg.textContent = '';
        errorMsg.style.display = 'none';
      }
    }
  });

  // Validate URL Rules
  currentConfig.urlRules.forEach((rule, index) => {
    if (rule.enabled) {
      const container = document.getElementById('urlRules');
      const ruleElement = container.children[index];
      const patternInput = ruleElement.querySelector('input[type="text"]');
      const errorMsg = ruleElement.querySelector('.error-message');

      if (!validateURLPattern(rule.pattern)) {
        patternInput.classList.add('invalid');
        errorMsg.textContent = 'Invalid URL pattern.';
        errorMsg.style.display = 'block';
        hasValidationErrors = true;
      } else {
        patternInput.classList.remove('invalid');
        errorMsg.textContent = '';
        errorMsg.style.display = 'none';
      }
    }
  });

  // Validate Advanced Settings
  const preflightMaxAgeInput = document.getElementById('preflightMaxAge');
  const preflightMaxAge = preflightMaxAgeInput.value;
  const preflightErrorMsg = preflightMaxAgeInput.parentElement.querySelector('.error-message');

  if (!validateMaxAge(preflightMaxAge)) {
    preflightMaxAgeInput.classList.add('invalid');
    preflightErrorMsg.textContent = 'Must be a number between 0 and 86400.';
    preflightErrorMsg.style.display = 'block';
    hasValidationErrors = true;
  } else {
    preflightMaxAgeInput.classList.remove('invalid');
    preflightErrorMsg.textContent = '';
    preflightErrorMsg.style.display = 'none';
  }
}

// Header Name Validation
function validateHeaderName(name) {
  const regex = /^[a-zA-Z0-9\-]+$/;
  return regex.test(name.trim());
}

// Header Value Validation
function validateHeaderValue(headerName, value) {
  headerName = headerName.toLowerCase();
  value = value.trim();

  const standardHeaders = {
    'access-control-allow-origin': validateAllowOrigin,
    'access-control-allow-methods': validateAllowMethods,
    'access-control-allow-headers': validateAllowHeaders,
    'access-control-allow-credentials': validateAllowCredentials,
    'access-control-expose-headers': validateExposeHeaders,
    'access-control-max-age': validateMaxAge,
    'cross-origin-resource-policy': validateResourcePolicy,
    'cross-origin-embedder-policy': validateEmbedderPolicy
  };

  if (standardHeaders[headerName]) {
    return standardHeaders[headerName](value);
  }

  // Allow custom headers with basic validation
  return /^[\w\-]+$/.test(value);
}

// Specific Header Validations

function validateAllowOrigin(value) {
  if (value === '*') return true;
  try {
    new URL(value);
    return true;
  } catch {
    return false;
  }
}

function validateAllowMethods(value) {
  const validMethods = ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'PATCH', 'HEAD'];
  const methods = value.split(',').map(m => m.trim().toUpperCase());
  return methods.every(m => validMethods.includes(m) || m === '*');
}

function validateAllowHeaders(value) {
  if (value === '*') return true;
  const headers = value.split(',').map(h => h.trim());
  return headers.every(h => /^[a-zA-Z0-9\-]+$/.test(h));
}

function validateAllowCredentials(value) {
  return value.toLowerCase() === 'true' || value.toLowerCase() === 'false';
}

function validateExposeHeaders(value) {
  if (value === '*') return true;
  const headers = value.split(',').map(h => h.trim());
  return headers.every(h => /^[a-zA-Z0-9\-]+$/.test(h));
}

function validateMaxAge(value) {
  const num = parseInt(value, 10);
  return !isNaN(num) && num >= 0 && num <= 86400;
}

function validateResourcePolicy(value) {
  const validPolicies = ['cross-origin', 'same-origin', 'same-site'];
  return validPolicies.includes(value.toLowerCase());
}

function validateEmbedderPolicy(value) {
  const validPolicies = ['require-corp', 'credentialless'];
  return validPolicies.includes(value.toLowerCase());
}

// URL Pattern Validation (Improved)
function validateURLPattern(pattern) {
  // Attempt to create a URL by replacing wildcards
  // This helps ensure Chrome can interpret the pattern
  try {
    const testPattern = pattern.replace(/\*/g, 'http');
    new URL(testPattern);
    return true;
  } catch {
    return false;
  }
}

// Show Save Success Feedback
function showSaveSuccess() {
  const saveButton = document.getElementById('saveButton');
  const originalText = saveButton.textContent;
  saveButton.textContent = '✓ Saved';
  saveButton.style.backgroundColor = '#4CAF50';
  saveButton.disabled = true;

  setTimeout(() => {
    saveButton.textContent = originalText;
    saveButton.style.backgroundColor = '';
    saveButton.disabled = false;
  }, 2000);
}

// Show Save Error Feedback
function showSaveError() {
  const saveButton = document.getElementById('saveButton');
  const originalText = saveButton.textContent;
  saveButton.textContent = '× Error';
  saveButton.style.backgroundColor = '#ff4444';
  saveButton.disabled = true;

  setTimeout(() => {
    saveButton.textContent = originalText;
    saveButton.style.backgroundColor = '';
    saveButton.disabled = false;
  }, 2000);
}

// Utility functions for handling UI state can be added here if needed

// utils.js
function showSaveSuccess() {
  const saveButton = document.getElementById('saveButton');
  const originalText = saveButton.textContent;
  saveButton.textContent = '✓ Saved';
  saveButton.style.backgroundColor = '#4CAF50';
  
  setTimeout(() => {
    saveButton.textContent = originalText;
    saveButton.style.backgroundColor = '';
  }, 2000);
}

function showSaveError() {
  const saveButton = document.getElementById('saveButton');
  const originalText = saveButton.textContent;
  saveButton.textContent = '× Error';
  saveButton.style.backgroundColor = '#ff4444';
  
  setTimeout(() => {
    saveButton.textContent = originalText;
    saveButton.style.backgroundColor = '';
  }, 2000);
}

// Add these helper functions to handle complex header scenarios
function validateHeaderValue(headerName, value) {
  // Special handling for certain headers
  const specialHeaders = {
    'Access-Control-Allow-Origin': ['*', 'null', ...customOriginValidation],
    'Access-Control-Allow-Methods': ['*', 'GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'PATCH', 'HEAD'],
    'Access-Control-Allow-Headers': ['*'],
    'Access-Control-Allow-Credentials': ['true', 'false'],
    'Access-Control-Max-Age': (value) => !isNaN(value) && parseInt(value) >= 0
  };

  if (specialHeaders[headerName]) {
    if (Array.isArray(specialHeaders[headerName])) {
      return specialHeaders[headerName].includes(value) || isValidCustomValue(headerName, value);
    } else {
      return specialHeaders[headerName](value);
    }
  }
  
  return true; // Allow custom headers by default
}

function customOriginValidation(value) {
  try {
    if (value === '*' || value === 'null') return true;
    new URL(value);
    return true;
  } catch {
    return false;
  }
}

function isValidCustomValue(headerName, value) {
  // Additional validation for custom values
  if (headerName === 'Access-Control-Allow-Methods') {
    const validMethods = ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'PATCH', 'HEAD'];
    const methods = value.split(',').map(m => m.trim().toUpperCase());
    return methods.every(m => validMethods.includes(m));
  }
  
  if (headerName === 'Access-Control-Allow-Headers') {
    return value.split(',').every(h => /^[a-zA-Z0-9-]+$/.test(h.trim()));
  }
  
  return true;
}