function panelLegendContent() {
    let legendContainer = document.createElement('div');
    legendContainer.setAttribute('id', 'legend-display');

    let headerTitle = "Color Legend";
    let headerElement = document.createElement('h3');
    headerElement.innerText = headerTitle;

    let legend = createLegend();

    // Add Reset Button
    const resetButton = document.createElement("button");
    resetButton.textContent = "Reset to Default";
    resetButton.style.marginTop = "20px";
    resetButton.addEventListener("click", resetColorsToDefault);

    legendContainer.appendChild(headerElement);
    legendContainer.appendChild(legend);
    legendContainer.appendChild(resetButton);

    return legendContainer;
}

function createLegend() {
    const colorClasses = [
        { name: "Straight", class: "hilight-straight", defaultColor: "#eac015" },
		{ name: "Quad", class: "hilight-quad", defaultColor: "rgb(4, 134, 255)" },
		{ name: "Splits - down", class: "hilight-split-upDown", defaultColor: "rgb(146, 235, 158)" },
		{ name: "Split - across", class: "hilight-split-across", defaultColor: "rgb(146, 235, 158)" },
		{ name: "Street", class: "hilight-street", defaultColor: "rgb(255, 0, 0)" },
		{ name: "Street 345", class: "hilight-street345", defaultColor: "rgb(255, 0, 0)" },
		{ name: "Line", class: "hilight-double-street", defaultColor: "rgb(72, 41, 248)" },
		{ name: "Pattern Break", class: "hilight-pattern-break", defaultColor: "rgb(12, 141, 247)" },
		{ name: "Groups", class: "hilight-groups", defaultColor: "rgb(30, 255, 0)" },
		{ name: "Uniques", class: "hilight-unique", defaultColor: "rgb(250, 63, 219)" },
		{ name: "Pattern eohl", class: "hilight-pattern-even-odd-high-low", defaultColor: "rgb(71, 48, 68)" },
		{ name: "Pattern rows", class: "hilight-pattern-rows", defaultColor: "rgb(71, 48, 68)" },
		{ name: "Pattern h/l", class: "hilight-pattern-hilow", defaultColor: "rgb(71, 48, 68)" },

    ];

    const legendContainer = document.createElement("div");
    legendContainer.id = "legend";
    legendContainer.style.margin = '20px';
    legendContainer.style.fontSize = '18px';
    legendContainer.style.padding = '25px';

    function createLegendItem(colorClass) {
        const item = document.createElement("div");
        item.style.display = "flex";
        item.style.alignItems = "center";
        item.style.marginBottom = "10px";

        const label = document.createElement("span");
        label.textContent = colorClass.name;
        label.style.marginRight = "10px";

        // Get stored color or default color
        const storedColor = localStorage.getItem(colorClass.class);
        const currentColor = storedColor || colorClass.defaultColor;

        // Create the color picker
        const colorPicker = document.createElement("input");
        colorPicker.type = "color";
        colorPicker.value = rgbToHex(currentColor);
        colorPicker.style.marginLeft = "auto";

        colorPicker.addEventListener("input", (event) => {
            const newColor = event.target.value;
            updatePseudoElementColor(colorClass.class, newColor);
            localStorage.setItem(colorClass.class, newColor);
        });

        // Apply initial color to the pseudo-element
        updatePseudoElementColor(colorClass.class, currentColor);

        item.appendChild(label);
        item.appendChild(colorPicker);

        legendContainer.appendChild(item);
    }

    colorClasses.forEach(createLegendItem);

    return legendContainer;
}

function resetColorsToDefault() {
    const colorClasses = [
        { name: "Straight", class: "hilight-straight", defaultColor: "#eac015" },
		{ name: "Quad", class: "hilight-quad", defaultColor: "rgb(4, 134, 255)" },
		{ name: "Splits - down", class: "hilight-split-upDown", defaultColor: "rgb(146, 235, 158)" },
		{ name: "Split - across", class: "hilight-split-across", defaultColor: "rgb(146, 235, 158)" },
		{ name: "Street", class: "hilight-street", defaultColor: "rgb(255, 0, 0)" },
		{ name: "Street 345", class: "hilight-street345", defaultColor: "rgb(255, 0, 0)" },
		{ name: "Line", class: "hilight-double-street", defaultColor: "rgb(72, 41, 248)" },
		{ name: "Pattern Break", class: "hilight-pattern-break", defaultColor: "rgb(12, 141, 247)" },
		{ name: "Groups", class: "hilight-groups", defaultColor: "rgb(30, 255, 0)" },
		{ name: "Uniques", class: "hilight-unique", defaultColor: "rgb(250, 63, 219)" },
		{ name: "Pattern eohl", class: "hilight-pattern-even-odd-high-low", defaultColor: "rgb(71, 48, 68)" },
		{ name: "Pattern rows", class: "hilight-pattern-rows", defaultColor: "rgb(71, 48, 68)" },
		{ name: "Pattern h/l", class: "hilight-pattern-hilow", defaultColor: "rgb(71, 48, 68)" },
    ];

    colorClasses.forEach((colorClass) => {
        localStorage.removeItem(colorClass.class);
        updatePseudoElementColor(colorClass.class, colorClass.defaultColor);
    });

    // Reload the legend to reflect changes
    const legendDisplay = document.getElementById('legend-display');
    if (legendDisplay) {
        legendDisplay.replaceWith(panelLegendContent());
    }
}

function updatePseudoElementColor(className, newColor) {
    const styleElement = document.getElementById('dynamic-styles');
    if (!styleElement) {
        const newStyleElement = document.createElement('style');
        newStyleElement.id = 'dynamic-styles';
        document.head.appendChild(newStyleElement);
    }

    const dynamicStyle = document.getElementById('dynamic-styles');
    dynamicStyle.sheet.insertRule(
        `.${className}::before { background-color: ${newColor} !important; }`,
        dynamicStyle.sheet.cssRules.length
    );
}

function rgbToHex(color) {
    if (!color) return "#000000"; // Default fallback color

    // Check if color is already in HEX format
    if (color.startsWith("#")) return color;

    // Extract RGB values from 'rgb(r, g, b)' string
    const rgbMatch = color.match(/\d+/g);
    if (rgbMatch) {
        const [r, g, b] = rgbMatch.map(Number);
        return `#${((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1)}`;
    }

    // Fallback to black if parsing fails
    return "#000000";
}
