import React from 'react';
import { Meta, Story } from '@storybook/react';
import CharacterStatUI from './CharacterStatUI';

export default {
  title: 'CharacterStatUI',
  component: CharacterStatUI
};

const Template = (args) => <CharacterStatUI {...args} />;

export const Default = Template.bind({});
Default.args = {};

// tests/test_code.test.js
describe('Storybook CharacterStatUI implementation tests', () => {
  // Basic initialization test
  test('Global test variables should be defined', () => {
    expect(global.__TEST_UTILS__).toBeDefined();
    expect(global.__RESULTS_MANAGER__).toBeDefined();
    expect(global.__IMPLEMENTATIONS__).toBeDefined();

    // Log implementation information for debugging
    console.log('Implementation count:', Object.keys(global.__IMPLEMENTATIONS__ || {}).length);

    // Create a basic test result for each implementation
    const implementations = global.__IMPLEMENTATIONS__ || {};
    Object.keys(implementations).forEach(implName => {
      if (implName !== 'original_code') {
        global.__RESULTS_MANAGER__.recordResult(implName, 'test_setup', true);
      }
    });
  });

  // Detailed implementation tests
  describe('Implementation specific tests', () => {
    let implementations;
    let resultsManager;

    beforeAll(() => {
      implementations = global.__IMPLEMENTATIONS__ || {};
      resultsManager = global.__RESULTS_MANAGER__;
    });

    // Test for Storybook structure according to requirements
    test('Each implementation should have the correct Storybook structure', () => {
      Object.entries(implementations).forEach(([implName, impl]) => {

        const testName = 'storybook_structure';

        try {
          // Check if implementation has errors
          if (impl.__errors__ && impl.__errors__.length > 0) {
            console.warn(`Implementation ${implName} has errors:`, impl.__errors__);
            resultsManager.recordSkip(implName, testName, 'Implementation has syntax or loading errors');
            return;
          }

          // Check for Default export with correct properties
          expect(impl.default).toBeDefined();
          expect(impl.default.title).toBe('CharacterStatUI');
          expect(impl.default.component).toBeDefined();

          // Check for Default story
          expect(impl.Default).toBeDefined();

          // If Template is defined, check that it's a function
          // (the Template might be created inline in the Template.bind() call)
          if (impl.Template) {
            expect(typeof impl.Template).toBe('function');
          }

          // Record success
          resultsManager.recordResult(implName, testName, true);
        } catch (e) {
          // Record failure with error message
          resultsManager.recordResult(implName, testName, false, e.message);
          console.error(`Implementation ${implName} failed structure test:`, e.message);
        }
      });
    });

    // Test for required parameters according to instruction.txt
    test('Each implementation should provide required parameters', () => {
      Object.entries(implementations).forEach(([implName, impl]) => {

        const testName = 'required_parameters';

        try {
          // Skip if implementation has errors
          if (impl.__errors__ && impl.__errors__.length > 0) {
            resultsManager.recordSkip(implName, testName, 'Implementation has syntax or loading errors');
            return;
          }

          // Check for parameters in Default.args or default.parameters
          let params = impl.Default.args || {};
          if (Object.keys(params).length === 0 && impl.default.parameters) {
            params = impl.default.parameters;
          }

          // Test required parameters from instruction.txt
          expect(Object.keys(params).length).toBeGreaterThan(0);
          expect(params.name).toBe('Alfonse');
          expect(params.level).toBe(40);

          // Check if "Folkvangr" exists in any parameter value
          const paramValues = Object.values(params);
          const hasFollkvangr = paramValues.includes('Folkvangr');
          expect(hasFollkvangr).toBe(true);

          // Stats parameters
          expect(params.wpn).toBe(50);
          expect(params.atk).toBe(50);
          expect(params.spd).toBe(50);
          expect(params.def).toBe(30);
          expect(params.res).toBe(30);

          // Record success
          resultsManager.recordResult(implName, testName, true);
        } catch (e) {
          // Record failure with error message
          resultsManager.recordResult(implName, testName, false, e.message);
          console.error(`Implementation ${implName} failed parameters test:`, e.message);
        }
      });
    });
  });
});

Instruction: Please make this Storybook test include the parameters: name="Alfonse", level=40, "Folkvangr", wpn=50, atk=50, spd=50, def=30, res=30

{
  "name": "js-test-framework",
  "version": "1.0.0",
  "description": "JavaScript testing framework for multiple implementations",
  "main": "index.js",
  "type": "commonjs",
  "scripts": {
    "test": "jest"
  },
  "dependencies": {
    "react": "^18.2.0",
    "react-dom": "^18.2.0"
  },
  "devDependencies": {
    "@babel/core": "^7.23.5",
    "@babel/preset-env": "^7.23.5",
    "@babel/preset-react": "^7.23.3",
    "@storybook/react": "^7.6.0",
    "@testing-library/jest-dom": "^6.1.5",
    "@testing-library/react": "^14.1.2",
    "babel-jest": "^29.7.0",
    "glob": "^10.4.5",
    "jest": "^29.7.0",
    "jest-environment-jsdom": "^29.7.0",
    "jest-mock": "^29.7.0"
  },
  "jest": {
    "setupFilesAfterEnv": [
      "./jest-setup.js"
    ],
    "testEnvironment": "jsdom",
    "testMatch": [
      "**/tests/**/*.test.js"
    ],
    "verbose": true,
    "collectCoverage": true,
    "coverageDirectory": "./coverage",
    "collectCoverageFrom": [
      "./*.{js,jsx}",
      "!jest-setup.js"
    ],
    "transform": {
      "^.+\\.(js|jsx)$": "babel-jest"
    },
    "transformIgnorePatterns": [
      "/node_modules/(?!(@storybook|storybook-|@babel/runtime)).+\\.js$"
    ],
    "moduleNameMapper": {
      "\\./(CharacterStatUI)$": "<rootDir>/mocks/CharacterStatUIMock.jsx",
      "^@storybook/(.*)$": "<rootDir>/node_modules/@storybook/$1"
    },
    "moduleDirectories": [
      "node_modules",
      "<rootDir>"
    ]
  },
  "babel": {
    "presets": [
      [
        "@babel/preset-env",
        {
          "targets": {
            "node": "current"
          }
        }
      ],
      [
        "@babel/preset-react",
        {
          "runtime": "automatic"
        }
      ]
    ]
  }
}

// jest-setup.js
const fs = require('fs');
const path = require('path');
const glob = require('glob');
const babel = require('@babel/core');

/**
 * Utility class to handle JavaScript implementations
 */
class TestUtils {
  /**
   * Find all implementation files in the current directory
   * @param {string} directory - Directory to search in (defaults to current directory)
   * @returns {Array<string>} List of implementation file paths
   */
  static discoverImplementationFiles(directory = null) {
    if (!directory) {
      directory = __dirname;
    }

    const patterns = [
      'original_modified_code\\d+\\.(js|jsx)',
      'modified_code\\d+\\.(js|jsx)',
      'new_code\\d+\\.(js|jsx)',
      'implementation\\d*\\.(js|jsx)',
    ];

    const regexPattern = new RegExp(patterns.join('|'));
    const implementations = [];

    // Use glob to find matching files
    const files = glob.sync(path.join(directory, '*.{js,jsx}'));

    for (const filePath of files) {
      const basename = path.basename(filePath);
      if (regexPattern.test(basename) && !basename.startsWith('jest-') && basename !== 'test-results.json') {
        implementations.push(filePath);
      }
    }

    // Sort files numerically
    implementations.sort((a, b) => {
      const aMatch = path.basename(a).match(/(\d+)/);
      const bMatch = path.basename(b).match(/(\d+)/);
      const aNum = aMatch ? parseInt(aMatch[1]) : 0;
      const bNum = bMatch ? parseInt(bMatch[1]) : 0;
      return aNum - bNum;
    });

    return implementations;
  }

  /**
   * Transform ES module code to CommonJS for Jest
   * @param {string} sourceCode - The source code to transform
   * @param {string} filePath - The path to the source file (for source maps)
   * @returns {string} Transformed code
   */
  static transformCode(sourceCode, filePath) {
    try {
      const result = babel.transformSync(sourceCode, {
        filename: filePath,
        presets: [
          ['@babel/preset-env', { targets: { node: 'current' }, modules: 'commonjs' }],
          ['@babel/preset-react', { runtime: 'automatic' }]
        ],
        ast: false,
        sourceMaps: false
      });

      return result.code;
    } catch (e) {
      console.error(`Babel transform error for ${filePath}: ${e.message}`);
      // Return original code if transform fails, the require will fail with better errors
      return sourceCode;
    }
  }

  /**
   * Safely load a module from a file path
   * @param {string} filePath - Path to the JavaScript file
   * @param {string} moduleName - Optional module name (defaults to filename)
   * @returns {Object} Loaded module with error information if any
   */
  static loadModule(filePath, moduleName = null) {
    if (!moduleName) {
      moduleName = path.basename(filePath).replace(/\.(js|jsx)$/, '');
    }

    // Create unique module name to avoid conflicts
    const sandboxId = path.basename(path.dirname(filePath));
    const uniqueModuleName = `${sandboxId}_${moduleName}`;

    // Create module object with default properties
    const moduleObj = {
      __file__: filePath,
      __name__: uniqueModuleName,
      __display_name__: moduleName,
      __errors__: [] // Track errors in the module
    };

    try {
      // Read file contents
      const sourceCode = fs.readFileSync(filePath, 'utf8');

      // Create a mock for CharacterStatUI
      this.ensureCharacterStatUIMock();

      try {
        // Instead of creating temporary files, we'll parse and evaluate the code directly
        try {
          // In-memory evaluation of the module
          // Since we're in a test environment, we can simulate the module structure

          // Create a basic module structure with default properties
          moduleObj.default = {
            title: 'CharacterStatUI',
            component: {
              name: 'CharacterStatUI'
            }
          };

          // Extract the Default.args from the source code
          const argsMatch = sourceCode.match(/Default\.args\s*=\s*({[^;]*});/);
          if (argsMatch && argsMatch[1]) {
            try {
              // Create a safe evaluation context for the args
              // This is a simple approach - in production we'd use a proper sandbox
              moduleObj.Default = {
                name: 'bound Template',
                args: {}
              };

              // Parse the args object
              const argsText = argsMatch[1].replace(/[\r\n]/g, '');
              // Extract key-value pairs with a basic regex
              const keyValuePairs = argsText.match(/(\w+)\s*:\s*([^,}]+)/g) || [];

              for (const pair of keyValuePairs) {
                const [key, valueStr] = pair.split(':').map(s => s.trim());
                // Parse the value (handling numbers and strings)
                let value;
                if (valueStr.startsWith('"') || valueStr.startsWith("'")) {
                  // It's a string
                  value = valueStr.replace(/^["']|["']$/g, '');
                } else if (!isNaN(Number(valueStr))) {
                  // It's a number
                  value = Number(valueStr);
                } else {
                  // Default to string
                  value = valueStr;
                }

                moduleObj.Default.args[key] = value;
              }
            } catch (e) {
              console.error(`Error parsing args for ${implName}:`, e.message);
            }
          }

          // Check for parameters in the default export
          const paramsMatch = sourceCode.match(/parameters\s*:\s*({[^}]*})/);
          if (paramsMatch && paramsMatch[1]) {
            try {
              moduleObj.default.parameters = {};

              // Parse the parameters object
              const paramsText = paramsMatch[1].replace(/[\r\n]/g, '');
              // Extract key-value pairs
              const keyValuePairs = paramsText.match(/(\w+)\s*:\s*([^,}]+)/g) || [];

              for (const pair of keyValuePairs) {
                const [key, valueStr] = pair.split(':').map(s => s.trim());
                // Parse the value
                let value;
                if (valueStr.startsWith('"') || valueStr.startsWith("'")) {
                  value = valueStr.replace(/^["']|["']$/g, '');
                } else if (!isNaN(Number(valueStr))) {
                  value = Number(valueStr);
                } else {
                  value = valueStr;
                }

                moduleObj.default.parameters[key] = value;
              }
            } catch (e) {
              console.error(`Error parsing parameters for ${implName}:`, e.message);
            }
          }

          // Add React for tests that need it
          moduleObj.React = require('react');

        } catch (e) {
          const errorMsg = `Runtime error: ${e.message}`;
          console.error(`Error executing module ${filePath}: ${e.message}`);

          // Record the runtime error
          moduleObj.__errors__.push({
            type: 'runtime',
            message: errorMsg,
            stack: e.stack
          });
        }
      } catch (e) {
        const errorMsg = `Syntax error: ${e.message}`;
        console.error(`Syntax error in ${filePath}: ${e.message}`);

        // Record the error but continue loading what we can
        moduleObj.__errors__.push({
          type: 'syntax',
          message: errorMsg,
          lineNumber: e.loc ? e.loc.line : undefined,
          columnNumber: e.loc ? e.loc.column : undefined
        });
      }

      return moduleObj;
    } catch (e) {
      if (e.code === 'ENOENT') {
        const errorMsg = `File not found: ${e.message}`;
        console.error(`Error: ${errorMsg}`);
        moduleObj.__errors__.push({
          type: 'file',
          message: errorMsg
        });
      } else {
        const errorMsg = `Unexpected error: ${e.message}`;
        console.error(`Error loading module ${filePath}: ${e.message}`);
        moduleObj.__errors__.push({
          type: 'unknown',
          message: errorMsg
        });
      }

      return moduleObj;
    }
  }

  /**
   * Ensure the CharacterStatUI mock exists
   */
  static ensureCharacterStatUIMock() {
    const mockDir = path.join(__dirname, 'mocks');
    const mockPath = path.join(mockDir, 'CharacterStatUIMock.jsx');

    if (!fs.existsSync(mockDir)) {
      fs.mkdirSync(mockDir, { recursive: true });
    }

    if (!fs.existsSync(mockPath)) {
      const mockContent = `
// Mock implementation of CharacterStatUI
const React = require('react');

const CharacterStatUI = (props) => {
  return React.createElement('div', { 'data-testid': 'character-stat-ui' }, 'CharacterStatUI Mock');
};

module.exports = CharacterStatUI;
      `;
      fs.writeFileSync(mockPath, mockContent);
    }
  }

  /**
   * Load all implementation files in the directory
   * @param {string} directory - Directory to search in (defaults to current directory)
   * @returns {Object} Dictionary mapping module names to loaded modules
   */
  static loadAllImplementations(directory = null) {
    if (!directory) {
      directory = __dirname;
    }

    const implementations = {};

    const implementationFiles = this.discoverImplementationFiles(directory);
    if (implementationFiles.length === 0) {
      console.warn("WARNING: No implementation files found. Check your file naming patterns.");
      return implementations; // Return empty object rather than null
    }

    for (const filePath of implementationFiles) {
      const moduleName = path.basename(filePath).replace(/\.(js|jsx)$/, '');
      const module = this.loadModule(filePath, moduleName);

      // Always add the module, even if it has errors
      implementations[moduleName] = module;

      if (module.__errors__ && module.__errors__.length > 0) {
        console.log(`Loaded with errors: ${moduleName} - ${module.__errors__.length} errors found`);
        module.__errors__.forEach(err => console.log(`  - ${err.type}: ${err.message}`));
      } else {
        console.log(`Successfully loaded: ${moduleName}`);
      }
    }

    return implementations;
  }

  /**
   * Check if a function exists in a module and is callable
   * @param {Object} module - The loaded module
   * @param {string} functionName - Name of the function to test
   * @returns {boolean} Whether the function exists and is callable
   */
  static hasFunction(module, functionName) {
    return module && typeof module[functionName] === 'function';
  }

  /**
   * Safely call a function in a module with error handling
   * @param {Object} module - The loaded module
   * @param {string} functionName - Name of the function to call
   * @param {Array} args - Arguments to pass to the function
   * @returns {Object} Result with success status and value or error
   */
  static callFunction(module, functionName, ...args) {
    if (!this.hasFunction(module, functionName)) {
      return {
        success: false,
        error: `Function '${functionName}' not found or not callable`
      };
    }

    try {
      const result = module[functionName](...args);
      return {
        success: true,
        value: result
      };
    } catch (e) {
      return {
        success: false,
        error: e.message,
        stack: e.stack
      };
    }
  }
}

/**
 * Class to manage test results
 */
class TestResultsManager {
  constructor() {
    this.results = {};
    this.sandboxName = path.basename(__dirname);
  }

  /**
   * Record a test result for an implementation
   * @param {string} implName - Implementation name
   * @param {string} testName - Test name
   * @param {boolean} passed - Whether the test passed
   * @param {string} errorMsg - Optional error message
   */
  recordResult(implName, testName, passed, errorMsg = null) {
    if (!this.results[implName]) {
      this.results[implName] = { passed: 0, failed: 0, skipped: 0, errors: [] };
    }

    if (passed) {
      this.results[implName].passed += 1;
    } else {
      this.results[implName].failed += 1;
      if (errorMsg) {
        this.results[implName].errors.push({
          test: testName,
          error: errorMsg
        });
      }
    }
  }

  /**
   * Record a skipped test for an implementation
   * @param {string} implName - Implementation name
   * @param {string} testName - Test name
   * @param {string} reason - Optional reason for skipping
   */
  recordSkip(implName, testName, reason = null) {
    if (!this.results[implName]) {
      this.results[implName] = { passed: 0, failed: 0, skipped: 0, errors: [] };
    }

    this.results[implName].skipped += 1;
    if (reason) {
      this.results[implName].errors.push({
        test: testName,
        error: `SKIPPED: ${reason}`
      });
    }
  }

  /**
   * Determine the winner based on test results
   * @returns {Array} [winner index, results]
   */
  getWinner() {
    let winner = null;
    let maxPassed = -1;

    for (const [implName, results] of Object.entries(this.results)) {
      if (implName === "original_code") {
        continue; // Skip original code when determining winner
      }

      if (results.passed > maxPassed) {
        maxPassed = results.passed;
        winner = implName;
      } else if (results.passed === maxPassed && winner !== null) {
        if (results.failed < this.results[winner].failed) {
          winner = implName;
        }
      }
    }

    // Convert winner to numeric index if possible
    let winnerIndex = -1;
    if (winner) {
      if (/modified_code(\d+)/.test(winner)) {
        const match = winner.match(/(\d+)/);
        if (match) {
          winnerIndex = parseInt(match[1]);
        }
      } else if (/new_code(\d+)/.test(winner)) {
        const match = winner.match(/(\d+)/);
        if (match) {
          winnerIndex = parseInt(match[1]);
        }
      }
    }

    return [winnerIndex, this.results];
  }

  /**
   * Save test results to a JSON file
   * @param {string} filename - Output filename
   * @returns {Object} Results summary object
   */
  saveResults(filename = "test_results.json") {
    const [winnerIndex, results] = this.getWinner();

    // Check if all tests were skipped
    let allSkipped = true;
    if (Object.keys(results).length > 0) {
      allSkipped = Object.entries(results)
        .filter(([implName]) => implName !== "original_code")
        .every(([_, stats]) => {
          return stats.passed === 0 && stats.failed === 0 && stats.skipped > 0;
        });
    }

    const output = {
      winner: winnerIndex,
      all_skipped: allSkipped,
      results: {}
    };

    for (const [name, stats] of Object.entries(results)) {
      if (!name.startsWith("_")) {
        output.results[name] = {
          passed: stats.passed,
          failed: stats.failed,
          skipped: stats.skipped,
          total: stats.passed + stats.failed + stats.skipped
        };
      }
    }

    fs.writeFileSync(filename, JSON.stringify(output, null, 2));
    console.log(`Test results saved to ${filename}`);

    return output;
  }
}

// Create the mocks directory and CharacterStatUI mock if they don't exist
TestUtils.ensureCharacterStatUIMock();

// Load implementations for this specific implementation directory
const implementations = TestUtils.loadAllImplementations();
const resultsManager = new TestResultsManager();

// Set up global variables for Jest tests
beforeAll(() => {
  global.__TEST_UTILS__ = TestUtils;
  global.__RESULTS_MANAGER__ = resultsManager;
  global.__IMPLEMENTATIONS__ = implementations;

  // Debug log
  console.log('Loaded implementation count:', Object.keys(implementations).length);
  console.log('Implementation keys:', Object.keys(implementations));
});

// After all tests run, save the results
afterAll(() => {
  resultsManager.saveResults();
});

// Export for use in tests
module.exports = {
  TestUtils,
  TestResultsManager,
  implementations,
  resultsManager
};


import React, { useRef, useEffect, useState } from 'react'
import { useGetQueryListQuery } from '../../api/query';
import { MdOutlineArrowDropDown } from 'react-icons/md';

const Query = () => {
  const abortController = useRef(null);
  const [isQueryOpen, setIsQueryOpen] = useState(false);
  const [selectedQuery, setSelectedQuery] = useState(null);

  const { data: queries, isFetching: queriesFetching, isLoading: queriesLoading } = useGetQueryListQuery({},
    {
      signal: abortController?.current?.signal
    }
  )

  // handleQuerySelect
  const handleQuerySelect = (query) => {
    setSelectedQuery(query);
    setIsQueryOpen(false);
  };

  useEffect(() => {
    abortController.current = new AbortController();
    return () => {
      abortController.current.abort();
    };
  }, []);

  return (

        <button
          type='button'
          className="w-full sm:w-auto bg-[#CB427C] focus:border-1 focus:border-[#CB427C] focus:outline-none text-white text-sm px-4 py-2 rounded-[24px] disabled:opacity-50">
          Add new
        </button>

Query name

            <button
              type="button"
              className="flex justify-between font-circe-light items-center w-full h-8 p-4 text-sm border border-[#dde6e9] font-thin focus:outline-none focus:border-1 focus:border-[#CB427C]"
              onClick={() => setIsQueryOpen(!isQueryOpen)}
            >
              {selectedQuery?.name || "Select query"}
              <MdOutlineArrowDropDown className="text-xl" />
            </button>
            {isQueryOpen && queries?.data?.length > 0 && (

                {queries?.data.length === 0 ? (

                    No queries available

                ) : (
                  queries?.data.map((query) => (

 handleQuerySelect(query)}
                    >
                      {query.name}

                  ))
                )}

            )}

  )
}

export default Query

const fs = require('fs');
const path = require('path');
const React = require('react');
const { render, screen, fireEvent, within } = require('@testing-library/react');
const { TestUtils, resultsManager } = require('../jest-setup');

// Import the instruction to check implementations against
const instruction = fs.readFileSync(path.join(__dirname, '../instruction.txt'), 'utf8').trim();

// Load implementations directly
const implementations = TestUtils.loadAllImplementations();

// For this test, we need to create a component loader
// that dynamically imports a component from a file
const loadReactComponent = async (filePath) => {
  try {
    // Use dynamic import with Babel to load JSX files
    const Component = require(filePath).default;
    return { Component, success: true };
  } catch (error) {
    console.error(`Error loading component from ${filePath}:`, error);
    return { success: false, error: error.message };
  }
};

// Function to read multiple implementation files and test them
const testImplementations = (implementations) => {
  describe('React Component Implementation Tests', () => {
    // Generic tests for all implementations
    Object.keys(implementations).forEach((implName) => {
      const impl = implementations[implName];

      describe(`Testing ${implName}`, () => {
        let Component;

        // Setup - Loading the component before tests
        beforeAll(async () => {
          try {
            const result = await loadReactComponent(impl.__file__);
            if (result.success) {
              Component = result.Component;
            } else {
              console.error(`Failed to load ${implName}:`, result.error);
            }
          } catch (error) {
            console.error(`Error loading ${implName}:`, error);
          }
        });

        // Skip all tests if component couldn't be loaded
        beforeEach(() => {
          if (!Component) {
            resultsManager.recordSkip(implName, 'Component loading', 'Component could not be loaded');
            throw new Error(`Component ${implName} could not be loaded`);
          }
        });

        // Test: Component should render without crashing
        test('should render without crashing', () => {
          try {
            render(<Component />);
            resultsManager.recordResult(implName, 'render_without_crashing', true);
          } catch (error) {
            resultsManager.recordResult(implName, 'render_without_crashing', false, error.message);
            throw error;
          }
        });

        // Test: Component should have an "Add new" button
        test('should have an "Add new" button', () => {
          try {
            render(<Component />);
            const addButton = screen.getByText('Add new');
            expect(addButton).toBeTruthy();
            resultsManager.recordResult(implName, 'has_add_new_button', true);
          } catch (error) {
            resultsManager.recordResult(implName, 'has_add_new_button', false, error.message);
            throw error;
          }
        });

        // Test: Component should have a dropdown button with default text
        test('should have a dropdown button with default text', () => {
          try {
            render(<Component />);
            // The dropdown might have the text split across elements
            // or combined with other elements, so we use a more flexible approach
            const buttons = screen.getAllByRole('button');
            const dropdownButton = buttons.find(button =>
              button.textContent.includes('Select query')
            );
            expect(dropdownButton).toBeTruthy();
            resultsManager.recordResult(implName, 'has_dropdown_button', true);
          } catch (error) {
            resultsManager.recordResult(implName, 'has_dropdown_button', false, error.message);
            throw error;
          }
        });

        // Test: Dropdown should open when clicked
        test('should open dropdown when clicked', () => {
          try {
            const { container } = render(<Component />);

            // Find the dropdown button by role and text content
            const buttons = screen.getAllByRole('button');
            const dropdownButton = buttons.find(button =>
              button.textContent.includes('Select query')
            );

            // Click to open dropdown
            fireEvent.click(dropdownButton);

            // Dropdown should now be visible - look for option presence
            const queryText = screen.getByText('Query 1', { exact: false });
            expect(queryText).toBeInTheDocument();

            resultsManager.recordResult(implName, 'dropdown_opens', true);
          } catch (error) {
            resultsManager.recordResult(implName, 'dropdown_opens', false, error.message);
            throw error;
          }
        });

        // Test: Should select a query when clicked
        test('should select a query when clicked', () => {
          try {
            render(<Component />);

            // Find the dropdown button by role and content
            const buttons = screen.getAllByRole('button');
            const dropdownButton = buttons.find(button =>
              button.textContent.includes('Select query')
            );

            // Open dropdown
            fireEvent.click(dropdownButton);

            // Find and click on the second option
            const option2Elements = screen.getAllByText(/Query 2/i);
            const option = option2Elements.find(el =>
              // Look for elements that might be query options
              el.className.includes('cursor-pointer') ||
              // If the query option is within a div with onclick property
              el.closest('div[class*="cursor-pointer"]')
            );

            if (!option) {
              throw new Error('Could not find clickable Query 2 option');
            }

            fireEvent.click(option);

            // After selection, the dropdown button should show the selected query
            const updatedButtons = screen.getAllByRole('button');
            const updatedDropdownButton = updatedButtons.find(button =>
              button.textContent.includes('Query 2')
            );

            expect(updatedDropdownButton).toBeTruthy();

            resultsManager.recordResult(implName, 'selects_query', true);
          } catch (error) {
            resultsManager.recordResult(implName, 'selects_query', false, error.message);
            throw error;
          }
        });

        // Test: Should have a "Query name" label
        test('should have a "Query name" label', () => {
          try {
            const { container } = render(<Component />);
            // Look for any element containing the text "Query name"
            const labelElements = screen.getAllByText(/Query name/i);
            expect(labelElements.length).toBeGreaterThan(0);

            // Find the element that's a label
            const label = labelElements.find(el =>
              el.tagName.toLowerCase() === 'label' ||
              el.getAttribute('role') === 'label'
            );

            expect(label).toBeTruthy();
            resultsManager.recordResult(implName, 'has_query_name_label', true);
          } catch (error) {
            resultsManager.recordResult(implName, 'has_query_name_label', false, error.message);
            throw error;
          }
        });

        // Specific tests for the instruction: adjust width according to content
        test('should implement label width according to content', () => {
          try {
            const { container } = render(<Component />);
            const labelElements = screen.getAllByText(/Query name/i);

            // Find the element that's a label
            const label = labelElements.find(el =>
              el.tagName.toLowerCase() === 'label' ||
              el.getAttribute('role') === 'label'
            ) || labelElements[0]; // Fallback to first element if no label found

            // Check if there's some kind of width setting in the implementations
            // We'll use several strategies to detect this, looking for CSS classes
            // that adjust width based on content

            // Common TailwindCSS classes for width fitting
            const hasFittingClass =
              label.className.includes('w-fit') ||
              label.className.includes('w-auto') ||
              label.className.includes('inline-block') ||
              label.className.includes('whitespace-nowrap') ||
              label.className.includes('inline') ||
              label.className.includes('inline-flex') ||
              label.className.includes('w-min') ||
              label.className.includes('w-max') ||
              label.className.includes('max-w-fit') ||
              label.className.includes('min-w-fit') ||
              label.className.includes('flex-none') ||
              label.className.includes('flex-shrink-0') ||
              label.className.includes('shrink-0');

            // Skip this check for original_code which we don't expect to have the width adjustment
            if (implName === 'original_code') {
              // Just record as passed but don't check the actual value
              resultsManager.recordResult(implName, 'has_width_fit_class', true);
            } else {
              // For all other implementations, expect the fitting class to be present
              expect(hasFittingClass).toBe(true);
              resultsManager.recordResult(implName, 'has_width_fit_class', true);
            }
          } catch (error) {
            resultsManager.recordResult(implName, 'has_width_fit_class', false, error.message);
            throw error;
          }
        });

        // Test: Dropdown should close after selection
        test('should close dropdown after selection', () => {
          try {
            render(<Component />);

            // Find the dropdown button
            const buttons = screen.getAllByRole('button');
            const dropdownButton = buttons.find(button =>
              button.textContent.includes('Select query')
            );

            // Open dropdown
            fireEvent.click(dropdownButton);

            // Find and click on first option
            const option1Elements = screen.getAllByText(/Query 1/i);
            const option = option1Elements.find(el =>
              el.className.includes('cursor-pointer') ||
              el.closest('div[class*="cursor-pointer"]')
            );

            if (!option) {
              throw new Error('Could not find clickable Query 1 option');
            }

            // Before clicking, we should be able to find Query 2
            const query2BeforeClick = screen.queryAllByText(/Query 2/i);
            expect(query2BeforeClick.length).toBeGreaterThan(0);

            // Click the option
            fireEvent.click(option);

            // After clicking, the dropdown should be closed and Query 2 should not be visible
            // Check for elements that don't have a parent button
            const query2AfterClickVisible = screen.queryAllByText(/Query 2/i).filter(el =>
              !el.closest('button')
            );

            expect(query2AfterClickVisible.length).toBe(0);

            // The dropdown button should now show Query 1
            const updatedButtons = screen.getAllByRole('button');
            const updatedDropdownButton = updatedButtons.find(button =>
              button.textContent.includes('Query 1')
            );

            expect(updatedDropdownButton).toBeTruthy();

            resultsManager.recordResult(implName, 'closes_dropdown_after_selection', true);
          } catch (error) {
            resultsManager.recordResult(implName, 'closes_dropdown_after_selection', false, error.message);
            throw error;
          }
        });
      });
    });
  });
};

// Run tests on all implementations
if (implementations && Object.keys(implementations).length > 0) {
  console.log(`Found ${Object.keys(implementations).length} implementations to test`);
  testImplementations(implementations);
} else {
  console.error('No implementations found or implementations are empty');

  // Add at least one dummy test to avoid Jest error
  test('dummy test to avoid Jest error', () => {
    expect(true).toBe(true);
  });
}

<label className="font-thin border">Query name</label>

Instruction: adjust width according to content

{
  "name": "js-test-framework",
  "version": "1.0.0",
  "description": "JavaScript testing framework for multiple implementations",
  "main": "index.js",
  "type": "commonjs",
  "scripts": {
    "test": "jest"
  },
  "devDependencies": {
    "@babel/preset-env": "^7.24.0",
    "@babel/preset-react": "^7.23.3",
    "@testing-library/jest-dom": "^6.4.2",
    "@testing-library/react": "^14.2.1",
    "babel-jest": "^29.7.0",
    "glob": "^10.3.10",
    "jest": "^29.7.0",
    "jest-environment-jsdom": "^29.7.0",
    "react": "^18.2.0",
    "react-dom": "^18.2.0"
  },
  "jest": {
    "setupFilesAfterEnv": ["./jest-setup.js", "./jest-dom-setup.js"],
    "testEnvironment": "jsdom",
    "testMatch": ["**/tests/**/*.test.js"],
    "verbose": true,
    "transform": {
      "^.+\\.(js|jsx)$": "babel-jest"
    },
    "moduleNameMapper": {
      "\\.(css|less|scss|sass)$": "<rootDir>/__mocks__/styleMock.js",
      "\\.(jpg|jpeg|png|gif|webp|svg)$": "<rootDir>/__mocks__/fileMock.js",
      "^../../api/(.*)$": "<rootDir>/__mocks__/api/$1"
    },
    "collectCoverage": true,
    "coverageDirectory": "./coverage",
    "collectCoverageFrom": [
      "./*.jsx",
      "!jest-setup.js"
    ]
  }
}

// jest-setup.js - Setup file for Jest tests
const fs = require('fs');
const path = require('path');
const glob = require('glob');

/**
 * Utility class to handle JavaScript implementations
 */
class TestUtils {
  /**
   * Find all implementation files in the current directory
   * @param {string} directory - Directory to search in (defaults to current directory)
   * @returns {Array<string>} List of implementation file paths
   */
  static discoverImplementationFiles(directory = null) {
    if (!directory) {
      directory = __dirname;
    }

    const patterns = [
      'modified_code\\d+\\.jsx',
      'new_code\\d+\\.jsx',
      'original_modified_code\\d+\\.jsx',
      'implementation\\d*\\.jsx',
      'original_code\\.jsx'
    ];

    const regexPattern = new RegExp(patterns.join('|'));
    const implementations = [];

    // Use glob to find matching files
    const files = glob.sync(path.join(directory, '*.jsx'));

    for (const filePath of files) {
      if (regexPattern.test(path.basename(filePath))) {
        implementations.push(filePath);
      }
    }

    // Sort files numerically
    implementations.sort((a, b) => {
      // Keep original_code always first
      if (path.basename(a) === 'original_code.jsx') return -1;
      if (path.basename(b) === 'original_code.jsx') return 1;

      const aMatch = path.basename(a).match(/(\d+)/);
      const bMatch = path.basename(b).match(/(\d+)/);
      const aNum = aMatch ? parseInt(aMatch[1]) : 0;
      const bNum = bMatch ? parseInt(bMatch[1]) : 0;
      return aNum - bNum;
    });

    return implementations;
  }

  /**
   * Safely load a module from a file path
   * @param {string} filePath - Path to the JavaScript or JSX file
   * @param {string} moduleName - Optional module name (defaults to filename)
   * @returns {Object} Loaded module with error information if any
   */
  static loadModule(filePath, moduleName = null) {
    if (!moduleName) {
      moduleName = path.basename(filePath).replace(/\.(js|jsx)$/, '');
    }

    // Create unique module name to avoid conflicts
    const sandboxId = path.basename(path.dirname(filePath));
    const uniqueModuleName = `${sandboxId}_${moduleName}`;

    try {
      // Read file contents
      const sourceCode = fs.readFileSync(filePath, 'utf8');

      // Create module object
      const moduleObj = {
        __file__: filePath,
        __name__: uniqueModuleName,
        __display_name__: moduleName,
        __source__: sourceCode, // Store source code for testing purposes
        __errors__: [] // Track errors in the module
      };

      // For JSX files, we can't easily test-compile, so we'll skip that step
      // and rely on Jest/Babel to handle the JSX transformation
      if (!filePath.endsWith('.jsx')) {
        try {
          // Try to test-compile the code to check for syntax errors
          new Function(sourceCode);
        } catch (e) {
          const errorMsg = `Syntax error: ${e.message}`;
          console.error(`Syntax error in ${filePath}: ${e.message}`);
          console.error(`  Line ${e.lineNumber}, column ${e.columnNumber}`);

          // Record the error but continue loading what we can
          moduleObj.__errors__.push({
            type: 'syntax',
            message: errorMsg,
            lineNumber: e.lineNumber,
            columnNumber: e.columnNumber
          });
        }
      }

      // For JSX/React components, we'll handle them differently in tests
      // and not attempt to require them directly
      if (filePath.endsWith('.jsx')) {
        moduleObj.__component_file__ = true;
        return moduleObj;
      }

      try {
        // Try to require the module even if there were syntax errors
        // This may or may not succeed
        delete require.cache[require.resolve(filePath)];
        const loadedModule = require(filePath);

        // Copy all properties from the loaded module
        for (const key in loadedModule) {
          if (Object.prototype.hasOwnProperty.call(loadedModule, key)) {
            moduleObj[key] = loadedModule[key];
          }
        }
      } catch (e) {
        const errorMsg = `Runtime error: ${e.message}`;
        console.error(`Error executing module ${filePath}: ${e.message}`);
        console.error(e.stack);

        // Record the runtime error
        moduleObj.__errors__.push({
          type: 'runtime',
          message: errorMsg,
          stack: e.stack
        });
      }

      return moduleObj;
    } catch (e) {
      const moduleObj = {
        __file__: filePath,
        __name__: uniqueModuleName,
        __display_name__: moduleName,
        __errors__: []
      };

      if (e.code === 'ENOENT') {
        const errorMsg = `File not found: ${e.message}`;
        console.error(`Error: ${errorMsg}`);
        moduleObj.__errors__.push({
          type: 'file',
          message: errorMsg
        });
      } else {
        const errorMsg = `Unexpected error: ${e.message}`;
        console.error(`Error loading module ${filePath}: ${e.message}`);
        moduleObj.__errors__.push({
          type: 'unknown',
          message: errorMsg
        });
      }

      return moduleObj;
    }
  }

  /**
   * Load all implementation files in the directory
   * @param {string} directory - Directory to search in (defaults to current directory)
   * @returns {Object} Dictionary mapping module names to loaded modules
   */
  static loadAllImplementations(directory = null) {
    if (!directory) {
      directory = __dirname;
    }

    const implementations = {};

    const implementationFiles = this.discoverImplementationFiles(directory);
    if (implementationFiles.length === 0) {
      console.warn("WARNING: No implementation files found. Check your file naming patterns.");
    }

    for (const filePath of implementationFiles) {
      const moduleName = path.basename(filePath).replace(/\.(js|jsx)$/, '');
      const module = this.loadModule(filePath, moduleName);

      // Always add the module, even if it has errors
      implementations[moduleName] = module;

      if (module.__errors__ && module.__errors__.length > 0) {
        console.log(`Loaded with errors: ${moduleName} - ${module.__errors__.length} errors found`);
        module.__errors__.forEach(err => console.log(`  - ${err.type}: ${err.message}`));
      } else {
        console.log(`Successfully loaded: ${moduleName}`);
      }
    }

    return implementations;
  }

  /**
   * Check if a function exists in a module and is callable
   * @param {Object} module - The loaded module
   * @param {string} functionName - Name of the function to test
   * @returns {boolean} Whether the function exists and is callable
   */
  static hasFunction(module, functionName) {
    return module && typeof module[functionName] === 'function';
  }

  /**
   * Safely call a function in a module with error handling
   * @param {Object} module - The loaded module
   * @param {string} functionName - Name of the function to call
   * @param {Array} args - Arguments to pass to the function
   * @returns {Object} Result with success status and value or error
   */
  static callFunction(module, functionName, ...args) {
    if (!this.hasFunction(module, functionName)) {
      return {
        success: false,
        error: `Function '${functionName}' not found or not callable`
      };
    }

    try {
      const result = module[functionName](...args);
      return {
        success: true,
        value: result
      };
    } catch (e) {
      return {
        success: false,
        error: e.message,
        stack: e.stack
      };
    }
  }
}

/**
 * Class to manage test results
 */
class TestResultsManager {
  constructor() {
    this.results = {};
    this.sandboxName = path.basename(__dirname);
  }

  /**
   * Record a test result for an implementation
   * @param {string} implName - Implementation name
   * @param {string} testName - Test name
   * @param {boolean} passed - Whether the test passed
   * @param {string} errorMsg - Optional error message
   */
  recordResult(implName, testName, passed, errorMsg = null) {
    if (!this.results[implName]) {
      this.results[implName] = { passed: 0, failed: 0, skipped: 0, errors: [] };
    }

    if (passed) {
      this.results[implName].passed += 1;
    } else {
      this.results[implName].failed += 1;
      if (errorMsg) {
        this.results[implName].errors.push({
          test: testName,
          error: errorMsg
        });
      }
    }
  }

  /**
   * Record a skipped test for an implementation
   * @param {string} implName - Implementation name
   * @param {string} testName - Test name
   * @param {string} reason - Optional reason for skipping
   */
  recordSkip(implName, testName, reason = null) {
    if (!this.results[implName]) {
      this.results[implName] = { passed: 0, failed: 0, skipped: 0, errors: [] };
    }

    this.results[implName].skipped += 1;
    if (reason) {
      this.results[implName].errors.push({
        test: testName,
        error: `SKIPPED: ${reason}`
      });
    }
  }

  /**
   * Determine the winner based on test results
   * @returns {Array} [winner index, results]
   */
  getWinner() {
    let winner = null;
    let maxPassed = -1;

    for (const [implName, results] of Object.entries(this.results)) {
      // Skip original code when determining winner
      if (implName === "original_code" || implName === "original_codex") {
        continue;
      }

      if (results.passed > maxPassed) {
        maxPassed = results.passed;
        winner = implName;
      } else if (results.passed === maxPassed && winner !== null) {
        if (results.failed < this.results[winner].failed) {
          winner = implName;
        }
      }
    }

    // If we have a tie, prefer the modified_code implementations over others
    if (winner) {
      // Create a tie-breaker score that prioritizes implementations based on instruction match
      const tiedImplementations = Object.entries(this.results)
        .filter(([name, res]) =>
          name !== "original_code" &&
          name !== "original_codex" &&
          res.passed === maxPassed)
        .map(([name, _]) => name);

      if (tiedImplementations.length > 1) {
        // First, prefer the modified_code implementations
        const modifiedCodeImpls = tiedImplementations.filter(name =>
          name.startsWith('modified_code'));

        if (modifiedCodeImpls.length > 0) {
          // If there are multiple modified_code implementations, pick the first one
          winner = modifiedCodeImpls[0];
        }
      }
    }

    // Convert winner to numeric index if possible
    let winnerIndex = -1;
    if (winner) {
      if (/modified_code\d+/.test(winner)) {
        const match = winner.match(/(\d+)/);
        if (match) {
          winnerIndex = parseInt(match[1]);
        }
      } else if (/new_code\d+/.test(winner)) {
        const match = winner.match(/(\d+)/);
        if (match) {
          winnerIndex = parseInt(match[1]);
        }
      }
    }

    return [winnerIndex, this.results];
  }

  /**
   * Save test results to a JSON file
   * @param {string} filename - Output filename
   * @returns {Object} Results summary object
   */
  saveResults(filename = "test_results.json") {
    const [winnerIndex, results] = this.getWinner();

    // Check if all tests were skipped
    const allSkipped = Object.entries(results)
      .filter(([implName]) => implName !== "original_code")
      .every(([_, stats]) => {
        return stats.skipped === (stats.passed + stats.failed + stats.skipped);
      });

    const output = {
      winner: winnerIndex,
      all_skipped: allSkipped,
      results: {}
    };

    for (const [name, stats] of Object.entries(results)) {
      if (!name.startsWith("_")) {
        output.results[name] = {
          passed: stats.passed,
          failed: stats.failed,
          skipped: stats.skipped,
          total: stats.passed + stats.failed + stats.skipped
        };
      }
    }

    fs.writeFileSync(filename, JSON.stringify(output, null, 2));
    console.log(`Test results saved to ${filename}`);

    return output;
  }
}

// Create results manager
const resultsManager = new TestResultsManager();

// Set up global variables for Jest tests
beforeAll(() => {
  // Load implementations inside the beforeAll to ensure it runs in the Jest environment
  const implementations = TestUtils.loadAllImplementations();
  console.log(`Found ${Object.keys(implementations).length} implementations`);

  global.__TEST_UTILS__ = TestUtils;
  global.__RESULTS_MANAGER__ = resultsManager;
  global.__IMPLEMENTATIONS__ = implementations;
});

// After all tests run, save the results
afterAll(() => {
  resultsManager.saveResults();
});

// Export for use in tests
module.exports = {
  TestUtils,
  TestResultsManager,
  resultsManager
};

// Import jest-dom utilities
require('@testing-library/jest-dom');

module.exports = {
  presets: [
    ['@babel/preset-env', { targets: { node: 'current' } }],
    ['@babel/preset-react', { runtime: 'automatic' }]
  ],
};

// Mock for MdOutlineArrowDropDown component
const MdOutlineArrowDropDown = () => {
  return 'MdOutlineArrowDropDown';
};

module.exports = {
  MdOutlineArrowDropDown
};

// Mock for useGetQueryListQuery hook
const mockQueries = {
  data: [
    { id: 1, name: 'Query 1' },
    { id: 2, name: 'Query 2' },
    { id: 3, name: 'Query 3' }
  ]
};

const useGetQueryListQuery = (params, options) => {
  return {
    data: mockQueries,
    isFetching: false,
    isLoading: false
  };
};

module.exports = {
  useGetQueryListQuery
};