document.addEventListener("DOMContentLoaded", function() {
console.log("--- Tire Filter (Supports P/LT & Small Widths) Started ---");
if (window.location.pathname !== "/" && window.location.pathname !== "/index.php") return;
let tireData = {};
function scrapeTireData() {
const allLinks = document.querySelectorAll('a, span, .nav-link, .category-item');
let foundAny = false;
allLinks.forEach(item => {
let text = item.innerText.trim();
// تحديث المنطق: يبحث عن (اختياري P أو LT) ثم (رقمين أو ثلاثة) / (رقمين) / (رقمين)
// Regex: /(?:P|LT)?\s*(\d{2,3})\/(\d{2})\/(\d{2})/i
let match = text.match(/(?:P|LT)?\s*(\d{2,3})\/(\d{2})\/(\d{2})/i);
if (match) {
let w = match[1], h = match[2], r = match[3];
if (!tireData[w]) tireData[w] = {};
if (!tireData[w][h]) tireData[w][h] = [];
if (!tireData[w][h].includes(r)) tireData[w][h].push(r);
foundAny = true;
}
});
return foundAny;
}
function buildUI() {
if (document.getElementById('tire-injector')) return;
const target = document.querySelector('header') || document.body;
const html = `
🔍 ابحث عن المقاس المناسب لسيارتك
`;
const div = document.createElement("div");
div.innerHTML = html;
target.insertAdjacentElement('afterend', div);
}
function populateOptions() {
const wSel = document.getElementById('js-width');
if (!wSel || Object.keys(tireData).length === 0) return;
wSel.innerHTML = '';
// ترتيب الأرقام تصاعدياً بشكل صحيح
Object.keys(tireData).sort((a, b) => a - b).forEach(w => wSel.add(new Option(w, w)));
wSel.onchange = function() {
const hSel = document.getElementById('js-height');
const rSel = document.getElementById('js-rim');
hSel.disabled = false;
hSel.innerHTML = '';
rSel.innerHTML = '';
rSel.disabled = true;
Object.keys(tireData[this.value]).sort((a, b) => a - b).forEach(h => hSel.add(new Option(h, h)));
};
document.getElementById('js-height').onchange = function() {
const rSel = document.getElementById('js-rim');
rSel.disabled = false;
rSel.innerHTML = '';
tireData[document.getElementById('js-width').value][this.value].sort((a, b) => a - b).forEach(r => rSel.add(new Option(r, r)));
};
}
buildUI();
let checkCount = 0;
let dataCheck = setInterval(() => {
if (scrapeTireData()) {
populateOptions();
clearInterval(dataCheck);
}
if (checkCount > 30) clearInterval(dataCheck);
checkCount++;
}, 300);
});
function runTireSearch() {
var w = document.getElementById("js-width").value;
var h = document.getElementById("js-height").value;
var r = document.getElementById("js-rim").value;
if(w && h && r) window.location.href = "/search?q=" + w + "/" + h + "/" + r;
else alert("الرجاء اختيار جميع المقاسات");
}