const { useState: useSt, useEffect: useEf, useMemo: useMem } = React;

// ── helpers ────────────────────────────────────────────────────────────────────

const STATUS_META = {
  active:   { label: "active",   cls: "chip pos dot" },
  draft:    { label: "draft",    cls: "chip warn dot" },
  archived: { label: "archived", cls: "chip dot" },
};

// products.images is a jsonb array; grab first item's url
function firstImage(p) {
  if (p.images && Array.isArray(p.images) && p.images.length > 0) {
    const img = p.images[0];
    return typeof img === "string" ? img : (img?.url || img?.src || null);
  }
  if (p.media && Array.isArray(p.media) && p.media.length > 0) {
    const m = p.media[0];
    return typeof m === "string" ? m : (m?.url || m?.src || null);
  }
  return null;
}

// ── KPI card ──────────────────────────────────────────────────────────────────

const KpiCard = ({ label, value, sub, last }) => (
  <div style={{ padding: "14px 18px", borderRight: last ? "none" : "1px solid var(--hairline)" }}>
    <div style={{ fontSize: 10, fontFamily: "var(--font-mono)", color: "var(--ink-3)", textTransform: "uppercase", letterSpacing: "0.06em", marginBottom: 4 }}>{label}</div>
    <div style={{ fontSize: 20, fontWeight: 550, letterSpacing: "-0.01em", fontFeatureSettings: '"tnum" 1' }}>{value}</div>
    {sub && <div style={{ fontSize: 11, color: "var(--ink-3)", marginTop: 2, fontFamily: "var(--font-mono)" }}>{sub}</div>}
  </div>
);

// ── Main page ─────────────────────────────────────────────────────────────────

const ProductsPage = () => {
  const D  = window.PipalData;
  const I  = window.Icons;
  const sb = window.supabaseClient;

  const [products,      setProducts]      = useSt([]);
  const [productId,     setProductId]     = useSt(null);
  const [loading,       setLoading]       = useSt(true);
  const [detailLoading, setDetailLoading] = useSt(false);
  const [search,        setSearch]        = useSt("");
  const [statusFilt,    setStatusFilt]    = useSt("all");
  const [orders,        setOrders]        = useSt([]);
  const [reviews,       setReviews]       = useSt([]);
  const [variants,      setVariants]      = useSt([]);
  const [stats,         setStats]         = useSt({ total: 0, active: 0, draft: 0, archived: 0 });
  const [activeTab,     setActiveTab]     = useSt("orders");
  const [showDetail,    setShowDetail]    = useSt(false); // mobile: toggle list vs detail
  const [sourcePopover, setSourcePopover] = useSt(null); // { anchor: DOMRect, data: obj, loading: bool }

  const product = products.find(p => p.id === productId) || null;

  // close popover on outside click
  useEf(() => {
    if (!sourcePopover) return;
    const close = () => setSourcePopover(null);
    window.addEventListener("click", close);
    return () => window.removeEventListener("click", close);
  }, [!!sourcePopover]);

  const visible = useMem(() => {
    const q = search.trim().toLowerCase();
    return products.filter(p => {
      if (statusFilt !== "all" && p.status !== statusFilt) return false;
      if (!q) return true;
      return (
        (p.name || "").toLowerCase().includes(q) ||
        (p.stores?.name || "").toLowerCase().includes(q) ||
        (p.category || "").toLowerCase().includes(q) ||
        (p.sku || "").toLowerCase().includes(q)
      );
    });
  }, [products, search, statusFilt]);

  // ── fetch product list ────────────────────────────────────────────────────

  useEf(() => {
    if (!sb) return;
    setLoading(true);
    sb.from("products")
      .select(`
        id, name, images, media, price, compare_at_price, status,
        rating, review_count, category, subcategory, store_id,
        created_at, sku, quantity, low_stock_threshold, sales_count,
        view_count, like_count, featured, condition, short_description,
        stores(id, name, logo_url, status, verification_status)
      `)
      .order("created_at", { ascending: false })
      .limit(100)
      .then(({ data, error }) => {
        if (!error && data) {
          setProducts(data);
          setStats({
            total:    data.length,
            active:   data.filter(p => p.status === "active").length,
            draft:    data.filter(p => p.status === "draft").length,
            archived: data.filter(p => p.status === "archived").length,
          });
          if (data.length > 0) setProductId(data[0].id);
        }
        setLoading(false);
      });
  }, []);

  const handleSelectProduct = (id) => {
    setProductId(id);
    setShowDetail(true);
  };

  // ── fetch product detail ──────────────────────────────────────────────────

  useEf(() => {
    if (!sb || !productId) return;
    setDetailLoading(true);
    setOrders([]);
    setReviews([]);
    setVariants([]);

    Promise.all([
      sb.from("order_items")
        .select("quantity, unit_price, total_price, source, source_post_id, source_challenge_post_id, order_id, orders(id, order_number, order_status, total_amount, created_at, payment_method, delivery_method)")
        .eq("product_id", productId)
        .order("created_at", { ascending: false })
        .limit(20),
      sb.from("product_reviews")
        .select("id, rating, title, review_text, verified_purchase, helpful_count, created_at, status")
        .eq("product_id", productId)
        .eq("status", "published")
        .order("created_at", { ascending: false })
        .limit(10),
      sb.from("product_variants")
        .select("id, name, sku, price, quantity, options, image_url")
        .eq("product_id", productId)
        .order("created_at", { ascending: true }),
    ]).then(([ordersRes, reviewsRes, variantsRes]) => {
      if (!ordersRes.error && ordersRes.data) setOrders(ordersRes.data.filter(r => r.orders));
      if (!reviewsRes.error && reviewsRes.data) setReviews(reviewsRes.data);
      if (!variantsRes.error && variantsRes.data) setVariants(variantsRes.data);
      setDetailLoading(false);
    });
  }, [productId]);

  // ── derived ───────────────────────────────────────────────────────────────

  const productRevenue = orders.reduce((s, r) => s + Number(r.total_price || 0), 0);
  const unitsSold      = orders.reduce((s, r) => s + (r.quantity || 1), 0);
  const avgRating      = reviews.length > 0
    ? (reviews.reduce((s, r) => s + r.rating, 0) / reviews.length).toFixed(1)
    : null;

  // ── helpers ───────────────────────────────────────────────────────────────

  const FilterPill = ({ id, label }) => (
    <span className="chip" onClick={() => setStatusFilt(id)} style={{
      cursor: "pointer",
      background:  statusFilt === id ? "var(--accent-soft)" : undefined,
      color:       statusFilt === id ? "var(--accent-ink)"  : undefined,
      borderColor: statusFilt === id ? "transparent"        : undefined,
    }}>{label}</span>
  );

  const orderChip = (status) => {
    if (!status) return null;
    const cls =
      status === "delivered"  ? "chip pos dot"  :
      status === "in_transit" ? "chip info dot" :
      status === "preparing"  ? "chip warn dot" :
      status === "cancelled"  ? "chip neg dot"  : "chip dot";
    return <span className={cls} style={{ fontSize: 11 }}>{status.replace(/_/g, " ")}</span>;
  };

  const SOURCE_META = {
    post_feed:            { label: "post feed",       cls: "chip info dot" },
    post_tag:             { label: "post tag",        cls: "chip info dot" },
    feed:                 { label: "home feed",        cls: "chip info dot" },
    feed_ad:              { label: "home feed (ad)",  cls: "chip warn dot" },
    challenge:            { label: "challenge 🔥",   cls: "chip warn dot" },
    search:               { label: "search",          cls: "chip dot" },
    search_suggestion_ad: { label: "search ad",       cls: "chip dot" },
    storefront:           { label: "store page",      cls: "chip dot" },
    chat:                 { label: "chat share",      cls: "chip dot" },
    posts_feed_ad:        { label: "feed ad",         cls: "chip warn dot" },
    wishlist:             { label: "wishlist",        cls: "chip dot" },
    explore:              { label: "explore",         cls: "chip dot" },
    offers:               { label: "offers",          cls: "chip dot" },
    notification:         { label: "notification",   cls: "chip dot" },
    order_history:        { label: "order history",  cls: "chip dot" },
    charts:               { label: "charts",         cls: "chip dot" },
    cart:                 { label: "cart",            cls: "chip dot" },
    profile:              { label: "profile",         cls: "chip dot" },
    buy_again:            { label: "buy again",      cls: "chip pos dot" },
    saved_for_later:      { label: "saved later",    cls: "chip dot" },
    recently_viewed:      { label: "recently viewed",cls: "chip dot" },
    restock_alert:        { label: "restock alert",  cls: "chip pos dot" },
    checkout_shop_more:   { label: "checkout",       cls: "chip dot" },
    direct:               { label: "direct",         cls: "chip dot" },
  };

  const LINKABLE = new Set(["post_feed", "post_tag", "challenge", "chat", "posts_feed_ad"]);

  const handleSourceClick = async (e, row) => {
    e.stopPropagation();
    const source = row.source;
    if (!LINKABLE.has(source)) return;
    const rect = e.currentTarget.getBoundingClientRect();
    const popW = 240;
    const popH = 260;
    const top  = rect.bottom + 6;
    const left = Math.min(rect.left, window.innerWidth - popW - 12);
    // if popover would go below viewport, show above the chip instead
    const finalTop = top + popH > window.innerHeight ? rect.top - popH - 6 : top;
    setSourcePopover({ top: finalTop, left, data: null, loading: true });

    let data = null;
    if ((source === "post_feed" || source === "post_tag" || source === "posts_feed_ad") && row.source_post_id) {
      const { data: d } = await sb
        .from("posts")
        .select("id, caption, user:user_profiles(display_name, avatar_url), media:media_items(public_url, file_type, thumbnail_url, order_index)")
        .eq("id", row.source_post_id)
        .single();
      if (d) {
        const media = (d.media || []).sort((a, b) => a.order_index - b.order_index)[0];
        data = { type: "post", caption: d.caption, author: d.user?.display_name, avatar: d.user?.avatar_url, thumb: media?.thumbnail_url || (media?.file_type !== "video" ? media?.public_url : null), id: d.id };
      }
    } else if (source === "challenge" && row.source_challenge_post_id) {
      const { data: d } = await sb
        .from("challenge_posts")
        .select("id, caption, tagged_product_name, media_url, media_type, thumbnail_url, user:user_profiles(display_name, avatar_url)")
        .eq("id", row.source_challenge_post_id)
        .single();
      if (d) {
        data = { type: "challenge", caption: d.caption, author: d.user?.display_name, avatar: d.user?.avatar_url, thumb: d.thumbnail_url || (d.media_type === "image" ? d.media_url : null), tagged: d.tagged_product_name, id: d.id };
      }
    } else if (source === "chat") {
      data = { type: "chat", caption: "Shared via chat message", author: null, thumb: null };
    }

    setSourcePopover(prev => ({ ...prev, data: data || { type: "empty" }, loading: false }));
  };

  const sourceChip = (row) => {
    const source = row.source;
    if (!source) return <span className="muted" style={{ fontSize: 11 }}>—</span>;
    const m = SOURCE_META[source];
    const label = m ? m.label : source.replace(/_/g, " ");
    const cls   = m ? m.cls : "chip dot";
    const clickable = LINKABLE.has(source);
    return (
      <span
        className={cls}
        style={{ fontSize: 11, cursor: clickable ? "pointer" : "default", textDecoration: clickable ? "underline dotted" : "none" }}
        onClick={clickable ? (e) => handleSourceClick(e, row) : undefined}
        title={clickable ? "Click to preview" : undefined}
      >{label}</span>
    );
  };

  const SourcePopover = () => {
    if (!sourcePopover) return null;
    const { top, left, data, loading } = sourcePopover;
    return (
      <div
        onClick={e => e.stopPropagation()}
        style={{
          position: "fixed", zIndex: 9999,
          top, left, width: 240,
          background: "var(--surface)", border: "1px solid var(--hairline)",
          borderRadius: 8, boxShadow: "0 4px 24px rgba(0,0,0,0.18)", fontSize: 12,
          overflow: "hidden",
        }}
      >
        {/* close button */}
        <button
          onClick={() => setSourcePopover(null)}
          style={{
            position: "absolute", top: 6, right: 6, zIndex: 1,
            width: 20, height: 20, borderRadius: 10,
            background: "rgba(0,0,0,0.35)", border: "none", cursor: "pointer",
            display: "grid", placeItems: "center", color: "#fff", fontSize: 11, lineHeight: 1,
          }}
        >✕</button>

        {loading ? (
          <div style={{ padding: "28px 16px", color: "var(--ink-3)", textAlign: "center" }}>Loading…</div>
        ) : !data || data.type === "empty" ? (
          <div style={{ padding: "16px" , color: "var(--ink-3)" }}>No details available</div>
        ) : data.type === "chat" ? (
          <div style={{ padding: 16, color: "var(--ink-2)" }}>📩 Shared via a chat message — no linked post.</div>
        ) : (
          <div style={{ display: "flex", flexDirection: "column" }}>
            {data.thumb ? (
              <img src={data.thumb} style={{ width: "100%", height: 120, objectFit: "cover", display: "block" }} />
            ) : (
              <div style={{ width: "100%", height: 60, background: "var(--surface-3)", display: "grid", placeItems: "center", color: "var(--ink-4)", fontSize: 11 }}>no preview</div>
            )}
            <div style={{ padding: "10px 12px", display: "flex", flexDirection: "column", gap: 6 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
                {data.avatar
                  ? <img src={data.avatar} style={{ width: 20, height: 20, borderRadius: 10, objectFit: "cover", flexShrink: 0 }} />
                  : <div style={{ width: 20, height: 20, borderRadius: 10, background: "var(--surface-3)", display: "grid", placeItems: "center", fontSize: 9, fontWeight: 700, color: "var(--ink-3)", flexShrink: 0 }}>{(data.author || "?")[0]?.toUpperCase()}</div>
                }
                <span style={{ fontWeight: 550, color: "var(--ink)", fontSize: 12 }}>{data.author || "Unknown"}</span>
                <span className={data.type === "challenge" ? "chip warn dot" : "chip info dot"} style={{ fontSize: 10, marginLeft: "auto", flexShrink: 0 }}>{data.type}</span>
              </div>
              {data.tagged && (
                <div style={{ color: "var(--ink-3)", fontSize: 11 }}>Tagged: <strong style={{ color: "var(--ink-2)" }}>{data.tagged}</strong></div>
              )}
              {data.caption && (
                <div style={{ color: "var(--ink-2)", lineHeight: 1.5, maxHeight: 52, overflow: "hidden" }}>{data.caption}</div>
              )}
              {!data.caption && !data.tagged && (
                <div style={{ color: "var(--ink-4)" }}>No caption</div>
              )}
            </div>
          </div>
        )}
      </div>
    );
  };

  const reviewStars = (n) => "★".repeat(n) + "☆".repeat(5 - n);

  // ── render ────────────────────────────────────────────────────────────────

  return (
    <div className="page" data-screen-label="products">
      <div className="page-h">
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          {showDetail && (
            <button
              className="btn mob-back-btn"
              onClick={() => setShowDetail(false)}
              style={{ display: "none" }}
            >
              <I.arrowR size={12} style={{ transform: "rotate(180deg)" }}/> Back
            </button>
          )}
          <div>
            <div className="ts">Catalog</div>
            <h1>Products</h1>
          </div>
        </div>
        <div className="ftabs" style={{ display: "flex", gap: 8, marginLeft: "auto", alignItems: "center" }}>
          <FilterPill id="all"      label={`All · ${stats.total}`} />
          <FilterPill id="active"   label={`Active · ${stats.active}`} />
          <FilterPill id="draft"    label={`Draft · ${stats.draft}`} />
          <FilterPill id="archived" label={`Archived · ${stats.archived}`} />
        </div>
      </div>

      <div className="mob-stack" style={{ display: "grid", gridTemplateColumns: "300px 1fr", gap: 14, flex: 1, minHeight: 0 }}>

        {/* LEFT: product list */}
        <div className={`panel prod-list-panel${showDetail ? " mob-hidden" : ""}`} style={{ display: "flex", flexDirection: "column", overflow: "hidden", padding: 0 }}>
          <div style={{ padding: "10px 12px", borderBottom: "1px solid var(--hairline)" }}>
            <div style={{ display: "flex", alignItems: "center", gap: 8, background: "var(--surface-2)", border: "1px solid var(--hairline)", borderRadius: 5, padding: "5px 10px" }}>
              <I.search size={12} style={{ color: "var(--ink-3)", flexShrink: 0 }}/>
              <input
                value={search}
                onChange={e => setSearch(e.target.value)}
                placeholder="Search name, SKU, category…"
                style={{ border: "none", background: "transparent", outline: "none", fontSize: 12, color: "var(--ink)", width: "100%", fontFamily: "var(--font-sans)" }}
              />
              {search && <I.x size={12} style={{ color: "var(--ink-3)", cursor: "pointer" }} onClick={() => setSearch("")}/>}
            </div>
          </div>

          <div style={{ overflow: "auto", flex: 1 }}>
            {loading ? (
              <div style={{ padding: 24, textAlign: "center", color: "var(--ink-3)", fontSize: 12 }}>Loading products…</div>
            ) : visible.length === 0 ? (
              <div style={{ padding: 24, textAlign: "center", color: "var(--ink-3)", fontSize: 12 }}>No products found</div>
            ) : visible.map((p) => {
              const sel      = p.id === productId;
              const sm       = STATUS_META[p.status] || { label: p.status || "unknown", cls: "chip dot" };
              const imgSrc   = firstImage(p);
              const lowStock = p.quantity <= (p.low_stock_threshold || 5) && p.quantity > 0;
              const noStock  = p.quantity === 0 && p.status === "active";
              return (
                <div key={p.id} onClick={() => handleSelectProduct(p.id)} style={{
                  display: "grid", gridTemplateColumns: "40px 1fr auto",
                  gap: 10, alignItems: "center",
                  padding: "9px 14px",
                  borderBottom: "1px solid var(--hairline)",
                  background: sel ? "var(--surface-2)" : "transparent",
                  cursor: "pointer", position: "relative",
                }}>
                  {sel && <div style={{ position: "absolute", left: 0, top: 8, bottom: 8, width: 2, background: "var(--accent)" }}/>}
                  {imgSrc ? (
                    <img src={imgSrc} alt={p.name} style={{ width: 40, height: 40, borderRadius: 4, objectFit: "cover" }}/>
                  ) : (
                    <div style={{ width: 40, height: 40, borderRadius: 4, background: "var(--surface-3)", display: "grid", placeItems: "center" }}>
                      <I.package size={16} style={{ color: "var(--ink-4)" }}/>
                    </div>
                  )}
                  <div style={{ minWidth: 0 }}>
                    <div style={{ fontWeight: 500, color: "var(--ink)", fontSize: 12.5, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
                      {p.featured && <span style={{ color: "var(--warn)", marginRight: 4, fontSize: 10 }}>★</span>}
                      {p.name || "—"}
                    </div>
                    <div className="muted" style={{ fontSize: 11, fontFamily: "var(--font-mono)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
                      {p.stores?.name || "—"}{p.price ? ` · ${D.currency(p.price)}` : ""}
                      {noStock  && <span style={{ color: "var(--neg)",  marginLeft: 4 }}>· out of stock</span>}
                      {!noStock && lowStock && <span style={{ color: "var(--warn)", marginLeft: 4 }}>· low stock</span>}
                    </div>
                  </div>
                  <span className={sm.cls} style={{ flexShrink: 0, fontSize: 11 }}>{sm.label}</span>
                </div>
              );
            })}
          </div>
        </div>

        {/* RIGHT: product detail */}
        {!product ? (
          <div className={`panel prod-detail-panel${showDetail ? " mob-visible" : ""}`} style={{ display: "flex", alignItems: "center", justifyContent: "center", color: "var(--ink-3)", fontSize: 13 }}>
            {loading ? "Loading…" : "Select a product"}
          </div>
        ) : (
          <div className={`prod-detail-panel${showDetail ? " mob-visible" : ""}`} style={{ display: "flex", flexDirection: "column", gap: 14, overflow: "auto" }}>

            {/* Header card */}
            <div className="panel">
              <div style={{ padding: "18px 20px", display: "flex", alignItems: "flex-start", gap: 16 }}>
                {(() => {
                  const src = firstImage(product);
                  return src ? (
                    <img src={src} alt={product.name} style={{ width: 80, height: 80, borderRadius: 8, objectFit: "cover", flexShrink: 0 }}/>
                  ) : (
                    <div style={{ width: 80, height: 80, borderRadius: 8, background: "var(--surface-3)", display: "grid", placeItems: "center", flexShrink: 0 }}>
                      <I.package size={28} style={{ color: "var(--ink-3)" }}/>
                    </div>
                  );
                })()}
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap" }}>
                    <h2 style={{ margin: 0, fontSize: 20, fontWeight: 550, letterSpacing: "-0.01em" }}>{product.name}</h2>
                    {product.featured && <span className="chip warn dot" style={{ fontSize: 11 }}>featured</span>}
                    <span className={(STATUS_META[product.status] || { cls: "chip dot" }).cls}>{product.status || "unknown"}</span>
                    {product.category && <span className="chip">{product.category}</span>}
                    {product.subcategory && <span className="chip">{product.subcategory}</span>}
                    {product.condition && product.condition !== "new" && <span className="chip">{product.condition}</span>}
                  </div>
                  <div className="muted" style={{ fontSize: 12, marginTop: 4, fontFamily: "var(--font-mono)" }}>
                    {product.sku && `SKU: ${product.sku}`}
                    {product.sku && product.stores?.name && " · "}
                    {product.stores?.name}
                    {product.created_at && ` · listed ${new Date(product.created_at).toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" })}`}
                  </div>
                  {product.short_description && (
                    <p style={{ margin: "8px 0 0", fontSize: 13, color: "var(--ink-2)", lineHeight: 1.5, maxWidth: 560 }}>{product.short_description}</p>
                  )}
                </div>
                <div style={{ textAlign: "right", flexShrink: 0 }}>
                  <div style={{ fontSize: 22, fontWeight: 600, letterSpacing: "-0.02em" }}>{D.currency(product.price)}</div>
                  {product.compare_at_price && Number(product.compare_at_price) > Number(product.price) && (
                    <div style={{ fontSize: 13, color: "var(--ink-3)", textDecoration: "line-through", fontFamily: "var(--font-mono)" }}>
                      {D.currency(product.compare_at_price)}
                    </div>
                  )}
                </div>
              </div>

              {/* KPI strip */}
              <div className="kpi-grid" style={{ display: "grid", gridTemplateColumns: "repeat(6, 1fr)", borderTop: "1px solid var(--hairline)" }}>
                <KpiCard label="Stock"   value={product.quantity ?? "—"} sub={product.quantity > 0 && product.quantity <= (product.low_stock_threshold || 5) ? "⚠ low" : null} />
                <KpiCard label="Sales"   value={product.sales_count?.toLocaleString() ?? "—"} />
                <KpiCard label="Views"   value={product.view_count?.toLocaleString() ?? "—"} />
                <KpiCard label="Likes"   value={product.like_count?.toLocaleString() ?? "—"} />
                <KpiCard label="Rating"  value={product.rating ? `${Number(product.rating).toFixed(1)} ★` : "—"} sub={product.review_count ? `${product.review_count} reviews` : null} />
                <KpiCard label="Revenue" value={productRevenue > 0 ? D.compactCurrency(productRevenue) : "—"} sub={unitsSold > 0 ? `${unitsSold} units` : null} last />
              </div>
            </div>

            {/* Store */}
            {product.stores && (
              <div className="panel" style={{ padding: "12px 18px" }}>
                <div style={{ fontSize: 10, fontFamily: "var(--font-mono)", color: "var(--ink-3)", textTransform: "uppercase", letterSpacing: "0.06em", marginBottom: 8 }}>Store</div>
                <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                  {product.stores.logo_url ? (
                    <img src={product.stores.logo_url} alt={product.stores.name} style={{ width: 28, height: 28, borderRadius: 4, objectFit: "cover" }}/>
                  ) : (
                    <div style={{ width: 28, height: 28, borderRadius: 4, background: "var(--surface-3)", display: "grid", placeItems: "center", fontSize: 12, fontWeight: 600, color: "var(--ink-3)" }}>
                      {(product.stores.name || "?")[0].toUpperCase()}
                    </div>
                  )}
                  <span style={{ fontWeight: 500, fontSize: 13 }}>{product.stores.name}</span>
                  {product.stores.verification_status === "verified" && <span className="chip pos dot" style={{ fontSize: 11 }}>verified</span>}
                  <span className={(STATUS_META[product.stores.status] || { cls: "chip dot" }).cls} style={{ fontSize: 11 }}>{product.stores.status}</span>
                </div>
              </div>
            )}

            {/* Tabbed detail */}
            <div className="panel" style={{ flex: 1 }}>
              <div style={{ display: "flex", borderBottom: "1px solid var(--hairline)" }}>
                {[
                  { id: "orders",   label: `Orders (${orders.length})` },
                  { id: "reviews",  label: `Reviews (${reviews.length})` },
                  { id: "variants", label: `Variants (${variants.length})` },
                ].map(t => (
                  <span key={t.id} onClick={() => setActiveTab(t.id)} style={{
                    padding: "10px 16px", fontSize: 13, cursor: "pointer",
                    fontWeight: activeTab === t.id ? 550 : 400,
                    color: activeTab === t.id ? "var(--ink)" : "var(--ink-3)",
                    borderBottom: activeTab === t.id ? "2px solid var(--accent)" : "2px solid transparent",
                    marginBottom: -1,
                  }}>{t.label}</span>
                ))}
                {detailLoading && <span className="muted" style={{ marginLeft: "auto", padding: "10px 16px", fontSize: 12 }}>Loading…</span>}
              </div>

              {/* Orders */}
              {activeTab === "orders" && (orders.length === 0 ? (
                <div style={{ padding: 24, textAlign: "center", color: "var(--ink-3)", fontSize: 12 }}>
                  {detailLoading ? "Loading…" : "No orders found for this product"}
                </div>
              ) : (
                <div className="t-wrap"><table className="t">
                  <thead><tr>
                    <th>Order #</th>
                    <th style={{ textAlign: "right" }}>Qty</th>
                    <th style={{ textAlign: "right" }}>Item total</th>
                    <th style={{ textAlign: "right" }}>Order total</th>
                    <th>Status</th>
                    <th>Source</th>
                    <th>Method</th>
                    <th>Date</th>
                  </tr></thead>
                  <tbody>
                    {orders.map((r, i) => {
                      const ord = r.orders;
                      return (
                        <tr key={i}>
                          <td style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--ink-2)" }}>{ord?.order_number || ord?.id?.slice(0, 12) || "—"}</td>
                          <td style={{ textAlign: "right", fontFamily: "var(--font-mono)" }}>{r.quantity ?? 1}</td>
                          <td style={{ textAlign: "right", fontFamily: "var(--font-mono)" }}>{r.total_price ? D.currency(r.total_price) : "—"}</td>
                          <td style={{ textAlign: "right", fontFamily: "var(--font-mono)" }}>{ord?.total_amount ? D.currency(ord.total_amount) : "—"}</td>
                          <td>{orderChip(ord?.order_status)}</td>
                          <td>{sourceChip(r)}</td>
                          <td className="muted" style={{ fontSize: 11 }}>{ord?.delivery_method || ord?.payment_method || "—"}</td>
                          <td className="muted" style={{ fontSize: 11, fontFamily: "var(--font-mono)" }}>
                            {ord?.created_at ? new Date(ord.created_at).toLocaleDateString("en-US", { month: "short", day: "numeric" }) : "—"}
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table></div>
              ))}

              {/* Reviews */}
              {activeTab === "reviews" && (reviews.length === 0 ? (
                <div style={{ padding: 24, textAlign: "center", color: "var(--ink-3)", fontSize: 12 }}>
                  {detailLoading ? "Loading…" : "No published reviews"}
                </div>
              ) : (
                <div style={{ display: "flex", flexDirection: "column" }}>
                  {reviews.map(r => (
                    <div key={r.id} style={{ padding: "14px 18px", borderBottom: "1px solid var(--hairline)" }}>
                      <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 4 }}>
                        <span style={{ fontFamily: "var(--font-mono)", fontSize: 13, color: "var(--warn)" }}>{reviewStars(r.rating)}</span>
                        {r.verified_purchase && <span className="chip pos dot" style={{ fontSize: 10 }}>verified purchase</span>}
                        {r.helpful_count > 0 && <span className="muted" style={{ fontSize: 11, marginLeft: "auto" }}>👍 {r.helpful_count}</span>}
                        <span className="muted" style={{ fontSize: 11, fontFamily: "var(--font-mono)" }}>
                          {r.created_at ? new Date(r.created_at).toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" }) : ""}
                        </span>
                      </div>
                      {r.title && <div style={{ fontWeight: 550, fontSize: 13, marginBottom: 4 }}>{r.title}</div>}
                      {r.review_text && <div style={{ fontSize: 13, color: "var(--ink-2)", lineHeight: 1.55 }}>{r.review_text}</div>}
                    </div>
                  ))}
                  {avgRating && (
                    <div style={{ padding: "10px 18px", fontSize: 12, color: "var(--ink-3)" }}>
                      Avg: <strong style={{ color: "var(--ink)" }}>{avgRating} ★</strong> from {reviews.length} shown
                    </div>
                  )}
                </div>
              ))}

              {/* Variants */}
              {activeTab === "variants" && (variants.length === 0 ? (
                <div style={{ padding: 24, textAlign: "center", color: "var(--ink-3)", fontSize: 12 }}>
                  {detailLoading ? "Loading…" : "No variants — single variant product"}
                </div>
              ) : (
                <div className="t-wrap"><table className="t">
                  <thead><tr>
                    <th>Variant</th>
                    <th>SKU</th>
                    <th style={{ textAlign: "right" }}>Price</th>
                    <th style={{ textAlign: "right" }}>Stock</th>
                    <th>Options</th>
                  </tr></thead>
                  <tbody>
                    {variants.map(v => (
                      <tr key={v.id}>
                        <td style={{ display: "flex", alignItems: "center", gap: 8 }}>
                          {v.image_url && <img src={v.image_url} alt={v.name} style={{ width: 24, height: 24, borderRadius: 3, objectFit: "cover" }}/>}
                          {v.name}
                        </td>
                        <td className="muted" style={{ fontFamily: "var(--font-mono)", fontSize: 11 }}>{v.sku || "—"}</td>
                        <td style={{ textAlign: "right", fontFamily: "var(--font-mono)" }}>{v.price ? D.currency(v.price) : "—"}</td>
                        <td style={{ textAlign: "right" }}>
                          <span style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: v.quantity === 0 ? "var(--neg)" : v.quantity <= 5 ? "var(--warn)" : "var(--ink)" }}>
                            {v.quantity ?? "—"}
                          </span>
                        </td>
                        <td className="muted" style={{ fontSize: 11 }}>
                          {v.options ? Object.entries(v.options).map(([k, val]) => `${k}: ${val}`).join(", ") : "—"}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table></div>
              ))}
            </div>
          </div>
        )}
      </div>
      <SourcePopover />
    </div>
  );
};

window.ProductsPage = ProductsPage;
