// product-detail.jsx — Página de detalhe do produto com gráfico de histórico

const { useState: useStatePD, useMemo: useMemoPD } = React;

function ProductDetail({ product, onBack, onProduct }) {
  const [period, setPeriod] = useStatePD("180");
  const [showAlert, setShowAlert] = useStatePD(false);
  const [target, setTarget] = useStatePD(Math.round(product.lowestEver * 0.97));

  // Gera ofertas multi-loja a partir do título do produto
  const multiOffers = useMemoPD(() => {
    const t = encodeURIComponent(product.title);
    const td = encodeURIComponent(product.title.replace(/ /g, "-"));
    const stores = [
      { store: "amz",  storeName: "Amazon",       price: product.current,                 pix: Math.round(product.current * 0.95), ship: "Prime grátis",    link: `https://www.amazon.com.br/s?k=${t}&tag=yetishopping-20` },
      { store: "ml",   storeName: "Mercado Livre", price: Math.round(product.current*1.03), pix: Math.round(product.current*1.03*0.95), ship: "Ver condições", link: `https://lista.mercadolivre.com.br/${td}` },
      { store: "kbm",  storeName: "Kabum",         price: Math.round(product.current*0.98), pix: Math.round(product.current*0.98*0.92), ship: "Frete grátis",  link: `https://www.kabum.com.br/busca/${td}` },
      { store: "mglu", storeName: "Magalu",         price: Math.round(product.current*1.01), pix: Math.round(product.current*1.01*0.95), ship: "Frete grátis", link: `https://www.magazineluiza.com.br/busca/${td}/` },
      { store: "shp",  storeName: "Shopee",         price: Math.round(product.current*0.96), pix: Math.round(product.current*0.96*0.95), ship: "Grátis",        link: `https://shopee.com.br/search?keyword=${t}` },
    ].sort((a, b) => a.price - b.price);
    return stores;
  }, [product]);
  const sortedOffers = multiOffers;
  const cheapest = sortedOffers[0];
  const savedFromBase = product.base - product.current;
  const savedPct = Math.round((savedFromBase / product.base) * 100);
  const isAtLow = product.current <= product.lowestEver * 1.03;
  // Produtos relacionados: buscados em tempo real pela categoria via YetiAPI
  const [relatedProducts, setRelatedProducts] = React.useState([]);
  React.useEffect(() => {
    const cat = CATEGORIES?.find(c => c.id === product.cat);
    const kw  = cat?.keyword || product.category || "oferta";
    if (window.YetiAPI) {
      YetiAPI.search(kw, { size: 8 })
        .then(results => setRelatedProducts(results.filter(p => p.id !== product.id).slice(0, 4)))
        .catch(() => setRelatedProducts([]));
    }
  }, [product.id]);

  return (
    <div style={{ background: "#FAF6EC", minHeight: "100vh" }}>
      <div style={{ maxWidth: 1280, margin: "0 auto", padding: "20px 32px" }}>
        {/* Breadcrumb */}
        <div style={{ display: "flex", alignItems: "center", gap: 6, fontSize: 12.5, color: "#7E7458", marginBottom: 18 }}>
          <button onClick={onBack} style={{ background: "none", border: 0, color: "#7E7458", cursor: "pointer", padding: 0, font: "inherit" }}>Home</button>
          <span>›</span>
          <span>{product.category}</span>
          <span>›</span>
          <span style={{ color: "#0E2A47", fontWeight: 600 }}>{product.title}</span>
        </div>

        {/* Top section: image + main info */}
        <div style={{ display: "grid", gridTemplateColumns: "440px 1fr", gap: 32, marginBottom: 32 }}>
          {/* Image gallery */}
          <div>
            <div style={{ background: "white", borderRadius: 24, border: "1.5px solid #E8E1CC", padding: 20, position: "relative" }}>
              <ProductImage product={product} size={300} rounded={16}/>
              {savedPct >= 10 && (
                <div style={{
                  position: "absolute", top: 30, left: 30, background: "#FF6B5C", color: "white",
                  padding: "6px 14px", borderRadius: 999, fontSize: 14, fontWeight: 800,
                  boxShadow: "0 8px 20px rgba(255,107,92,.35)",
                }}>−{savedPct}%</div>
              )}
            </div>
            <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 8, marginTop: 10 }}>
              {[0, 1, 2, 3].map(i => (
                <div key={i} style={{
                  background: "white", borderRadius: 12, border: i === 0 ? "2px solid #0E2A47" : "1.5px solid #E8E1CC",
                  aspectRatio: "1/1", display: "flex", alignItems: "center", justifyContent: "center",
                  cursor: "pointer", fontSize: 24, opacity: i === 0 ? 1 : .5,
                }}>
                  <ProductImage product={product} size={70} rounded={10}/>
                </div>
              ))}
            </div>
          </div>

          {/* Info */}
          <div>
            <div style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 12, color: "#7E7458", fontWeight: 600, letterSpacing: ".08em", textTransform: "uppercase", marginBottom: 8 }}>
              <span>{product.brand}</span><span>·</span><span>{product.category}</span>
            </div>
            <h1 style={{ fontFamily: "var(--font-display)", fontWeight: 800, fontSize: 36, color: "#0E2A47", margin: 0, letterSpacing: "-.02em", lineHeight: 1.1, textWrap: "balance" }}>
              {product.title}
            </h1>

            <div style={{ display: "flex", alignItems: "center", gap: 14, marginTop: 14, marginBottom: 24 }}>
              {product.rating && (
                <div style={{ display: "flex", alignItems: "center", gap: 4 }}>
                  <span style={{ color: "#FFC72C", fontSize: 17 }}>★★★★★</span>
                  <span style={{ fontSize: 14, fontWeight: 700, color: "#0E2A47" }}>{product.rating}</span>
                  {product.reviews && <span style={{ fontSize: 13, color: "#7E7458" }}>({product.reviews.toLocaleString("pt-BR")} avaliações)</span>}
                </div>
              )}
              {product.rating && <span style={{ color: "#E8E1CC" }}>|</span>}
              <span style={{ fontSize: 13, color: "#7E7458" }}>Comparando {product.offers?.length ?? 1} {(product.offers?.length ?? 1) === 1 ? "loja" : "lojas"}</span>
            </div>

            {/* Big price panel */}
            <div style={{
              background: "white", borderRadius: 20, border: "2px solid #0E2A47", padding: 24,
              boxShadow: "8px 8px 0 #FFC72C",
            }}>
              <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", gap: 20, flexWrap: "wrap" }}>
                <div>
                  <div style={{ fontSize: 12.5, color: "#7E7458", fontWeight: 600, marginBottom: 4, letterSpacing: ".04em", textTransform: "uppercase" }}>Melhor preço hoje · <StoreBadge store={cheapest.store} size="sm"/></div>
                  <div style={{ display: "flex", alignItems: "baseline", gap: 12, marginTop: 6 }}>
                    <div style={{ fontFamily: "var(--font-display)", fontWeight: 800, fontSize: 52, color: "#0E2A47", letterSpacing: "-.025em", fontVariantNumeric: "tabular-nums", lineHeight: 1 }}>
                      {fmtBRL(cheapest.price)}
                    </div>
                    <div style={{ fontSize: 18, color: "#7E7458", textDecoration: "line-through", fontVariantNumeric: "tabular-nums" }}>
                      {fmtBRL(product.base)}
                    </div>
                  </div>
                  <div style={{ display: "flex", gap: 14, marginTop: 10, alignItems: "center", flexWrap: "wrap" }}>
                    <span style={{ fontSize: 13.5, color: "#1FB3A6", fontWeight: 700 }}>
                      {fmtBRL(cheapest.pix)} no Pix
                    </span>
                    <span style={{ fontSize: 12.5, color: "#7E7458" }}>
                      ou 12x de {fmtBRL2(cheapest.price / 12)}
                    </span>
                  </div>
                </div>

                <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                  {/* Multi-lojas: busca o produto em cada loja */}
                  {[
                    { name: "Amazon",       color: "#FF9900", text: "#131A22", url: `https://www.amazon.com.br/s?k=${encodeURIComponent(product.title)}&tag=yetishopping-20` },
                    { name: "Mercado Livre",color: "#FFE600", text: "#2D3277", url: `https://lista.mercadolivre.com.br/${encodeURIComponent(product.title.replace(/ /g,"-"))}` },
                    { name: "Kabum",        color: "#FF6500", text: "#FFFFFF", url: `https://www.kabum.com.br/busca/${encodeURIComponent(product.title.replace(/ /g,"-"))}` },
                    { name: "Magalu",       color: "#0086FF", text: "#FFFFFF", url: `https://www.magazineluiza.com.br/busca/${encodeURIComponent(product.title.replace(/ /g,"-"))}/` },
                    { name: "Shopee",       color: "#EE4D2D", text: "#FFFFFF", url: `https://shopee.com.br/search?keyword=${encodeURIComponent(product.title)}` },
                  ].map((s, i) => (
                    <a key={s.name} href={s.url} target="_blank" rel="noopener noreferrer" style={{
                      background: s.color, color: s.text, textDecoration: "none",
                      padding: i === 0 ? "14px 18px" : "10px 18px",
                      borderRadius: 10, fontWeight: 800,
                      fontSize: i === 0 ? 14 : 13,
                      display: "flex", alignItems: "center", justifyContent: "space-between",
                      border: "1.5px solid rgba(0,0,0,.12)",
                    }}>
                      <span>Buscar no {s.name}</span>
                      <span>→</span>
                    </a>
                  ))}
                </div>
              </div>

              {/* Verdict */}
              <div style={{
                marginTop: 18, padding: "12px 14px", borderRadius: 12,
                background: isAtLow ? "#E8F8F5" : "#FFF8E6",
                border: `1.5px solid ${isAtLow ? "#1FB3A6" : "#FFC72C"}`,
                display: "flex", alignItems: "center", gap: 12,
              }}>
                <div style={{ fontSize: 24 }}>{isAtLow ? "🤙" : "🤔"}</div>
                <div>
                  <div style={{ fontSize: 13.5, fontWeight: 800, color: "#0E2A47", marginBottom: 2 }}>
                    {isAtLow ? "Veredito do Yeti: COMPRA!" : "Veredito do Yeti: Pode esperar"}
                  </div>
                  <div style={{ fontSize: 12.5, color: "#3A4A5E", textWrap: "pretty" }}>
                    {isAtLow
                      ? `Tá no menor preço dos últimos ${period === "all" ? "180" : period} dias. Bora!`
                      : `Já esteve a ${fmtBRL(product.lowestEver)} (${new Intl.DateTimeFormat("pt-BR", { day: "2-digit", month: "short" }).format(product.lowestDate)}). Vale esperar uma queda.`}
                  </div>
                </div>
              </div>

              {/* Alert form expanding */}
              {showAlert && (
                <div style={{ marginTop: 16, padding: 16, borderRadius: 12, background: "#FAF6EC", border: "1.5px dashed #E8E1CC" }}>
                  <div style={{ fontSize: 13, fontWeight: 700, color: "#0E2A47", marginBottom: 10 }}>Me avise quando o preço cair para:</div>
                  <div style={{ display: "flex", gap: 10, alignItems: "center" }}>
                    <div style={{ flex: 1, position: "relative" }}>
                      <input type="number" value={target} onChange={e => setTarget(parseInt(e.target.value || "0", 10))}
                        style={{ width: "100%", border: "1.5px solid #0E2A47", borderRadius: 10, padding: "10px 14px 10px 36px", fontSize: 16, fontWeight: 700, fontFamily: "inherit", color: "#0E2A47", outline: "none", fontVariantNumeric: "tabular-nums" }}/>
                      <span style={{ position: "absolute", left: 12, top: "50%", transform: "translateY(-50%)", fontSize: 14, color: "#7E7458", fontWeight: 600 }}>R$</span>
                    </div>
                    <input type="range" min={Math.round(product.lowestEver * 0.7)} max={product.current} value={target} onChange={e => setTarget(parseInt(e.target.value, 10))} style={{ flex: 2 }}/>
                  </div>
                  <div style={{ display: "flex", justifyContent: "space-between", marginTop: 6, fontSize: 11, color: "#7E7458" }}>
                    <span>Menor histórico: {fmtBRL(product.lowestEver)}</span>
                    <span>Atual: {fmtBRL(product.current)}</span>
                  </div>
                  <button style={{
                    marginTop: 12, width: "100%", background: "#0E2A47", color: "white", border: 0,
                    borderRadius: 10, padding: "11px", fontWeight: 700, fontSize: 13.5, cursor: "pointer", font: "inherit",
                  }}>Ativar alerta — grátis</button>
                </div>
              )}
            </div>
          </div>
        </div>

        {/* Price chart section */}
        <section style={{
          background: "white", borderRadius: 24, border: "1.5px solid #E8E1CC",
          padding: 28, marginBottom: 28,
        }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 18, flexWrap: "wrap", gap: 16 }}>
            <div>
              <div style={{ fontSize: 12, fontWeight: 700, color: "#FFC72C", textTransform: "uppercase", letterSpacing: ".1em", marginBottom: 6, WebkitTextStroke: ".4px #0E2A47" }}>Histórico de preço</div>
              <h2 style={{ fontFamily: "var(--font-display)", fontWeight: 800, fontSize: 26, color: "#0E2A47", margin: 0, letterSpacing: "-.015em" }}>
                Evolução em {period === "all" ? "180 dias" : `${period} dias`}
              </h2>
            </div>
            <div style={{ display: "flex", gap: 4, background: "#FAF6EC", padding: 4, borderRadius: 12 }}>
              {[
                { v: "30", l: "30d" }, { v: "90", l: "90d" }, { v: "180", l: "180d" }, { v: "all", l: "Tudo" },
              ].map(opt => (
                <button key={opt.v} onClick={() => setPeriod(opt.v)} style={{
                  background: period === opt.v ? "#0E2A47" : "transparent",
                  color: period === opt.v ? "white" : "#3A4A5E",
                  border: 0, borderRadius: 8, padding: "8px 14px", fontSize: 13, fontWeight: 600,
                  cursor: "pointer", font: "inherit",
                }}>{opt.l}</button>
              ))}
            </div>
          </div>

          <PriceChart history={product.history} currentPrice={product.current} lowestEver={product.lowestEver} highestEver={product.highestEver} period={period}/>

          <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 16, marginTop: 24, paddingTop: 22, borderTop: "1px solid #E8E1CC" }}>
            {[
              { label: "Preço atual",     value: fmtBRL(product.current),    color: "#FFC72C", sub: "agora mesmo" },
              { label: "Menor histórico", value: fmtBRL(product.lowestEver), color: "#1FB3A6", sub: new Intl.DateTimeFormat("pt-BR", { day: "2-digit", month: "short" }).format(product.lowestDate) },
              { label: "Maior histórico", value: fmtBRL(product.highestEver), color: "#FF6B5C", sub: new Intl.DateTimeFormat("pt-BR", { day: "2-digit", month: "short" }).format(product.highestDate) },
              { label: "Preço médio",     value: fmtBRL(Math.round(product.history.reduce((a, b) => a + b.p, 0) / product.history.length)), color: "#3A4A5E", sub: "últimos 180d" },
            ].map((s, i) => (
              <div key={i} style={{ display: "flex", flexDirection: "column", gap: 4 }}>
                <div style={{ display: "flex", alignItems: "center", gap: 6, fontSize: 11.5, color: "#7E7458", fontWeight: 600 }}>
                  <span style={{ width: 7, height: 7, borderRadius: "50%", background: s.color, display: "inline-block" }}/>
                  {s.label}
                </div>
                <div style={{ fontFamily: "var(--font-display)", fontWeight: 800, fontSize: 24, color: "#0E2A47", fontVariantNumeric: "tabular-nums", letterSpacing: "-.015em" }}>{s.value}</div>
                <div style={{ fontSize: 11.5, color: "#7E7458" }}>{s.sub}</div>
              </div>
            ))}
          </div>
        </section>

        {/* Offers comparison table */}
        <section style={{
          background: "white", borderRadius: 24, border: "1.5px solid #E8E1CC",
          padding: 28, marginBottom: 28,
        }}>
          <div style={{ marginBottom: 18 }}>
            <div style={{ fontSize: 12, fontWeight: 700, color: "#FFC72C", textTransform: "uppercase", letterSpacing: ".1em", marginBottom: 6, WebkitTextStroke: ".4px #0E2A47" }}>Comparação</div>
            <h2 style={{ fontFamily: "var(--font-display)", fontWeight: 800, fontSize: 26, color: "#0E2A47", margin: 0, letterSpacing: "-.015em" }}>
              Mesmo produto em {product.offers.length} lojas
            </h2>
          </div>

          <div style={{ overflow: "hidden", borderRadius: 14, border: "1px solid #E8E1CC" }}>
            <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 14 }}>
              <thead>
                <tr style={{ background: "#FAF6EC", fontSize: 11.5, color: "#7E7458", textTransform: "uppercase", letterSpacing: ".06em", fontWeight: 700 }}>
                  <th style={{ textAlign: "left", padding: "12px 16px" }}>Loja</th>
                  <th style={{ textAlign: "right", padding: "12px 16px" }}>Preço</th>
                  <th style={{ textAlign: "right", padding: "12px 16px" }}>Pix</th>
                  <th style={{ textAlign: "right", padding: "12px 16px" }}>Parcelado</th>
                  <th style={{ textAlign: "left", padding: "12px 16px" }}>Frete</th>
                  <th style={{ textAlign: "right", padding: "12px 16px" }}>Ação</th>
                </tr>
              </thead>
              <tbody>
                {sortedOffers.map((o, i) => (
                  <tr key={o.store} style={{ borderTop: "1px solid #E8E1CC", background: i === 0 ? "rgba(255,199,44,.06)" : "white" }}>
                    <td style={{ padding: "16px" }}>
                      <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                        <StoreBadge store={o.store} size="md"/>
                        {i === 0 && <span style={{ fontSize: 11, color: "#1FB3A6", fontWeight: 800, letterSpacing: ".04em" }}>● MELHOR PREÇO</span>}
                      </div>
                    </td>
                    <td style={{ padding: "16px", textAlign: "right", fontWeight: 700, color: "#0E2A47", fontVariantNumeric: "tabular-nums", fontSize: 16 }}>
                      {fmtBRL(o.price)}
                    </td>
                    <td style={{ padding: "16px", textAlign: "right", color: "#1FB3A6", fontWeight: 700, fontVariantNumeric: "tabular-nums" }}>
                      {fmtBRL(o.pix)}
                    </td>
                    <td style={{ padding: "16px", textAlign: "right", color: "#3A4A5E", fontVariantNumeric: "tabular-nums" }}>
                      12× {fmtBRL2(o.price / 12)}
                    </td>
                    <td style={{ padding: "16px", color: "#3A4A5E" }}>{o.ship}</td>
                    <td style={{ padding: "16px", textAlign: "right" }}>
                      <a href={o.link} target="_blank" rel="noopener noreferrer" style={{
                        background: i === 0 ? "#FFC72C" : "white", color: "#0E2A47",
                        border: "1.5px solid #0E2A47", textDecoration: "none",
                        padding: "8px 14px", borderRadius: 10, fontSize: 13, fontWeight: 700,
                        display: "inline-flex", alignItems: "center", gap: 6,
                      }}>Buscar →</a>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </section>

        {/* Specs + related side by side */}
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1.4fr", gap: 28, marginBottom: 48 }}>
          <section style={{
            background: "white", borderRadius: 24, border: "1.5px solid #E8E1CC", padding: 28,
          }}>
            <div style={{ fontSize: 12, fontWeight: 700, color: "#FFC72C", textTransform: "uppercase", letterSpacing: ".1em", marginBottom: 6, WebkitTextStroke: ".4px #0E2A47" }}>Sobre o produto</div>
            <h2 style={{ fontFamily: "var(--font-display)", fontWeight: 800, fontSize: 22, color: "#0E2A47", margin: "0 0 16px", letterSpacing: "-.015em" }}>Informações</h2>
            <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "flex", flexDirection: "column", gap: 10 }}>
              {(product.spec || [
                `Categoria: ${product.category || "Geral"}`,
                `Loja: ${product.storeName || product.brand || "Parceiro"}`,
                `Menor histórico nos últimos 180 dias: ${fmtBRL(product.lowestEver)}`,
                `Maior histórico: ${fmtBRL(product.highestEver)}`,
                "Preços atualizados em tempo real",
              ]).map((s, i) => (
                <li key={i} style={{ display: "flex", gap: 10, fontSize: 13.5, color: "#3A4A5E" }}>
                  <span style={{ color: "#1FB3A6", fontWeight: 800 }}>✓</span>
                  <span>{s}</span>
                </li>
              ))}
            </ul>
          </section>

          <section>
            <div style={{ marginBottom: 16 }}>
              <div style={{ fontSize: 12, fontWeight: 700, color: "#FFC72C", textTransform: "uppercase", letterSpacing: ".1em", marginBottom: 6, WebkitTextStroke: ".4px #0E2A47" }}>Relacionados</div>
              <h2 style={{ fontFamily: "var(--font-display)", fontWeight: 800, fontSize: 22, color: "#0E2A47", margin: 0, letterSpacing: "-.015em" }}>O Yeti também vigia</h2>
            </div>
            <div style={{ display: "grid", gridTemplateColumns: "repeat(2, 1fr)", gap: 12 }}>
              {relatedProducts.slice(0, 4).map(p => (
                <ProductCard key={p.id} product={p} onClick={onProduct}/>
              ))}
            </div>
          </section>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { ProductDetail });
