const { useState: useStateS, useMemo: useMemoS, useEffect: useEffectS, useRef: useRefS, useId: useIdS } = React;
const useStateS2 = useStateS;

// ── helpers ────────────────────────────────────────────────────────────────────

function fmtCompact(n) {
  const D = window.PipalData;
  return D.compactCurrency(n);
}

function buildRevenueData(orders, range) {
  const now = new Date();
  const days = range === "1W" ? 7 : range === "1M" ? 30 : range === "3M" ? 90 : range === "6M" ? 180 : range === "1Y" ? 365 : 730;
  const bucketDays = days <= 30 ? 1 : days <= 90 ? 7 : 30;
  const curStart = new Date(now.getTime() - days * 86400000);

  const buckets = [];
  let t = new Date(curStart);
  while (t <= now) {
    const end = new Date(t.getTime() + bucketDays * 86400000);
    const cur = orders
      .filter(o => o.created_at && new Date(o.created_at) >= t && new Date(o.created_at) < end)
      .reduce((s, o) => s + Number(o.total_amount || 0), 0);

    const prevBucketStart = new Date(t.getTime() - days * 86400000);
    const prevBucketEnd = new Date(end.getTime() - days * 86400000);
    const prev = orders
      .filter(o => o.created_at && new Date(o.created_at) >= prevBucketStart && new Date(o.created_at) < prevBucketEnd)
      .reduce((s, o) => s + Number(o.total_amount || 0), 0);

    const months = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
    const label = bucketDays === 30
      ? months[t.getMonth()]
      : `${months[t.getMonth()]} ${t.getDate()}`;

    buckets.push({ label, revenue: cur, prev, date: new Date(t) });
    t = end;
  }
  return buckets;
}

// ── Main page ──────────────────────────────────────────────────────────────────

const StoresPage = () => {
  const D = window.PipalData;
  const I = window.Icons;
  const sb = window.supabaseClient;

  const [stores, setStores] = useStateS([]);
  const [storeId, setStoreId] = useStateS(null);
  const [range, setRange] = useStateS("1M");
  const [compare, setCompare] = useStateS(true);
  const [loading, setLoading] = useStateS(true);
  const [detailLoading, setDetailLoading] = useStateS(false);
  const [platformStats, setPlatformStats] = useStateS({ activeStores: 0, pendingInvitations: 0 });
  const [search, setSearch] = useStateS("");
  const [statusFilter, setStatusFilter] = useStateS("all");
  const [extraInfo, setExtraInfo] = useStateS({
    products: 0, activeProducts: 0, orders: 0,
    revenue: 0, prevRevenue: 0, rating: 0, reviews: 0,
    owner: null, averageOrderValue: 0,
    topProducts: [], recentOrders: [], revenueData: [],
    takeRate: 0,
  });

  const store = stores.find(s => s.id === storeId) || null;

  const visibleStores = useMemoS(() => {
    const q = search.trim().toLowerCase();
    return stores.filter(s => {
      if (statusFilter !== "all" && s.status !== statusFilter) return false;
      if (!q) return true;
      return s.name.toLowerCase().includes(q) || (s.category || "").toLowerCase().includes(q) || (s.slug || "").toLowerCase().includes(q);
    });
  }, [stores, search, statusFilter]);

  // ── fetch store list ──────────────────────────────────────────────────────

  useEffectS(() => {
    if (!sb) return;
    setLoading(true);
    sb.from("stores")
      .select("*, user_profiles(username, display_name, email)")
      .order("created_at", { ascending: false })
      .limit(60)
      .then(({ data, error }) => {
        if (!error && data) {
          setStores(data);
          const active = data.filter(s => s.status === "active").length;
          setPlatformStats(p => ({ ...p, activeStores: active }));
          if (data.length > 0) setStoreId(data[0].id);
        }
        setLoading(false);
      });
  }, []);

  // ── fetch store detail ────────────────────────────────────────────────────

  useEffectS(() => {
    if (!sb || !store) return;
    if (!store.seller_id) return;
    setDetailLoading(true);

    const now = new Date();
    const days = range === "1W" ? 7 : range === "1M" ? 30 : range === "3M" ? 90 : range === "6M" ? 180 : range === "1Y" ? 365 : 730;
    const curStart = new Date(now.getTime() - days * 86400000).toISOString();
    const prevStart = new Date(now.getTime() - 2 * days * 86400000).toISOString();

    Promise.all([
      sb.from("products").select("id").eq("store_id", store.id),
      sb.from("products").select("id").eq("store_id", store.id).eq("status", "active"),
      sb.from("orders")
        .select("id, buyer_id, order_status, total_amount, platform_fee_amount, created_at, order_items(*)")
        .eq("store_id", store.id)
        .gte("created_at", prevStart),
      sb.from("user_profiles").select("*").eq("id", store.seller_id).single(),
      sb.from("products").select("id, name, image_url, price, status, rating, review_count").eq("store_id", store.id),
    ]).then(([productsRes, activeProductsRes, allOrdersRes, ownerRes, allProductsRes]) => {
      const allOrders = allOrdersRes.data || [];
      const curOrders = allOrders.filter(o => o.created_at && new Date(o.created_at) >= new Date(curStart));
      const prevOrders = allOrders.filter(o => o.created_at && new Date(o.created_at) < new Date(curStart));

      const revenue = curOrders.reduce((s, o) => s + Number(o.total_amount || 0), 0);
      const prevRevenue = prevOrders.reduce((s, o) => s + Number(o.total_amount || 0), 0);
      const platformFees = curOrders.reduce((s, o) => s + Number(o.platform_fee_amount || 0), 0);
      const takeRate = revenue > 0 ? (platformFees / revenue) * 100 : 0;

      // rating
      let storeRating = 0, totalReviews = 0;
      if (allProductsRes.data) {
        let ws = 0;
        allProductsRes.data.forEach(p => {
          const r = Number(p.rating) || 0;
          const rc = Number(p.review_count) || 0;
          if (r > 0 && rc > 0) { ws += r * rc; totalReviews += rc; }
        });
        storeRating = totalReviews > 0 ? ws / totalReviews : 0;
      }

      // top products by revenue
      const productCounts = {};
      curOrders.forEach(o => {
        (o.order_items || []).forEach(item => {
          if (item.product_id) {
            const e = productCounts[item.product_id] || { count: 0, revenue: 0 };
            e.count += item.quantity || 1;
            e.revenue += Number(item.total_price || 0);
            productCounts[item.product_id] = e;
          }
        });
      });
      const topIds = Object.entries(productCounts)
        .sort(([, a], [, b]) => b.revenue - a.revenue)
        .slice(0, 5)
        .map(([id]) => id);

      // Fall back to product_snapshot name if product no longer in catalog
      const topProducts = topIds.map(id => {
        const p = (allProductsRes.data || []).find(x => x.id === id);
        const snapshot = curOrders.flatMap(o => o.order_items || []).find(i => i.product_id === id)?.product_snapshot;
        const name = p?.name || snapshot?.name || "—";
        const image_url = p?.image_url || (snapshot?.images?.[0]) || null;
        return { id, name, image_url, orderCount: productCounts[id].count, orderRevenue: productCounts[id].revenue };
      });

      const recentOrders = [...curOrders]
        .sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime())
        .slice(0, 7);

      setExtraInfo({
        products: (productsRes.data || []).length,
        activeProducts: (activeProductsRes.data || []).length,
        orders: curOrders.length,
        revenue,
        prevRevenue,
        rating: storeRating,
        reviews: totalReviews,
        owner: ownerRes.data,
        averageOrderValue: curOrders.length > 0 ? revenue / curOrders.length : 0,
        topProducts,
        recentOrders,
        revenueData: buildRevenueData(allOrders, range),
        takeRate,
      });
      setDetailLoading(false);
    });
  }, [storeId, range]);

  // ── derived chart data ────────────────────────────────────────────────────

  const rev = useMemoS(() => extraInfo.revenueData.map(d => d.revenue), [extraInfo.revenueData]);
  const revPrev = useMemoS(() => extraInfo.revenueData.map(d => d.prev), [extraInfo.revenueData]);
  const labels = useMemoS(() => extraInfo.revenueData.map(d => d.label), [extraInfo.revenueData]);

  const totalRevenue = rev.reduce((a, b) => a + b, 0);
  const prevTotal = revPrev.reduce((a, b) => a + b, 0);

  const revenuePct = extraInfo.prevRevenue > 0
    ? ((extraInfo.revenue - extraInfo.prevRevenue) / extraInfo.prevRevenue * 100)
    : 0;

  // ── render ────────────────────────────────────────────────────────────────

  return (
    <div className="page" data-screen-label="04 Stores">
      <div className="page-h">
        <div>
          <div className="ts">
            {loading ? "Loading…" : `${platformStats.activeStores} active stores · ${platformStats.pendingInvitations} pending invitation · Khalti gateway healthy`}
          </div>
          <h1>Stores</h1>
        </div>
        <div className="acts">
          <button className="btn"><I.download size={12}/>Export</button>
          <button className="btn"><I.plus size={12}/>Invite store</button>
        </div>
      </div>

      <div className="mob-stack" style={{display:"grid", gridTemplateColumns:"300px 1fr", gap:14}}>
        {/* LEFT: store list */}
        <div className="panel" style={{height:"calc(100vh - 180px)", minHeight: 540, display:"flex", flexDirection:"column", overflow:"hidden"}}>
          {/* Search bar */}
          <div style={{padding:"8px 10px", borderBottom:"1px solid var(--hairline)", position:"relative"}}>
            <I.search size={12} style={{position:"absolute", left:20, top:"50%", transform:"translateY(-50%)", color:"var(--ink-4)", pointerEvents:"none"}}/>
            <input
              value={search}
              onChange={e => setSearch(e.target.value)}
              placeholder="Search stores…"
              style={{
                width:"100%", paddingLeft:28, paddingRight:8, height:28,
                background:"var(--surface-2)", border:"1px solid var(--hairline)",
                borderRadius:5, fontSize:12, color:"var(--ink)", outline:"none",
                fontFamily:"var(--font-sans)", boxSizing:"border-box"
              }}
            />
          </div>
          {/* Filter bar */}
          <div style={{display:"flex", gap:4, padding:"6px 10px", borderBottom:"1px solid var(--hairline)", flexWrap:"wrap"}}>
            {[["all","All"],["active","Live"],["suspended","Suspended"],["draft","Draft"]].map(([val, label]) => (
              <span key={val}
                onClick={() => setStatusFilter(val)}
                className="chip"
                style={{
                  cursor:"pointer", fontSize:11,
                  background: statusFilter === val ? "var(--accent-soft)" : undefined,
                  color: statusFilter === val ? "var(--accent-ink)" : undefined,
                  borderColor: statusFilter === val ? "transparent" : undefined,
                }}>{label}</span>
            ))}
          </div>
          <div style={{overflow:"auto", flex:1}}>
            {loading ? (
              <div style={{padding:"24px", textAlign:"center", color:"var(--ink-3)", fontSize:12}}>Loading stores…</div>
            ) : visibleStores.length === 0 ? (
              <div style={{padding:"24px", textAlign:"center", color:"var(--ink-3)", fontSize:12}}>No stores found</div>
            ) : visibleStores.map((s) => {
              const sel = s.id === storeId;
              const statusIsLive = s.status === "active";
              return (
                <div key={s.id}
                  onClick={() => setStoreId(s.id)}
                  style={{
                    display:"grid", gridTemplateColumns:"30px 1fr auto", gap:10,
                    alignItems:"center", padding:"10px 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)"}}/>}
                  {s.logo_url ? (
                    <img src={s.logo_url} alt={s.name} style={{width:30, height:30, borderRadius:4, objectFit:"cover"}}/>
                  ) : (
                    <div style={{width:30,height:30,borderRadius:4,background:"var(--surface-3)",display:"grid",placeItems:"center",color:"var(--ink-3)",fontSize:12,fontWeight:600}}>{s.name[0]}</div>
                  )}
                  <div style={{minWidth:0}}>
                    <div style={{fontWeight:500, color:"var(--ink)", fontSize:12.5, whiteSpace:"nowrap", overflow:"hidden", textOverflow:"ellipsis"}}>{s.name}</div>
                    <div className="muted" style={{fontSize:11, fontFamily:"var(--font-mono)", whiteSpace:"nowrap", overflow:"hidden", textOverflow:"ellipsis"}}>{s.category || s.business_type || ""}</div>
                  </div>
                  {statusIsLive
                    ? <span className="chip pos dot" style={{flexShrink:0}}>live</span>
                    : <span className="chip warn dot" style={{flexShrink:0}}>{s.status || "draft"}</span>}
                </div>
              );
            })}
          </div>
        </div>

        {/* RIGHT: store detail */}
        {!store ? (
          <div className="panel" style={{display:"flex", alignItems:"center", justifyContent:"center", color:"var(--ink-3)", fontSize:13}}>
            {loading ? "Loading…" : "Select a store"}
          </div>
        ) : (
          <div style={{display:"flex", flexDirection:"column", gap:14}}>
            {/* Store header */}
            <div className="panel">
              <div style={{padding:"18px 20px", display:"flex", alignItems:"flex-start", gap:16}}>
                {store.logo_url ? (
                  <img src={store.logo_url} alt={store.name} style={{width:60, height:60, borderRadius:6, objectFit:"cover"}}/>
                ) : (
                  <div style={{width:60, height:60, borderRadius:6}} className="ph-img">{store.name.split(" ").map(s=>s[0]).join("")}</div>
                )}
                <div style={{flex:1, minWidth:0}}>
                  <div style={{display:"flex", alignItems:"center", gap:10}}>
                    <h2 style={{margin:0, fontSize:20, fontWeight:550, letterSpacing:"-0.01em"}}>{store.name}</h2>
                    {store.verification_status === "verified" && <span className="chip pos dot">verified</span>}
                    {store.category && <span className="chip">{store.category}</span>}
                  </div>
                  <div className="muted" style={{fontSize:12, marginTop:4, fontFamily:"var(--font-mono)"}}>
                    {store.slug ? `STR-${store.slug.slice(-3).toUpperCase()}` : store.id}
                    {extraInfo.owner && ` · owner: ${extraInfo.owner.display_name || extraInfo.owner.username || ""}`}
                    {store.created_at && ` · joined ${new Date(store.created_at).toLocaleDateString("en-US", {month:"short", year:"numeric"})}`}
                  </div>
                </div>
                {store.phone ? (
                  <a href={`tel:${store.phone}`} className="btn" style={{fontFamily:"var(--font-mono)", fontSize:12}}>
                    <I.message size={11}/>{store.phone}
                  </a>
                ) : null}
              </div>
              <div style={{display:"grid", gridTemplateColumns:"repeat(5, 1fr)", borderTop:"1px solid var(--hairline)"}}>
                <SmallStat label="GMV · 30d"   value={D.compactCurrency(extraInfo.revenue)} delta={revenuePct !== 0 ? `${revenuePct > 0 ? "+" : ""}${revenuePct.toFixed(1)}%` : "flat"} tone={revenuePct > 0 ? "up" : revenuePct < 0 ? "dn" : "flat"}/>
                <SmallStat label="Orders"      value={extraInfo.orders.toLocaleString()} delta="" tone="flat"/>
                <SmallStat label="AOV"         value={D.compactCurrency(extraInfo.averageOrderValue)} delta="" tone="flat"/>
                <SmallStat label="Take rate"   value={`${extraInfo.takeRate.toFixed(1)}%`} delta="flat" tone="flat"/>
                <SmallStat label="Rating"      value={extraInfo.rating > 0 ? `${extraInfo.rating.toFixed(1)} ★` : "—"} delta={extraInfo.reviews > 0 ? `${extraInfo.reviews} reviews` : ""} tone="flat" muted/>
              </div>
            </div>

            {/* Chart */}
            <div className="panel">
              <div className="panel-h">
                <span>Revenue</span>
                <div className="right">
                  <div className="row gap-2">
                    {["1W","1M","3M","6M","1Y","ALL"].map(r =>
                      <span key={r}
                        onClick={()=>setRange(r)}
                        className="chip"
                        style={{
                          cursor:"pointer",
                          background: r===range ? "var(--accent-soft)" : undefined,
                          color: r===range ? "var(--accent-ink)" : undefined,
                          borderColor: r===range ? "transparent" : undefined,
                        }}>{r}</span>
                    )}
                  </div>
                  <span className="vhairline" style={{height:14}}/>
                  <span className="chip dot" onClick={()=>setCompare(c=>!c)} style={{cursor:"pointer", background: compare?"var(--surface-2)":"transparent"}}>
                    Compare
                  </span>
                </div>
              </div>
              <div style={{padding:"14px"}}>
                <div className="row gap-6" style={{marginBottom:8}}>
                  <div>
                    <div className="lbl-mini" style={{fontFamily:"var(--font-mono)", fontSize:9.5, color:"var(--ink-3)", letterSpacing:"0.06em", textTransform:"uppercase"}}>This period</div>
                    <div style={{fontSize:22, fontWeight:550, letterSpacing:"-0.01em", marginTop:2, fontFamily:"var(--font-sans)", fontFeatureSettings:'"tnum" 1'}}>{D.compactCurrency(totalRevenue)}</div>
                  </div>
                  {compare && (
                    <div>
                      <div className="lbl-mini" style={{fontFamily:"var(--font-mono)", fontSize:9.5, color:"var(--ink-3)", letterSpacing:"0.06em", textTransform:"uppercase"}}>Previous</div>
                      <div className="muted" style={{fontSize:22, fontWeight:500, letterSpacing:"-0.01em", marginTop:2, fontFamily:"var(--font-sans)", fontFeatureSettings:'"tnum" 1'}}>{D.compactCurrency(prevTotal)}</div>
                    </div>
                  )}
                  <div style={{marginLeft:"auto", display:"flex", gap:14, alignItems:"center"}}>
                    <Legend color="var(--accent)" label="This period"/>
                    {compare && <Legend color="var(--ink-4)" label="Previous"/>}
                  </div>
                </div>
                {detailLoading ? (
                  <div style={{height:240, display:"flex", alignItems:"center", justifyContent:"center", color:"var(--ink-3)", fontSize:12}}>Loading…</div>
                ) : rev.length < 2 ? (
                  <div style={{height:240, display:"flex", alignItems:"center", justifyContent:"center", color:"var(--ink-3)", fontSize:12}}>No revenue data</div>
                ) : (
                  <DualAreaChart current={rev} previous={compare ? revPrev : null} labels={labels} height={240}/>
                )}
              </div>
            </div>

            {/* Products + Recent orders side-by-side */}
            <div className="mob-stack" style={{display:"grid", gridTemplateColumns:"1fr 1fr", gap:14}}>
              <div className="panel">
                <div className="panel-h">
                  <span>Top products</span>
                  <span className="meta">last 30 days</span>
                </div>
                <div className="t-wrap"><table className="t">
                  <thead><tr><th>Product</th><th style={{textAlign:"right"}}>Sold</th><th style={{textAlign:"right"}}>Revenue</th></tr></thead>
                  <tbody>
                    {extraInfo.topProducts.map(p => (
                      <tr key={p.id}>
                        <td>
                          <div className="row gap-2">
                            {p.image_url ? (
                              <img src={p.image_url} alt={p.name} style={{width:24, height:24, borderRadius:3, objectFit:"cover"}}/>
                            ) : (
                              <div style={{width:24,height:24,borderRadius:3}} className="ph-img"></div>
                            )}
                            <span>{p.name || "—"}</span>
                          </div>
                        </td>
                        <td className="num" style={{textAlign:"right", whiteSpace:"nowrap"}}>{p.orderCount}</td>
                        <td className="num" style={{textAlign:"right", whiteSpace:"nowrap", color:"var(--ink)"}}>{D.compactCurrency(p.orderRevenue || 0)}</td>
                      </tr>
                    ))}
                  </tbody>
                </table></div>
              </div>
              <div className="panel">
                <div className="panel-h">
                  <span>Recent orders</span>
                  <div className="right"><button className="btn ghost" style={{height:24}}>All <I.arrowR size={11}/></button></div>
                </div>
                {extraInfo.recentOrders.length === 0 ? (
                  <div style={{padding:"24px", textAlign:"center", color:"var(--ink-3)", fontSize:12}}>No orders</div>
                ) : (
                  <div className="t-wrap"><table className="t">
                    <thead><tr><th>Order</th><th>Buyer</th><th>Status</th><th style={{textAlign:"right"}}>Total</th></tr></thead>
                    <tbody>
                      {extraInfo.recentOrders.map(o => (
                        <RecentOrderRow key={o.id} order={o}/>
                      ))}
                    </tbody>
                  </table></div>
                )}
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

// ── RecentOrderRow with lazy buyer name ────────────────────────────────────────

const RecentOrderRow = ({ order }) => {
  const D = window.PipalData;
  const sb = window.supabaseClient;
  const [buyerName, setBuyerName] = useStateS(null);

  useEffectS(() => {
    if (!order.buyer_id || !sb) return;
    sb.from("user_profiles")
      .select("display_name, username")
      .eq("id", order.buyer_id)
      .single()
      .then(({ data }) => {
        if (data) setBuyerName(data.display_name || data.username || null);
      });
  }, [order.buyer_id]);

  const status = order.order_status || "pending";
  const chipTone = status === "delivered" ? "pos"
    : status === "cancelled" ? "neg"
    : status === "shipped" ? "accent"
    : "warn";
  const label = status === "shipped" ? "in transit" : status.replace("_", " ");

  return (
    <tr>
      <td><span className="id" style={{color:"var(--ink)"}}>{String(order.id).slice(0, 7).toUpperCase()}</span></td>
      <td>{buyerName || "—"}</td>
      <td><span className={`chip dot ${chipTone}`}>{label}</span></td>
      <td className="num" style={{textAlign:"right", whiteSpace:"nowrap"}}>{D.compactCurrency(Number(order.total_amount || 0))}</td>
    </tr>
  );
};

// ── Legend ─────────────────────────────────────────────────────────────────────

const Legend = ({color, label}) => (
  <div className="row gap-2" style={{fontSize:11, color:"var(--ink-3)", fontFamily:"var(--font-mono)"}}>
    <span style={{width:12, height:2, background:color, borderRadius:1}}/>{label}
  </div>
);

// ── SmallStat ──────────────────────────────────────────────────────────────────

const SmallStat = ({label, value, delta, tone="flat", muted}) => {
  const I = window.Icons;
  return (
    <div style={{padding:"14px 18px", borderRight:"1px solid var(--hairline)", minWidth:0, overflow:"hidden"}}>
      <div className="lbl-mini" style={{fontFamily:"var(--font-mono)", fontSize:9.5, color:"var(--ink-3)", letterSpacing:"0.06em", textTransform:"uppercase"}}>{label}</div>
      <div style={{fontSize:18, fontWeight:550, marginTop:4, color:"var(--ink)", letterSpacing:"-0.01em", fontFamily:"var(--font-sans)", fontFeatureSettings:'"tnum" 1', whiteSpace:"nowrap", overflow:"hidden", textOverflow:"ellipsis"}}>{value}</div>
      <div className={"delta " + (tone==="up"?"up":tone==="dn"?"dn":"flat")} style={{marginTop:2}}>
        {tone==="up" && <I.arrowUp size={9}/>}{tone==="dn" && <I.arrowDn size={9}/>}{delta}
      </div>
    </div>
  );
};

// ── DualAreaChart ──────────────────────────────────────────────────────────────

const DualAreaChart = ({ current, previous, labels, height = 220 }) => {
  const ref = useRefS(null);
  const [w, setW] = useStateS2(600);
  useEffectS(() => {
    if (!ref.current) return;
    const ro = new ResizeObserver(([e]) => setW(e.contentRect.width));
    ro.observe(ref.current);
    return () => ro.disconnect();
  }, []);
  const id = useIdS().replace(/:/g,"");
  const padL=44,padR=8,padT=14,padB=22;
  const innerW = w-padL-padR;
  const innerH = height-padT-padB;
  const all = previous ? [...current, ...previous] : current;
  const min = Math.min(...all), max = Math.max(...all);
  const range = max - min || 1;
  const ticks = Array.from({length:5}, (_,i)=>min + (range*i)/4);

  const linePath = (data) => {
    return data.map((v,i) => {
      const x = padL + (i/(data.length-1)) * innerW;
      const y = padT + innerH - ((v-min)/range) * innerH;
      return `${i===0?"M":"L"} ${x.toFixed(2)} ${y.toFixed(2)}`;
    }).join(" ");
  };
  const areaPath = (data) => `${linePath(data)} L ${padL+innerW} ${padT+innerH} L ${padL} ${padT+innerH} Z`;

  return (
    <div ref={ref} style={{width:"100%", height}}>
      <svg width={w} height={height} style={{display:"block"}}>
        <defs>
          <linearGradient id={"sa"+id} x1="0" y1="0" x2="0" y2="1">
            <stop offset="0" stopColor="var(--accent)" stopOpacity="0.20"/>
            <stop offset="1" stopColor="var(--accent)" stopOpacity="0"/>
          </linearGradient>
        </defs>
        {ticks.map((t,i) => {
          const y = padT + innerH - ((t-min)/range)*innerH;
          return (
            <g key={i}>
              <line x1={padL} x2={w-padR} y1={y} y2={y} stroke="var(--hairline)"/>
              <text x={padL-8} y={y+3} textAnchor="end" fill="var(--ink-3)" fontFamily="var(--font-mono)" fontSize="9.5">{window.PipalData.compactCurrency(t)}</text>
            </g>
          );
        })}
        {labels.map((l,i)=> i % Math.max(1, Math.floor(labels.length/8))===0 ? (
          <text key={i} x={padL + (i/(labels.length-1))*innerW} y={height-6} textAnchor="middle" fill="var(--ink-3)" fontFamily="var(--font-mono)" fontSize="9.5">{l}</text>
        ) : null)}

        {previous && (
          <path d={linePath(previous)} fill="none" stroke="var(--ink-4)" strokeWidth="1.25" strokeDasharray="3 3"/>
        )}
        <path d={areaPath(current)} fill={"url(#sa"+id+")"}/>
        <path d={linePath(current)} fill="none" stroke="var(--accent)" strokeWidth="1.5"/>
      </svg>
    </div>
  );
};

window.StoresPage = StoresPage;
