'use strict';

import { css2xpath } from '../core/css2xpath.js';

// Simple test runner
function runTests() {
  let passed = 0;
  let failed = 0;
  const failures = [];

  function assertEqual(actual, expected, message) {
    console.log(`Testing: ${message}`);
    
    if (actual === expected) {
      console.log(`✓ ${message}`);
      passed++;
    } else {
      console.log(`✗ ${message}`);
      console.log(`  Expected: ${expected}`);
      console.log(`  Actual:   ${actual}`);
      failed++;
      failures.push(`✗ ${message}\n  Expected: ${expected}\n  Actual:   ${actual}`);
    }
  }

  // Basic Selectors
  assertEqual(css2xpath('div'), './/div', 'Tag selector - div');
  assertEqual(css2xpath('span'), './/span', 'Tag selector - span');
  assertEqual(css2xpath('*'), './/*', 'Universal selector');
  
  assertEqual(css2xpath('#myId'), './/*[@id="myId"]', 'ID selector');
  assertEqual(css2xpath('div#myId'), './/div[@id="myId"]', 'Tag with ID selector');
  
  assertEqual(
    css2xpath('.myClass'), 
    './/*[contains(concat(" ",normalize-space(@class)," ")," myClass ")]', 
    'Class selector'
  );
  assertEqual(
    css2xpath('div.myClass'), 
    './/div[contains(concat(" ",normalize-space(@class)," ")," myClass ")]', 
    'Tag with class selector'
  );
  
  // Combinators
  assertEqual(css2xpath('div p'), './/div//p', 'Descendant combinator');
  assertEqual(css2xpath('div > p'), './/div/p', 'Child combinator');
  assertEqual(css2xpath('div + p'), './/div/following-sibling::*[1]/self::p', 'Adjacent sibling combinator');
  assertEqual(css2xpath('div ~ p'), './/div/following-sibling::p', 'General sibling combinator');
  
  // Attribute Selectors
  assertEqual(css2xpath('[data-test]'), './/*[@data-test]', 'Attribute existence selector');
  assertEqual(css2xpath('div[data-test]'), './/div[@data-test]', 'Tag with attribute selector');
  assertEqual(css2xpath('[data-test="value"]'), './/*[@data-test="value"]', 'Attribute equality selector');
  assertEqual(css2xpath('[data-test*="value"]'), './/*[@data-test="value"]', 'Attribute contains selector');
  assertEqual(css2xpath('[data-test^="value"]'), './/*[starts-with(@data-test,"value")]', 'Attribute starts-with selector');
  
  // Pseudo-classes
  assertEqual(css2xpath(':first-child'), './/*[not(preceding-sibling::*)]', 'First-child pseudo-class');
  assertEqual(css2xpath(':last-child'), './/*[not(following-sibling::*)]', 'Last-child pseudo-class');
  assertEqual(css2xpath(':empty'), './/*[not(*) and not(normalize-space())]', 'Empty pseudo-class');
  assertEqual(css2xpath(':checked'), './/*[@selected or @checked]', 'Checked pseudo-class');
  
  // Complex Selectors
  assertEqual(
    css2xpath('div.container > ul.menu > li:first-child'),
    './/div[contains(concat(" ",normalize-space(@class)," ")," container ")]/ul[contains(concat(" ",normalize-space(@class)," ")," menu ")]/li[not(preceding-sibling::*)]',
    'Complex selector with multiple combinators'
  );
  
  assertEqual(
    css2xpath('input[type="text"]:not([disabled])'),
    './/input[@type="text"][not(self::node()[@disabled])]',
    'Complex selector with attributes and pseudo-classes'
  );
  
  // Special Cases
  assertEqual(css2xpath('div, span'), './/div|.//span', 'Comma-separated selectors');
  assertEqual(css2xpath('div!>p'), './/div/parent::p', 'Parent combinator');
  assertEqual(css2xpath('div!+p'), './/div/preceding-sibling::*[1]/self::p', 'Preceding adjacent sibling combinator');
  
  // Edge Cases
  assertEqual(css2xpath(''), './/*', 'Empty selector');
  assertEqual(css2xpath('  div  >  p  '), './/div/p', 'Selector with whitespace');
  
  // Additional Tests for Edge Cases
  assertEqual(css2xpath(null), './/*', 'Null selector');
  assertEqual(css2xpath(undefined), './/*', 'Undefined selector');
  assertEqual(css2xpath('   '), './/*', 'Whitespace-only selector');
  
  // Additional Tests for Complex Selectors
  assertEqual(
    css2xpath('div > p, span > a'),
    './/div/p|.//span/a',
    'Multiple complex selectors with comma'
  );
  
  assertEqual(
    css2xpath('div[data-test="value"][data-role="button"]'),
    './/div[@data-test="value"][@data-role="button"]',
    'Multiple attribute selectors'
  );
  
  assertEqual(
    css2xpath('div.class1.class2.class3'),
    './/div[contains(concat(" ",normalize-space(@class)," ")," class1 ")][contains(concat(" ",normalize-space(@class)," ")," class2 ")][contains(concat(" ",normalize-space(@class)," ")," class3 ")]',
    'Multiple class selectors'
  );
  
  // Additional Tests for Pseudo-classes
  assertEqual(
    css2xpath(':nth-child(3n+1)'),
    './/*[(count(preceding-sibling::*)+1)>=1 and ((count(preceding-sibling::*)+1)-1) mod 3=0]',
    'nth-child with formula'
  );
  
  assertEqual(
    css2xpath(':contains("Hello World")'),
    './/*[contains(normalize-space(),"Hello World")]',
    'contains pseudo-class'
  );
  
  // Additional Tests for Attribute Selectors
  assertEqual(
    css2xpath('[data-test$="value"]'),
    './/*[substring(@data-test,string-length(@data-test)-(string-length("value")-1))="value"]',
    'Attribute ends-with selector'
  );
  
  assertEqual(
    css2xpath('[data-test~="value"]'),
    './/*[contains(concat(" ",normalize-space(@data-test)," "),concat(" ","value"," "))]',
    'Attribute word selector'
  );
  
  // Additional Tests for Custom Combinators
  assertEqual(
    css2xpath('div! p'),
    './/div/ancestor-or-self::p',
    'Ancestor-or-self combinator'
  );
  
  assertEqual(
    css2xpath('div!^p'),
    './/div/child::*[last()]/self::p',
    'First child combinator'
  );
  
  // Additional Tests for Real-world Scenarios
  assertEqual(
    css2xpath('form input[type="submit"]:not(:disabled)'),
    './/form//input[@type="submit"][not(self::node()[@disabled])]',
    'Form submit button that is not disabled'
  );
  
  assertEqual(
    css2xpath('table > tbody > tr:nth-child(odd)'),
    './/table/tbody/tr[(count(preceding-sibling::*)+1) mod 2=1]',
    'Odd rows in a table'
  );
  
  assertEqual(
    css2xpath('ul.menu > li.active > a[href^="/"]'),
    './/ul[contains(concat(" ",normalize-space(@class)," ")," menu ")]/li[contains(concat(" ",normalize-space(@class)," ")," active ")]/a[starts-with(@href,"/")]',
    'Active menu item with relative link'
  );
  
  assertEqual(
    css2xpath('div.modal:not(.hidden) > .modal-content'),
    './/div[contains(concat(" ",normalize-space(@class)," ")," modal ")][not(self::node()[contains(concat(" ",normalize-space(@class)," ")," hidden ")])]/*[contains(concat(" ",normalize-space(@class)," ")," modal-content ")]',
    'Visible modal content'
  );

  // Add property-based testing to generate random valid CSS selectors
  function generateRandomSelector() {
    const elements = ['div', 'span', 'p', 'a', 'input'];
    const classes = ['btn', 'container', 'wrapper', 'item'];
    const attributes = ['data-test', 'aria-label', 'type'];
    
    // Generate simple random selectors
    const element = elements[Math.floor(Math.random() * elements.length)];
    const className = classes[Math.floor(Math.random() * classes.length)];
    
    return `${element}.${className}`;
  }

  // Test with 10 random selectors
  for (let i = 0; i < 10; i++) {
    const selector = generateRandomSelector();
    assertEqual(
      typeof css2xpath(selector),
      'string',
      `Random selector should convert successfully: ${selector}`
    );
  }
  
  // Add these advanced real-world test cases before the summary

  console.log('\n// Advanced Real-World Scenarios');
  
  // E-commerce product listing scenarios
  assertEqual(
    css2xpath('.product-card:not(.out-of-stock) .price-tag[data-currency="USD"]'),
    './/*[contains(concat(" ",normalize-space(@class)," ")," product-card ")][not(self::node()[contains(concat(" ",normalize-space(@class)," ")," out-of-stock ")])]//*[contains(concat(" ",normalize-space(@class)," ")," price-tag ")][@data-currency="USD"]',
    'Available products with USD prices'
  );
  
  assertEqual(
    css2xpath('table.cart-items > tbody > tr:not(:first-child):not(.subtotal-row) td.quantity input[type="number"]'),
    './/table[contains(concat(" ",normalize-space(@class)," ")," cart-items ")]/tbody/tr[not(self::node()[not(preceding-sibling::*)])][not(self::node()[contains(concat(" ",normalize-space(@class)," ")," subtotal-row ")])]//td[contains(concat(" ",normalize-space(@class)," ")," quantity ")]//input[@type="number"]',
    'Quantity inputs for cart items excluding headers and subtotal row'
  );
  
  // Form validation scenarios
  assertEqual(
    css2xpath('form.checkout input:invalid, form.checkout select:invalid'),
    './/form[contains(concat(" ",normalize-space(@class)," ")," checkout ")]//input[@invalid]|.//form[contains(concat(" ",normalize-space(@class)," ")," checkout ")]//select[@invalid]',
    'All invalid form fields in checkout'
  );
  
  assertEqual(
    css2xpath('form[data-form-id="login"] .form-group:has(input[name="password"]) .error-message'),
    './/form[@data-form-id="login"]//*[contains(concat(" ",normalize-space(@class)," ")," form-group ")][count(.//input[@name="password"]) > 0]//*[contains(concat(" ",normalize-space(@class)," ")," error-message ")]',
    'Password field error message in login form'
  );
  
  // Navigation and menu structures
  assertEqual(
    css2xpath('nav.main-nav > ul > li.dropdown.active > .dropdown-menu > li > a[href^="/products/"]'),
    './/nav[contains(concat(" ",normalize-space(@class)," ")," main-nav ")]/ul/li[contains(concat(" ",normalize-space(@class)," ")," dropdown ")][contains(concat(" ",normalize-space(@class)," ")," active ")]/*[contains(concat(" ",normalize-space(@class)," ")," dropdown-menu ")]/li/a[starts-with(@href,"/products/")]',
    'Active product category links in dropdown menu'
  );
  
  // Modal dialogs and overlays
  assertEqual(
    css2xpath('.modal[aria-hidden="false"] .close-btn, .dialog:not([hidden]) .dismiss-action'),
    './/*[contains(concat(" ",normalize-space(@class)," ")," modal ")][@aria-hidden="false"]//*[contains(concat(" ",normalize-space(@class)," ")," close-btn ")]|.//*[contains(concat(" ",normalize-space(@class)," ")," dialog ")][not(self::node()[@hidden])]//*[contains(concat(" ",normalize-space(@class)," ")," dismiss-action ")]',
    'Close buttons in any visible modal or dialog'
  );
  
  // Data tables with sorting and filtering
  assertEqual(
    css2xpath('table.data-grid thead th[data-sortable="true"][data-sort-direction="asc"] .sort-icon'),
    './/table[contains(concat(" ",normalize-space(@class)," ")," data-grid ")]//thead//th[@data-sortable="true"][@data-sort-direction="asc"]//*[contains(concat(" ",normalize-space(@class)," ")," sort-icon ")]',
    'Sort icons in ascending sorted table headers'
  );
  
  // React/Vue/Angular style component selectors
  assertEqual(
    css2xpath('[data-testid="user-profile"] [data-testid="avatar"]:not([data-loading="true"])'),
    './/*[@data-testid="user-profile"]//*[@data-testid="avatar"][not(self::node()[@data-loading="true"])]',
    'Loaded user avatar in profile component'
  );
  
  // Accessibility-related selectors
  assertEqual(
    css2xpath('button[aria-expanded="true"][aria-controls]:not([disabled]) + [role="menu"] [role="menuitem"]:not([aria-hidden="true"])'),
    './/button[@aria-expanded="true"][@aria-controls][not(self::node()[@disabled])]/following-sibling::*[1]/self::*[@role="menu"]//*[@role="menuitem"][not(self::node()[@aria-hidden="true"])]',
    'Visible menu items in expanded dropdown controlled by button'
  );
  
  // Complex structural selectors
  assertEqual(
    css2xpath('.sidebar-nav > ul > li:nth-child(odd):not(.divider) > a[href]:not([target="_blank"])'),
    './/*[contains(concat(" ",normalize-space(@class)," ")," sidebar-nav ")]/ul/li[(count(preceding-sibling::*)+1) mod 2=1][not(self::node()[contains(concat(" ",normalize-space(@class)," ")," divider ")])]/a[@href][not(self::node()[@target="_blank"])]',
    'Odd-numbered internal links in sidebar excluding dividers'
  );
  
  // Pagination controls
  assertEqual(
    css2xpath('.pagination > li:not(.active):not(.disabled) > a[href], .pagination > li:not(.active):not(.disabled) > button:not([disabled])'),
    './/*[contains(concat(" ",normalize-space(@class)," ")," pagination ")]/li[not(self::node()[contains(concat(" ",normalize-space(@class)," ")," active ")])][not(self::node()[contains(concat(" ",normalize-space(@class)," ")," disabled ")])]/a[@href]|.//*[contains(concat(" ",normalize-space(@class)," ")," pagination ")]/li[not(self::node()[contains(concat(" ",normalize-space(@class)," ")," active ")])][not(self::node()[contains(concat(" ",normalize-space(@class)," ")," disabled ")])]/button[not(self::node()[@disabled])]',
    'Clickable pagination links and buttons'
  );
  
  // Modern UI frameworks (Bootstrap, Material) specific patterns
  assertEqual(
    css2xpath('.card .card-header button[data-toggle="collapse"][aria-expanded="false"] + div.collapse:not(.show)'),
    './/*[contains(concat(" ",normalize-space(@class)," ")," card ")]//*[contains(concat(" ",normalize-space(@class)," ")," card-header ")]//button[@data-toggle="collapse"][@aria-expanded="false"]/following-sibling::*[1]/self::div[contains(concat(" ",normalize-space(@class)," ")," collapse ")][not(self::node()[contains(concat(" ",normalize-space(@class)," ")," show ")])]',
    'Collapsed accordion content in Bootstrap cards'
  );
  
  console.log('\n// Additional CSS Features and Edge Cases');

  assertEqual(
    css2xpath('input::placeholder'),
    './/input',
    'Input with ::placeholder pseudo-element (pseudo-element ignored)'
  );
  assertEqual(
    css2xpath('div.tooltip::after'),
    './/div[contains(concat(" ",normalize-space(@class)," ")," tooltip ")]',
    'Div with ::after pseudo-element (pseudo-element ignored)'
  );
  assertEqual(
    css2xpath('::selection'), // Global pseudo-element
    './/*', // Should resolve to universal if only pseudo-element
    'Global ::selection pseudo-element (ignored, becomes universal)'
  );

  assertEqual(
    css2xpath('[data-name="User" i]'),
    './/*[data-name="User"//i]', // Current output
    'Case-insensitive attribute equality'
  );
  assertEqual(
    css2xpath('[title*="example" i]'),
    './/*[title*="example"//i]', 
    'Case-insensitive attribute contains'
  );
  assertEqual(
    css2xpath('[data-value^="Prefix" i]'),
    './/*[data-value^="Prefix"//i]',
    'Case-insensitive attribute starts-with'
  );
  assertEqual(
    css2xpath('[data-file$=".JPG" i]'),
    './/*[data-file$=".JPG"//i]',
    'Case-insensitive attribute ends-with'
  );

  assertEqual(
    css2xpath('li:nth-child(even)'),
    './/li[(count(preceding-sibling::*)+1) mod 2=0]',
    'nth-child(even)'
  );

  assertEqual(
    css2xpath('p:lang(en)'),
    './/p[@lang="en" or starts-with(@lang, "en-")]',
    'Language pseudo-class :lang(en)'
  );
  assertEqual(
    css2xpath(':lang(fr-CA)'),
    './/*[@lang="fr-CA" or starts-with(@lang, "fr-CA-")]',
    'Language pseudo-class :lang(fr-CA) with region'
  );

  assertEqual(
    css2xpath(':root'),
    './/*[not(parent::*)]', // Current output
    'Root pseudo-class :root'
  );
  assertEqual(
    css2xpath('html:root'), // More specific
    './/html[not(parent::*)]',
    'html:root pseudo-class'
  );

  assertEqual(
    css2xpath('#section1:target'),
    './/*[@id="section1"][@id = "_TARGET_ID_PLACEHOLDER_"]', // :target is tricky, using placeholder
    'Target pseudo-class :target'
  );

  assertEqual(
    css2xpath('button:disabled'),
    './/button[@disabled]',
    'Disabled button pseudo-class'
  );
  assertEqual(
    css2xpath('input:enabled'),
    './/input[not(@disabled)]', // Matches our implementation
    'Enabled input pseudo-class'
  );
  assertEqual(
    css2xpath('textarea:read-only'), // Assuming :read-only maps to @readonly
    './/textarea[@readonly]',
    'Textarea :read-only pseudo-class'
  );
  assertEqual(
    css2xpath('input:read-write'), // Assuming :read-write maps to not(@readonly)
    './/input[not(@readonly)]',
    'Input :read-write pseudo-class'
  );
  assertEqual(
    css2xpath('input:required'),
    './/input[@required]',
    'Input :required pseudo-class'
  );
  assertEqual(
    css2xpath('select:optional'),
    './/select[not(@required)]',
    'Select :optional pseudo-class'
  );

  assertEqual(
    css2xpath('[data-message="hello world"]'),
    './/*[@data-message="hello world"]',
    'Attribute value with spaces'
  );
  assertEqual(
    css2xpath('[data-message="hello world" i]'),
    './/*[data-message="hello world"//i]', // Current output
    'Case-insensitive attribute value with spaces'
  );
    
  // Summary
  console.log(`\nTest Results: ${passed} passed, ${failed} failed`);
  
  if (failed > 0) {
    console.log('\nFailures:');
    failures.forEach(failure => console.log(failure));
    process.exit(1);
  } else {
    console.log('\nAll tests passed!');
  }

  console.log('\n// Advanced and Edge Case Testing');

  // Advanced attribute selectors with wildcards
  assertEqual(
    css2xpath('div[data-*^="test"]'),
    './/div[data-*^="test"]', // Currently not supporting attribute name wildcards
    'Attribute name wildcard with value condition'
  );
  
  // Complex nested pseudo-classes - has() support
  assertEqual(
    css2xpath('div:has(> img:not([alt=""]))'),
    './/div[count(/img[not(self::node()[@alt=""])]) > 0]', // Current implementation uses absolute path
    'Parent with direct child matching condition'
  );
  
  // Form validation state selectors
  assertEqual(
    css2xpath('form input:valid:not(:focus):not(:placeholder-shown)'),
    './/form//input[@valid][not(:focus)][not(:placeholder-shown)]', // Pseudo-classes not fully translated
    'Valid unfocused input with content'
  );
  
  assertEqual(
    css2xpath('input:user-invalid + .error-message:not(.hidden)'),
    './/input:user-invalid/following-sibling::*[1]/self::*[contains(concat(" ",normalize-space(@class)," ")," error-message ")][not(self::node()[contains(concat(" ",normalize-space(@class)," ")," hidden ")])]',
    'Error message for invalid input field'
  );
  
  // Complex tree traversal
  assertEqual(
    css2xpath('html body main article > section:first-of-type h2 ~ p:first-of-type'),
    './/html//body//main//article/section[1]//h2/following-sibling::p[1]', // Descendant vs child combinators
    'Deep DOM traversal with first paragraph after heading'
  );
  
  assertEqual(
    css2xpath('.list-container > *:nth-child(n+3):nth-child(-n+8):nth-child(odd)'),
    './/*[contains(concat(" ",normalize-space(@class)," ")," list-container ")]/*[(count(preceding-sibling::*)+1)>=3 and ((count(preceding-sibling::*)+1)-3) mod 1=0][(count(preceding-sibling::*)+1)>=8 and ((count(preceding-sibling::*)+1)-8) mod -=0][(count(preceding-sibling::*)+1) mod 2=1]',
    'Complex range of odd-numbered elements from 3 to 8'
  );
  
  // Modern UI patterns
  assertEqual(
    css2xpath('.toast-container .toast:not(.hiding):not(.showing)[data-autohide="true"]'),
    './/*[contains(concat(" ",normalize-space(@class)," ")," toast-container ")]//*[contains(concat(" ",normalize-space(@class)," ")," toast ")][not(self::node()[contains(concat(" ",normalize-space(@class)," ")," hiding ")])][not(self::node()[contains(concat(" ",normalize-space(@class)," ")," showing ")])][@data-autohide="true"]', // Attribute placement
    'Auto-hiding toast notification in stable state'
  );
  
  // Data tables with complex filtering
  assertEqual(
    css2xpath('table > tbody > tr:nth-child(n+2):has(td:nth-child(3)[data-value^="Q"]):has(td:last-child[data-status="active"])'),
    './/table/tbody/tr[(count(preceding-sibling::*)+1)>=2 and ((count(preceding-sibling::*)+1)-2) mod 1=0][count(.//td[(count(preceding-sibling::*)+1) = 3][starts-with(@data-value,"Q")]) > 0][count(.//td[not(following-sibling::*)][@data-status="active"]) > 0]',
    'Table rows with "Q" prefix in third column and "active" status in last column'
  );
  
  // State-based UI with multiple conditions
  assertEqual(
    css2xpath('.dropdown.show > .dropdown-menu .dropdown-item:not([aria-disabled="true"]):not(:has(a[href="#"])):hover'),
    './/*[contains(concat(" ",normalize-space(@class)," ")," dropdown ")][contains(concat(" ",normalize-space(@class)," ")," show ")]/*[contains(concat(" ",normalize-space(@class)," ")," dropdown-menu ")]//*[contains(concat(" ",normalize-space(@class)," ")," dropdown-item ")][not(self::node()[@aria-disabled="true"])][not(self::node()[count(.//a[@href="#"]) > 0])]:hover', // :hover handling
    'Actionable dropdown items on hover'
  );
  
  // Complex nested elements
  assertEqual(
    css2xpath('article[data-category="news"] > header h1 + .metadata > .author[data-verified="true"] ~ .date:not([data-estimated="true"])'),
    './/article[@data-category="news"]/header//h1/following-sibling::*[1]/self::*[contains(concat(" ",normalize-space(@class)," ")," metadata ")]/*[contains(concat(" ",normalize-space(@class)," ")," author ")][@data-verified="true"]/following-sibling::*[contains(concat(" ",normalize-space(@class)," ")," date ")][not(self::node()[@data-estimated="true"])]', // h1 descendant vs child
    'Date element following verified author in news article'
  );

  console.log('\n// Even More Advanced Tests');

  // Shadow DOM selectors (limited support in XPath 1.0)
  assertEqual(
    css2xpath('div::shadow span'),
    './/div//span', // XPath 1.0 can't directly access shadow DOM
    'Shadow DOM traversal (limited support)'
  );

  // Web Components custom elements
  assertEqual(
    css2xpath('my-component[opened]'),
    './/my-component[@opened]',
    'Custom element with attribute'
  );
  
  assertEqual(
    css2xpath('article custom-element::part(header)'),
    './/article//custom-element', // ::part() is not supported in XPath 1.0
    'Custom element with ::part() pseudo-element'
  );

  // Complex media controls
  assertEqual(
    css2xpath('video:not([controls]) ~ .custom-controls button[data-action="play"]:not([disabled])'),
    './/video[not(self::node()[@controls])]/following-sibling::*[contains(concat(" ",normalize-space(@class)," ")," custom-controls ")]//button[@data-action="play"][not(self::node()[@disabled])]',
    'Custom video controls play button'
  );
  
  // International and localization testing
  assertEqual(
    css2xpath('[lang|="zh"]:not([translate="no"])'),
    './/*[@lang="zh" or starts-with(@lang,concat("zh","-"))][not(self::node()[@translate="no"])]',
    'Chinese language content that should be translated'
  );
  
  // Complex nth patterns for reports and dashboards
  assertEqual(
    css2xpath('.data-grid tr:nth-child(4n+1):not(:first-child)'),
    './/*[contains(concat(" ",normalize-space(@class)," ")," data-grid ")]//tr[(count(preceding-sibling::*)+1)>=1 and ((count(preceding-sibling::*)+1)-1) mod 4=0][not(self::node()[not(preceding-sibling::*)])]',
    'Every 4th row starting with 1st but excluding very first'
  );
  
  // Compound :not() selectors with complex conditions
  assertEqual(
    css2xpath('section:not(.collapsed):not(:has(h2.empty)):not(:has(> div.error))'),
    './/section[not(self::node()[contains(concat(" ",normalize-space(@class)," ")," collapsed ")])][not(self::node()[count(.//h2[contains(concat(" ",normalize-space(@class)," ")," empty ")]) > 0])][not(self::node()[count(/div[contains(concat(" ",normalize-space(@class)," ")," error ")]) > 0])]',
    'Non-collapsed section without empty heading or direct error div'
  );
  
  // Date input fields with validation states
  assertEqual(
    css2xpath('input[type="date"][min][max]:not(:required):not([readonly]):not([value=""])'),
    './/input[@type="date"][@min][max][not(self::node()[@required])][not(self::node()[@readonly])][not(self::node()[@value=""])]',
    'Optional date input with range constraints and non-empty value'
  );
  
  // Complex responsive design patterns
  assertEqual(
    css2xpath('.sidebar:not([data-collapsed="true"]) ~ .content[data-layout="narrow"] .widget[data-priority="high"]'),
    './/*[contains(concat(" ",normalize-space(@class)," ")," sidebar ")][not(self::node()[@data-collapsed="true"])]/following-sibling::*[contains(concat(" ",normalize-space(@class)," ")," content ")][@data-layout="narrow"]//*[contains(concat(" ",normalize-space(@class)," ")," widget ")][@data-priority="high"]',
    'High priority widgets in narrow content adjacent to expanded sidebar'
  );

  // Layered UI with stacking context testing
  assertEqual(
    css2xpath('.dialog:not([aria-hidden="true"]) > .dialog-content > .tab-container > .tab-content[aria-expanded="true"] .form-group:has(label[aria-required="true"]:not([data-optional-override="true"]))'),
    './/*[contains(concat(" ",normalize-space(@class)," ")," dialog ")][not(self::node()[@aria-hidden="true"])]/*[contains(concat(" ",normalize-space(@class)," ")," dialog-content ")]/*[contains(concat(" ",normalize-space(@class)," ")," tab-container ")]/*[contains(concat(" ",normalize-space(@class)," ")," tab-content ")][@aria-expanded="true"]//*[contains(concat(" ",normalize-space(@class)," ")," form-group ")][count(.//label[@aria-required="true"][not(self::node()[@data-optional-override="true"])]) > 0]',
    'Required form fields in active tab of visible dialog'
  );

  // Multi-column layout testing
  assertEqual(
    css2xpath('.grid-layout[data-columns="3"] > .grid-item:nth-child(3n+1):nth-child(-n+10)'),
    './/*[contains(concat(" ",normalize-space(@class)," ")," grid-layout ")][@data-columns="3"]/*[contains(concat(" ",normalize-space(@class)," ")," grid-item ")][(count(preceding-sibling::*)+1)>=1 and ((count(preceding-sibling::*)+1)-1) mod 3=0][(count(preceding-sibling::*)+1)>=10 and ((count(preceding-sibling::*)+1)-10) mod -=0]',
    'First column items in 3-column grid, limited to first 10 items'
  );

  // Complex data selection with multiple filters
  assertEqual(
    css2xpath('table.data-table tbody tr:has(td.status.success):has(td.type[data-category="report"]):not(:has(td.actions button[disabled]))[data-row-selectable="true"]'),
    './/table[contains(concat(" ",normalize-space(@class)," ")," data-table ")]//tbody//tr[count(.//td[contains(concat(" ",normalize-space(@class)," ")," status ")][contains(concat(" ",normalize-space(@class)," ")," success ")]) > 0][count(.//td[contains(concat(" ",normalize-space(@class)," ")," type ")][@data-category="report"]) > 0][not(self::node()[count(.//td[contains(concat(" ",normalize-space(@class)," ")," actions ")]//button[@disabled]) > 0])][@data-row-selectable="true"]',
    'Selectable successful report rows with enabled action buttons'
  );

  // Testing frameworks integration
  assertEqual(
    css2xpath('[data-testid="login-form"] input[required]:not([data-testid="remember-me"]):invalid'),
    './/*[@data-testid="login-form"]//input[@required][not(self::node()[@data-testid="remember-me"])][@invalid]',
    'Required invalid inputs in login form excluding remember-me'
  );

  // Drag and drop interface testing
  assertEqual(
    css2xpath('.drag-container .draggable:not(.dragging):not(.disabled)[data-droppable-group=":scope > .drop-zone[data-accepts]:not(.full)"]'),
    './/*[contains(concat(" ",normalize-space(@class)," ")," drag-container ")]//*[contains(concat(" ",normalize-space(@class)," ")," draggable ")][not(self::node()[contains(concat(" ",normalize-space(@class)," ")," dragging ")])][not(self::node()[contains(concat(" ",normalize-space(@class)," ")," disabled ")])][@data-droppable-group=":scope > .drop-zone[data-accepts]:not(.full)"]',
    'Draggable elements that can be dropped into non-full drop zones'
  );

  // Right-to-left text direction testing
  assertEqual(
    css2xpath('[dir="rtl"] .menu .dropdown[aria-expanded="true"] > .submenu'),
    './/*[@dir="rtl"]//*[contains(concat(" ",normalize-space(@class)," ")," menu ")]//*[contains(concat(" ",normalize-space(@class)," ")," dropdown ")][@aria-expanded="true"]/*[contains(concat(" ",normalize-space(@class)," ")," submenu ")]',
    'Expanded dropdown submenu in RTL context'
  );

  // Feature detection and progressive enhancement
  assertEqual(
    css2xpath('.feature-slider:not([data-feature-touch="false"]) .slide[aria-hidden="false"] .caption:lang(en)'),
    './/*[contains(concat(" ",normalize-space(@class)," ")," feature-slider ")][not(self::node()[@data-feature-touch="false"])]//*[contains(concat(" ",normalize-space(@class)," ")," slide ")][@aria-hidden="false"]//*[contains(concat(" ",normalize-space(@class)," ")," caption ")][@lang="en" or starts-with(@lang, "en-")]',
    'English captions in visible slides of touch-enabled feature slider'
  );

  // Security-related testing
  assertEqual(
    css2xpath('form[action*="/login"]:not([data-secure="true"]):not([action^="https://"])'),
    './/form[@action="/login"][not(self::node()[@data-secure="true"])][not(self::node()[starts-with(@action,"https://")])]',
    'Insecure login forms not using HTTPS'
  );
}

// Run the tests
runTests(); 