(function() {
  'use strict';
  if (window.__QYDZ_OZON_VISUAL_CATEGORY__) return;
  window.__QYDZ_OZON_VISUAL_CATEGORY__ = true;

  function wait(ms) {
    return new Promise(function(resolve) { setTimeout(resolve, ms); });
  }

  function clean(value, max) {
    return String(value == null ? '' : value).replace(/\s+/g, ' ').trim().slice(0, max || 500);
  }

  function unique(values) {
    var seen = {};
    return (Array.isArray(values) ? values : []).map(clean).filter(function(value) {
      if (!value || seen[value]) return false;
      seen[value] = true;
      return true;
    });
  }

  function setNativeValue(input, value) {
    var setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value');
    if (setter && setter.set) setter.set.call(input, value);
    else input.value = value;
    input.dispatchEvent(new Event('input', { bubbles: true }));
    input.dispatchEvent(new Event('change', { bubbles: true }));
  }

  function waitFor(getter, timeout) {
    var started = Date.now();
    return new Promise(function(resolve, reject) {
      (function poll() {
        var result = null;
        try { result = getter(); } catch (_) {}
        if (result) return resolve(result);
        if (Date.now() - started > (timeout || 15000)) return reject(new Error('Ozon以图搜索页面元素未出现'));
        setTimeout(poll, 300);
      }());
    });
  }

  function searchInput() {
    return document.querySelector('input[type="search"], input[placeholder*="Искать"], input[placeholder*="искать"], input[aria-label*="Поиск"]');
  }

  function clickCamera() {
    var input = searchInput();
    var root = input && (input.closest('form') || input.parentElement && input.parentElement.parentElement || input.parentElement);
    var buttons = root ? Array.from(root.querySelectorAll('button,[role="button"]')) : Array.from(document.querySelectorAll('button,[role="button"]'));
    var labelled = buttons.find(function(button) {
      var label = clean((button.getAttribute('aria-label') || '') + ' ' + (button.getAttribute('title') || '') + ' ' + button.textContent, 200).toLowerCase();
      return /фото|изображ|картин|камер|image|photo/.test(label);
    });
    var button = labelled || (buttons.length > 1 ? buttons[buttons.length - 2] : null);
    if (!button) throw new Error('未找到 Ozon 搜索框相机按钮');
    button.click();
  }

  function visualUrlInput() {
    var inputs = Array.from(document.querySelectorAll('input'));
    return inputs.find(function(input) {
      var text = clean((input.placeholder || '') + ' ' + (input.getAttribute('aria-label') || ''), 300).toLowerCase();
      return /url|ссылк|изображ|фото|image/.test(text) && input !== searchInput();
    });
  }

  function submitVisualUrl(input, url) {
    setNativeValue(input, url);
    input.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', code: 'Enter', bubbles: true }));
    input.dispatchEvent(new KeyboardEvent('keyup', { key: 'Enter', code: 'Enter', bubbles: true }));
  }

  function productLinks() {
    return unique(Array.from(document.querySelectorAll('a[href]')).map(function(anchor) {
      var href = anchor.href || '';
      return /\/product\//i.test(href) ? href.split('?')[0] : '';
    })).slice(0, 8);
  }

  function productCards() {
    var seen = {};
    return Array.from(document.querySelectorAll('a[href*="/product/"]')).map(function(anchor) {
      var url = (anchor.href || '').split('?')[0];
      if (!url || seen[url]) return null;
      seen[url] = true;
      var card = anchor.closest('[data-widget],article,li') || anchor.parentElement;
      var titleNode = card && card.querySelector('span[title],h3,h2');
      return {
        url: url,
        title: clean((titleNode && (titleNode.getAttribute('title') || titleNode.textContent)) || anchor.getAttribute('title') || anchor.textContent, 300),
        category_path: [],
        category_name: ''
      };
    }).filter(Boolean).slice(0, 8);
  }

  function parseJsonLd(doc) {
    var result = [];
    Array.from(doc.querySelectorAll('script[type="application/ld+json"]')).forEach(function(script) {
      try {
        var value = JSON.parse(script.textContent || '');
        var rows = Array.isArray(value) ? value : [value];
        rows.forEach(function(row) {
          if (row && typeof row === 'object') result.push(row);
        });
      } catch (_) {}
    });
    return result;
  }

  function extractProductEvidence(url, html) {
    var doc = new DOMParser().parseFromString(html, 'text/html');
    var jsonRows = parseJsonLd(doc);
    var product = jsonRows.find(function(row) { return row['@type'] === 'Product'; }) || {};
    var crumbs = Array.from(doc.querySelectorAll('[class*="breadcrumb" i] a, nav a[href*="/category/"], [data-widget*="breadcrumb" i] a'))
      .map(function(node) { return clean(node.textContent, 160); });
    var categoryName = clean(crumbs[crumbs.length - 1] || '', 200);
    if (!categoryName) {
      var match = html.match(/(?:categoryName|category_name|categoryTitle)["']?\s*[:=]\s*["']([^"']{2,120})/i);
      categoryName = clean(match && match[1], 200);
    }
    return {
      url: url,
      title: clean(product.name || doc.querySelector('meta[property="og:title"]') && doc.querySelector('meta[property="og:title"]').content || doc.title, 300),
      category_path: unique(crumbs).slice(-8),
      category_name: categoryName
    };
  }

  async function collectEvidence() {
    var cards = productCards();
    var links = cards.map(function(card) { return card.url; });
    var evidence = [];
    for (var i = 0; i < links.length; i += 1) {
      try {
        var response = await fetch(links[i], { credentials: 'include' });
        if (!response.ok) throw new Error('HTTP ' + response.status);
        var parsed = extractProductEvidence(links[i], await response.text());
        evidence.push({
          url: parsed.url,
          title: parsed.title || cards[i].title,
          category_path: parsed.category_path,
          category_name: parsed.category_name
        });
      } catch (_) {
        if (cards[i] && cards[i].title) evidence.push(cards[i]);
      }
      if (evidence.length >= 6) break;
    }
    return evidence;
  }

  async function run(task) {
    if (window.__QYDZ_OZON_VISUAL_RUNNING__) return;
    window.__QYDZ_OZON_VISUAL_RUNNING__ = true;
    try {
      if (String(task.stage || 'submit') === 'submit') {
        clickCamera();
        var input = await waitFor(visualUrlInput, 12000);
        if (!task.image_url) throw new Error('没有可用于 Ozon 以图搜索的主图 URL');
        submitVisualUrl(input, task.image_url);
        chrome.runtime.sendMessage({ action: 'ozonVisualCategoryNavigationStarted', task_id: task.task_id });
        await wait(1500);
      }
      await waitFor(function() { return productLinks().length ? true : null; }, 30000);
      var evidence = await collectEvidence();
      if (!evidence.length) throw new Error('Ozon以图搜索没有返回同类商品');
      chrome.runtime.sendMessage({ action: 'ozonVisualCategoryResults', task_id: task.task_id, evidence: evidence });
    } catch (error) {
      chrome.runtime.sendMessage({ action: 'ozonVisualCategoryResults', task_id: task.task_id, success: false, message: error.message || 'Ozon以图搜索失败' });
    } finally {
      window.__QYDZ_OZON_VISUAL_RUNNING__ = false;
    }
  }

  chrome.runtime.onMessage.addListener(function(message) {
    if (message && message.action === 'runOzonVisualCategorySearch') run(message);
  });
}());
