/* ============================================================
   AfricaMart — Product Listing page
   ============================================================ */
function ProductPage({ nav, currency, params, showToast }) {
  const p = AM.productBySlug[params.slug] || AM.PRODUCTS[0];
  const s = AM.supplierById[p.supplier];
  const cat = AM.catById[p.cat];
  const c = AM.countryByCode[s.country];
  const [activeImg, setActiveImg] = useState(0);
  const galleryIcons = [cat.icon, "box", "ruler", "layers"];
  const related = AM.PRODUCTS.filter(x => x.supplier === p.supplier && x.id !== p.id).slice(0, 4);

  return (
    <div className="route-anim wrap" style={{ padding: "24px 24px 64px" }}>
      <Breadcrumb trail={[["Home", () => nav("home")], ["Browse", () => nav("browse")], [cat.name, () => nav("browse", { cat: cat.id })], [p.name]]} />

      <div className="product-layout" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 36, marginTop: 20, alignItems: "start" }}>
        {/* Gallery */}
        <div style={{ position: "sticky", top: 84 }}>
          <div className="card" style={{ overflow: "hidden", padding: 0 }}>
            <ProductPh product={p} h={400} icon={galleryIcons[activeImg]} />
          </div>
          <div style={{ display: "flex", gap: 10, marginTop: 12 }}>
            {galleryIcons.map((ic, i) => (
              <button key={i} onClick={() => setActiveImg(i)} className="card" style={{ flex: 1, padding: 0, overflow: "hidden", border: "2px solid " + (activeImg === i ? "var(--gold-500)" : "var(--border)"), cursor: "pointer" }}>
                <ProductPh product={p} h={76} icon={ic} />
              </button>
            ))}
          </div>
          <ProductInsights product={p} />
        </div>

        {/* Info */}
        <div>
          <div style={{ display: "flex", gap: 8, flexWrap: "wrap", marginBottom: 12 }}>
            <span className="badge badge-gray">{cat.name}</span>
            {p.tags.slice(0, 3).map(t => <span key={t} className="badge badge-gray">{t}</span>)}
          </div>
          <h1 style={{ fontSize: 28, lineHeight: 1.15 }}>{p.name}</h1>
          <div className="mono muted" style={{ fontSize: 13, marginTop: 8 }}>SKU: {p.sku}</div>

          <div className="card" style={{ padding: 22, marginTop: 20, background: "var(--navy-50)", border: "1px solid var(--border)" }}>
            <div style={{ display: "flex", alignItems: "baseline", gap: 8 }}>
              <span style={{ fontSize: 38, fontWeight: 800, color: "var(--navy-800)", letterSpacing: "-.02em" }}>{fmtPrice(p.priceUSD, currency)}</span>
              <span className="muted" style={{ fontSize: 16 }}>/ {p.unit}</span>
            </div>
            <div style={{ display: "flex", gap: 28, marginTop: 16, flexWrap: "wrap" }}>
              <div><div className="muted" style={{ fontSize: 12.5 }}>Min. order (MOQ)</div><div style={{ fontWeight: 700, marginTop: 2 }}>{p.moq} {p.moqUnit}</div></div>
              <div><div className="muted" style={{ fontSize: 12.5 }}>Unit</div><div style={{ fontWeight: 700, marginTop: 2 }}>per {p.unit}</div></div>
              <div><div className="muted" style={{ fontSize: 12.5 }}>Lead time</div><div style={{ fontWeight: 700, marginTop: 2 }}>2–4 weeks</div></div>
            </div>
            <div style={{ display: "flex", gap: 12, marginTop: 20, flexWrap: "wrap" }}>
              <button className="btn btn-gold btn-lg" style={{ flex: 1, minWidth: 160 }} onClick={() => document.getElementById("inq")?.scrollTo?.()}><Icon name="mail" size={18} /> Send inquiry</button>
              <button className="btn btn-navy btn-lg" style={{ flex: 1, minWidth: 160 }} onClick={() => showToast("Quote requested from " + s.name)}><Icon name="file-text" size={18} /> Request quote</button>
            </div>
          </div>

          {/* Supplier mini-card */}
          <a className="card" onClick={() => nav("store", { slug: s.slug })} style={{ padding: 16, marginTop: 16, display: "flex", gap: 14, alignItems: "center", cursor: "pointer" }}>
            <div style={{ width: 48, height: 48, borderRadius: 10, background: s.color + "1a", color: s.color, display: "flex", alignItems: "center", justifyContent: "center", fontWeight: 700, fontSize: 18, flexShrink: 0 }}>
              {s.name.split(" ").map(w => w[0]).slice(0, 2).join("")}
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontWeight: 700, display: "flex", alignItems: "center", gap: 6 }}>{s.name} {s.verified && <Icon name="badge-check" size={15} style={{ color: "var(--gold-600)" }} />}</div>
              <div className="muted" style={{ fontSize: 13, display: "flex", alignItems: "center", gap: 6, marginTop: 2 }}>
                <Flag code={s.country} size={12} /> {c.name} · <Stars value={s.rating} size={12} /> {s.rating}
              </div>
            </div>
            <span className="btn btn-ghost btn-sm">Visit store <Icon name="arrow-right" size={14} /></span>
          </a>

          {/* Direct phone contact */}
          {s.phone && (
            <a href={"tel:" + s.phone.replace(/\s/g, "")} className="card" style={{ padding: "12px 16px", marginTop: 12, display: "flex", alignItems: "center", gap: 12, cursor: "pointer" }}
              onMouseEnter={e => e.currentTarget.style.boxShadow = "var(--sh-md)"} onMouseLeave={e => e.currentTarget.style.boxShadow = "var(--sh-sm)"}>
              <div style={{ width: 38, height: 38, borderRadius: 10, background: "var(--gold-100)", color: "var(--gold-700)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}><Icon name="phone" size={18} /></div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div className="muted" style={{ fontSize: 11.5 }}>Call supplier directly</div>
                <div className="mono" style={{ fontWeight: 700, fontSize: 15, color: "var(--navy-800)" }}>{s.phone}</div>
              </div>
              <span className="btn btn-navy btn-sm" style={{ flexShrink: 0 }}><Icon name="phone-call" size={14} /> Call</span>
            </a>
          )}

          {/* Certs */}
          <div style={{ display: "flex", gap: 8, marginTop: 16, flexWrap: "wrap" }}>
            {p.certs.map(cert => <span key={cert} className="badge badge-green"><Icon name="award" size={12} /> {cert}</span>)}
          </div>
        </div>
      </div>

      {/* Description + specs */}
      <div className="desc-layout" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 36, marginTop: 48, alignItems: "start" }}>
        <div>
          <h2 style={{ fontSize: 21, marginBottom: 14 }}>Description</h2>
          <p style={{ lineHeight: 1.75, color: "var(--ink-700)" }}>{p.desc}</p>
          <AskAI product={p} />
        </div>
        <div>
          <h2 style={{ fontSize: 21, marginBottom: 14 }}>Specifications</h2>
          <div className="card" style={{ overflow: "hidden" }}>
            <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 14 }}>
              <tbody>
                {p.specs.map(([k, v], i) => (
                  <tr key={k} style={{ background: i % 2 ? "var(--navy-50)" : "#fff" }}>
                    <td style={{ padding: "11px 16px", color: "var(--ink-500)", width: "45%", borderBottom: "1px solid var(--border)" }}>{k}</td>
                    <td style={{ padding: "11px 16px", fontWeight: 600, borderBottom: "1px solid var(--border)" }}>{v}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      </div>

      {/* Inquiry form */}
      <div id="inq" style={{ marginTop: 48 }}>
        <h2 style={{ fontSize: 21, marginBottom: 16 }}>Inquire about this product</h2>
        <InquiryForm supplier={s} product={p} showToast={showToast} />
      </div>

      {/* Related */}
      {related.length > 0 && (
        <div style={{ marginTop: 48 }}>
          <h2 style={{ fontSize: 21, marginBottom: 16 }}>More from {s.name}</h2>
          <div className="card-grid-4" style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 16 }}>
            {related.map(r => <ProductCard key={r.id} product={r} nav={nav} cur={currency} />)}
          </div>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { ProductPage, ProductInsights, AskAI });

/* ---------- AI product insights (buyer-facing) ---------- */
function ProductInsights({ product }) {
  const [state, setState] = useState({ status: "idle" });
  const canAI = window.AMAI && AMAI.available();
  if (!canAI) return null;
  const run = async () => {
    setState({ status: "loading" });
    try { setState({ status: "done", data: await AMAI.productInsights(product) }); }
    catch (e) { setState({ status: "error" }); }
  };
  return (
    <div style={{ marginTop: 12, border: "1px solid var(--gold-300)", background: "var(--gold-50)", borderRadius: 10, padding: "12px 14px" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
        <span className="ai-chip"><Icon name="sparkles" size={12} /> AI insights</span>
        {state.status === "idle" && <button onClick={run} className="btn btn-ghost btn-sm" style={{ marginLeft: "auto", padding: "5px 10px" }}>Get buyer insights</button>}
        {state.status === "loading" && <Icon name="loader-circle" size={15} className="spin" style={{ color: "var(--gold-700)", marginLeft: "auto" }} />}
      </div>
      {state.status === "error" && <div className="muted" style={{ fontSize: 12.5, marginTop: 8 }}>AI insights are unavailable right now.</div>}
      {state.status === "done" && (
        <div style={{ marginTop: 10, display: "flex", flexDirection: "column", gap: 12 }}>
          <div>
            <div style={{ fontSize: 11.5, fontWeight: 700, color: "var(--ink-500)", textTransform: "uppercase", letterSpacing: ".05em" }}>Typical applications</div>
            <ul style={{ margin: "6px 0 0", padding: 0, display: "flex", flexDirection: "column", gap: 4 }}>
              {state.data.applications.map((a, i) => <li key={i} style={{ display: "flex", gap: 7, fontSize: 13, lineHeight: 1.45 }}><Icon name="check" size={14} style={{ color: "var(--green-600)", flexShrink: 0, marginTop: 2 }} /> {a}</li>)}
            </ul>
          </div>
          <div>
            <div style={{ fontSize: 11.5, fontWeight: 700, color: "var(--ink-500)", textTransform: "uppercase", letterSpacing: ".05em" }}>Questions to ask the supplier</div>
            <ul style={{ margin: "6px 0 0", padding: 0, display: "flex", flexDirection: "column", gap: 4 }}>
              {state.data.questions.map((qn, i) => <li key={i} style={{ display: "flex", gap: 7, fontSize: 13, lineHeight: 1.45 }}><Icon name="help-circle" size={14} style={{ color: "var(--gold-700)", flexShrink: 0, marginTop: 2 }} /> {qn}</li>)}
            </ul>
          </div>
        </div>
      )}
    </div>
  );
}

/* ---------- Ask AI about this product (grounded Q&A) ---------- */
function AskAI({ product }) {
  const [q, setQ] = useState("");
  const [busy, setBusy] = useState(false);
  const [answer, setAnswer] = useState("");
  const canAI = window.AMAI && AMAI.available();
  if (!canAI) return null;
  const suggestions = ["Is this suitable for my use case?", "What certifications come with it?", "What are the delivery terms?"];
  const ask = async (question) => {
    const text = (question || q).trim();
    if (!text || busy) return;
    setQ(text); setBusy(true); setAnswer("");
    try { setAnswer(await AMAI.askAboutProduct(product, text)); }
    catch (e) { setAnswer("Sorry, the assistant is unavailable right now — please contact the supplier directly."); }
    setBusy(false);
  };
  return (
    <div style={{ marginTop: 16, border: "1px solid var(--gold-300)", background: "var(--gold-50)", borderRadius: 12, padding: 16 }}>
      <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 10 }}>
        <span className="ai-chip"><Icon name="sparkles" size={12} /> AI</span>
        <span style={{ fontSize: 13.5, fontWeight: 700 }}>Ask about this product</span>
      </div>
      <div style={{ display: "flex", gap: 8 }}>
        <input className="input" value={q} onChange={e => setQ(e.target.value)} onKeyDown={e => e.key === "Enter" && ask()} placeholder="e.g. Will this meet BS 4449 for a highway project?" style={{ flex: 1 }} />
        <button className="btn btn-navy" onClick={() => ask()} disabled={busy} style={{ flexShrink: 0 }}><Icon name={busy ? "loader-circle" : "send"} size={16} className={busy ? "spin" : ""} /></button>
      </div>
      {!answer && !busy && (
        <div style={{ display: "flex", gap: 7, flexWrap: "wrap", marginTop: 10 }}>
          {suggestions.map(s => <button key={s} onClick={() => ask(s)} className="badge badge-gray" style={{ cursor: "pointer", border: "1px solid var(--border-strong)" }}>{s}</button>)}
        </div>
      )}
      {busy && <div className="muted" style={{ fontSize: 13, marginTop: 10 }}>Thinking…</div>}
      {answer && (
        <div style={{ marginTop: 12, background: "#fff", border: "1px solid var(--border)", borderRadius: 10, padding: "12px 14px", fontSize: 13.5, lineHeight: 1.6, color: "var(--ink-900)" }}>{answer}
          <div className="muted" style={{ fontSize: 11, marginTop: 8, display: "flex", gap: 5, alignItems: "center" }}><Icon name="info" size={12} /> AI-generated from this listing — confirm specifics with the supplier.</div>
        </div>
      )}
    </div>
  );
}
