(() => {
  if (document.getElementById('custowhey-extension-root')) return;

  const observation = globalThis.CustoWheyParser?.parseWheyProduct(document);
  if (!observation?.name) return;

  const host = document.createElement('div');
  host.id = 'custowhey-extension-root';
  const shadow = host.attachShadow({ mode: 'closed' });
  document.documentElement.append(host);

  const style = document.createElement('style');
  style.textContent = `
    :host{all:initial}*{box-sizing:border-box}.cw{--ink:#272331;--muted:#6f6876;--cream:#fffdf7;--gold:#f4c95d;font-family:Manrope,Inter,ui-sans-serif,system-ui,-apple-system,sans-serif;color:var(--ink)}
    button,a{font:inherit}.launcher{position:fixed;right:20px;bottom:20px;z-index:2147483646;display:flex;align-items:center;gap:9px;border:1px solid rgba(39,35,49,.14);border-radius:999px;background:var(--ink);color:#fff;padding:11px 16px 11px 11px;box-shadow:0 18px 48px rgba(39,35,49,.28);cursor:pointer;font-size:13px;font-weight:800;transition:.2s transform,.2s box-shadow}.launcher:hover{transform:translateY(-2px);box-shadow:0 22px 55px rgba(39,35,49,.34)}.mark{display:grid;place-items:center;width:27px;height:27px;border-radius:50%;background:var(--gold);color:var(--ink);font-size:15px}
    .panel{position:fixed;right:20px;bottom:76px;z-index:2147483647;width:min(382px,calc(100vw - 28px));max-height:min(650px,calc(100vh - 100px));overflow:auto;border:1px solid rgba(39,35,49,.13);border-radius:22px;background:var(--cream);box-shadow:0 28px 80px rgba(39,35,49,.28);transform-origin:bottom right;animation:show .18s ease-out}@keyframes show{from{opacity:0;transform:translateY(8px) scale(.98)}}
    .head{position:relative;padding:21px 48px 18px 20px;background:linear-gradient(135deg,#fff8df,#f7e9b8);border-bottom:1px solid rgba(39,35,49,.09)}.eyebrow{margin:0 0 6px;color:#8a5b00;font-size:10px;font-weight:900;letter-spacing:.15em;text-transform:uppercase}.title{margin:0;font-size:21px;line-height:1.15;letter-spacing:-.025em}.close{position:absolute;right:13px;top:13px;width:30px;height:30px;border:0;border-radius:50%;background:rgba(255,255,255,.62);color:var(--ink);cursor:pointer;font-size:18px}.observed{display:grid;grid-template-columns:1fr auto;gap:12px;padding:17px 20px;border-bottom:1px solid rgba(39,35,49,.08)}.product{margin:0;font-size:13px;font-weight:750;line-height:1.35}.sub{margin:5px 0 0;color:var(--muted);font-size:11px}.metric{text-align:right}.metric strong{display:block;font-size:18px;letter-spacing:-.03em}.metric span{color:var(--muted);font-size:10px}
    .body{padding:17px 20px 20px}.section-title{margin:0 0 12px;font-size:12px;font-weight:900}.cards{display:grid;gap:9px}.card{display:grid;grid-template-columns:50px 1fr auto;gap:11px;align-items:center;padding:10px;border:1px solid rgba(39,35,49,.09);border-radius:14px;background:#fff;color:var(--ink);text-decoration:none;transition:.18s border-color,.18s transform}.card:hover{transform:translateY(-1px);border-color:#d9a832}.pic{width:50px;height:50px;object-fit:contain;border-radius:9px;background:#fff}.card-name{margin:0;font-size:11px;font-weight:800;line-height:1.35}.card-store{margin:4px 0 0;color:var(--muted);font-size:10px}.card-price{text-align:right}.card-price strong{display:block;font-size:13px}.card-price span{font-size:9px;color:#8a5b00}.state{padding:14px;border-radius:13px;background:#fff7df;color:#665624;font-size:12px;line-height:1.5}.retry{margin-top:10px;border:0;border-radius:10px;background:var(--ink);color:#fff;padding:9px 12px;cursor:pointer;font-weight:800}.foot{margin:13px 2px 0;color:#89828d;font-size:9px;line-height:1.45}.contribution{padding:14px 20px 17px;border-top:1px solid rgba(39,35,49,.08);background:#fff}.consent{display:flex;gap:10px;align-items:flex-start;cursor:pointer}.consent input{width:16px;height:16px;margin:1px 0 0;accent-color:#272331}.consent strong{display:block;font-size:11px}.consent span{display:block;margin-top:3px;color:var(--muted);font-size:9px;line-height:1.4}.contribution-status{margin:8px 0 0 26px;color:#8a5b00;font-size:9px;font-weight:700}
    @media(max-width:520px){.launcher{right:12px;bottom:12px}.panel{right:14px;bottom:68px}.launcher-label{display:none}.launcher{padding:10px}}
  `;
  shadow.append(style);

  const container = document.createElement('div');
  container.className = 'cw';
  const launcher = document.createElement('button');
  launcher.className = 'launcher';
  launcher.type = 'button';
  launcher.setAttribute('aria-label', 'Abrir comparação do CustoWhey');
  launcher.innerHTML = '<span class="mark">↘</span><span class="launcher-label">Comparar no CustoWhey</span>';
  container.append(launcher);
  shadow.append(container);

  let panel = null;
  let comparisons = null;
  let loading = false;
  let contributionEnabled = false;
  let contributionStatus = '';
  let contributionSent = false;

  const money = (value) => Number(value).toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' });
  const safe = (value) => String(value ?? '').replace(/[&<>"']/g, (char) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[char]);

  async function installationId() {
    const stored = await chrome.storage.local.get('cwInstallationId');
    if (stored.cwInstallationId) return stored.cwInstallationId;
    const id = crypto.randomUUID();
    await chrome.storage.local.set({ cwInstallationId: id });
    return id;
  }

  function renderContribution() {
    if (!panel) return;
    const target = panel.querySelector('.contribution');
    target.innerHTML = `<label class="consent"><input type="checkbox" ${contributionEnabled ? 'checked' : ''}><span><strong>Ajudar a atualizar preços</strong><span>Se você aceitar, enviaremos nome do produto, marca, peso, preço, disponibilidade e endereço público sem parâmetros para melhorar as comparações. Nunca enviamos cookies, login, carrinho, checkout ou histórico.</span></span></label>${contributionStatus ? `<p class="contribution-status">${safe(contributionStatus)}</p>` : ''}`;
    target.querySelector('input').addEventListener('change', async (event) => {
      contributionEnabled = event.currentTarget.checked;
      contributionStatus = contributionEnabled ? 'Preferência salva. Enviando esta observação…' : 'Contribuição desativada.';
      await chrome.storage.local.set({ cwPriceContribution: contributionEnabled });
      renderContribution();
      if (contributionEnabled) submitObservation();
    });
  }

  async function submitObservation() {
    if (!contributionEnabled || contributionSent || !observation.complete) return;
    contributionSent = true;
    const id = await installationId();
    chrome.runtime.sendMessage({
      type: 'CUSTOWHEY_OBSERVE',
      observation: {
        installationId: id,
        consent: true,
        pageUrl: location.href,
        productName: observation.name,
        brand: observation.brand,
        gtin: observation.gtin,
        packageWeightGrams: observation.packageWeightGrams,
        productType: observation.productType,
        effectivePrice: observation.price,
        pixPrice: observation.pixPrice,
        cardPrice: observation.cardPrice,
        currency: observation.currency,
        available: true,
        observedAt: new Date().toISOString(),
        extensionVersion: chrome.runtime.getManifest().version,
      },
    }, (response) => {
      if (chrome.runtime.lastError || !response?.ok) {
        contributionSent = false;
        contributionStatus = response?.error || 'Não foi possível contribuir agora.';
      } else {
        contributionStatus = response.duplicate ? 'Preço já observado recentemente.' : 'Preço enviado para validação. Obrigado!';
      }
      renderContribution();
    });
  }

  function renderBody() {
    if (!panel) return;
    const body = panel.querySelector('.body');
    if (!observation.complete) {
      body.innerHTML = '<div class="state">Ainda não conseguimos identificar com segurança o preço e o peso desta opção. Selecione um sabor ou tamanho e tente novamente.</div>';
      return;
    }
    if (loading) {
      body.innerHTML = '<div class="state">Buscando as melhores alternativas no CustoWhey…</div>';
      return;
    }
    if (comparisons?.error) {
      body.innerHTML = `<div class="state">${safe(comparisons.error)}<br><button class="retry" type="button">Tentar novamente</button></div>`;
      body.querySelector('.retry').addEventListener('click', load);
      return;
    }
    const items = comparisons?.items ?? [];
    if (!items.length) {
      body.innerHTML = '<div class="state">Ainda não encontramos este mesmo produto em outras lojas.</div>';
      return;
    }
    body.innerHTML = `<p class="section-title">O mesmo whey em outras lojas</p><div class="cards">${items.map((item) => `
      <a class="card" href="${safe(item.productUrl)}" target="_blank" rel="noopener noreferrer">
        <img class="pic" src="${safe(item.imageUrl)}" alt="">
        <div><p class="card-name">${safe(item.name)}</p><p class="card-store">${safe(item.store)} · ${safe(item.packageWeightGrams)}g</p></div>
        <div class="card-price"><strong>${money(item.price)}</strong><span>${item.pricePer100g != null ? `${money(item.pricePer100g)}/100g` : 'ver oferta'}</span></div>
      </a>`).join('')}</div><p class="foot">Ao escolher uma oferta, você vai direto para a loja. Alguns links são de afiliados e podem gerar comissão ao CustoWhey sem custo extra. Os preços podem mudar.</p>`;
  }

  function load() {
    if (!observation.complete || loading) return;
    loading = true;
    renderBody();
    chrome.runtime.sendMessage({
      type: 'CUSTOWHEY_COMPARE',
      identity: {
        query: observation.name,
        brand: observation.brand,
        gtin: observation.gtin,
        packageWeightGrams: observation.packageWeightGrams,
        productType: observation.productType,
      },
    }, (response) => {
      loading = false;
      if (chrome.runtime.lastError || !response?.ok) {
        comparisons = { error: response?.error || 'Não foi possível consultar o CustoWhey agora.' };
      } else {
        comparisons = { items: response.comparisons };
      }
      renderBody();
    });
  }

  function open() {
    if (panel) return;
    panel = document.createElement('section');
    panel.className = 'panel';
    panel.setAttribute('role', 'dialog');
    panel.setAttribute('aria-label', 'Comparação CustoWhey');
    panel.innerHTML = `
      <header class="head"><p class="eyebrow">Comparador especializado</p><h2 class="title">Este whey vale o preço?</h2><button class="close" type="button" aria-label="Fechar">×</button></header>
      <div class="observed"><div><p class="product">${safe(observation.name)}</p><p class="sub">${observation.packageWeightGrams ? `${observation.packageWeightGrams}g` : 'Peso não identificado'} · preço observado ${observation.price ? money(observation.price) : 'indisponível'}</p></div>
      <div class="metric">${observation.pricePer100g ? `<strong>${money(observation.pricePer100g)}</strong><span>por 100g</span>` : ''}</div></div>
      <div class="body"></div><div class="contribution"></div>`;
    container.append(panel);
    panel.querySelector('.close').addEventListener('click', close);
    renderBody();
    renderContribution();
    if (!comparisons) load();
  }

  function close() {
    panel?.remove();
    panel = null;
  }

  launcher.addEventListener('click', () => panel ? close() : open());
  chrome.storage.local.get('cwPriceContribution').then((stored) => {
    contributionEnabled = stored.cwPriceContribution === true;
    if (contributionEnabled) submitObservation();
  });
})();
