// =============================================================================
// STORE TAB — Etsy/Printify.
// Top-line metrics, top listings, agent team, escalations, trends,
// store-boss conversation (shared with Dashboard via useShared).
// =============================================================================

(function () {
  const { C } = window.JD_THEME;
  const { card, ct, inp, bg, bgg, Empty, Loading, ErrorBox } = window.JD_STYLES;

  function Store() {
    const storeQ = window.useJarvisData("store");
    const s = storeQ.data || {};
    const { storeMsg, setStoreMsg, storeMsgs, sendStoreBoss } = window.useShared();

    const listings = s.listings_top || s.listings || [];
    const isListingsArr = Array.isArray(listings);
    const listingsArr = isListingsArr && typeof listings[0] === "object" ? listings : [];

    return (
      <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
        {storeQ.error && <ErrorBox message={storeQ.error.message} />}
        <div style={{ display: "grid", gridTemplateColumns: "repeat(6,1fr)", gap: 10 }}>
          {[
            ["Revenue MTD", s.revenueMTD, C.green],
            ["Expenses",    s.expenses,   C.red],
            ["Net",         s.net,        C.green],
            ["Orders",      s.orders,     C.gold],
            ["Listings",    typeof s.listings === "string" ? s.listings : (listingsArr.length || null), C.blue],
            ["Traffic 7d",  s.traffic,    C.purple],
          ].map(([l, v, c]) => (
            <div key={l} style={card({ textAlign: "center" })}>
              <div style={{ fontSize: 11, color: C.muted, letterSpacing: "0.14em", textTransform: "uppercase", marginBottom: 4 }}>{l}</div>
              <div style={{ fontSize: 24, color: v ? c : C.muted, fontVariantNumeric: "tabular-nums" }}>{v || "—"}</div>
            </div>
          ))}
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "2fr 1fr", gap: 14 }}>
          <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
            <div style={card()}>
              <div style={ct}>Top Listings · 7-Day Performance</div>
              {storeQ.loading ? <Loading /> :
               listingsArr.length === 0 ? <Empty label="No listings yet" sub="Connect Etsy + Printify via adapter" /> : listingsArr.map((p, i) => (
                <div key={i} style={{ padding: "10px 0", borderBottom: "0.5px solid " + C.border }}>
                  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 6 }}>
                    <div style={{ fontSize: 14, color: C.cream, flex: 1 }}>{p.t}</div>
                    <div style={{ fontSize: 14, color: p.c, fontVariantNumeric: "tabular-nums", marginLeft: 10 }}>{p.rev} <span style={{ color: C.muted, fontSize: 12 }}>· {p.sales} sold</span></div>
                  </div>
                  <div style={{ height: 5, background: "rgba(222,214,185,0.08)", borderRadius: 3, overflow: "hidden" }}>
                    <div style={{ width: ((p.mark || 0) * 100) + "%", height: "100%", background: p.c }} />
                  </div>
                </div>
              ))}
            </div>
            <div style={card()}>
              <div style={ct}>Agent Team Status</div>
              {(s.agents || []).length === 0 ? <Empty label="No agents registered" /> : (s.agents || []).map((a, i) => (
                <div key={i} style={{ display: "flex", alignItems: "center", gap: 12, padding: "10px 0", borderBottom: "0.5px solid " + C.border }}>
                  <div style={{ width: 8, height: 8, borderRadius: "50%", background: a.c, flexShrink: 0 }} />
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 15, color: C.cream }}>{a.n}</div>
                    <div style={{ fontSize: 13, color: a.c, marginTop: 2 }}>{a.s}</div>
                  </div>
                  <span style={{ fontSize: 12, padding: "3px 10px", borderRadius: 10, background: a.c + "18", color: a.c, border: "0.5px solid " + a.c + "30" }}>{a.load}</span>
                </div>
              ))}
            </div>
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
            <div style={card({ border: "0.5px solid rgba(224,82,82,0.3)" })}>
              <div style={{ fontSize: 12, color: C.red, letterSpacing: "0.18em", textTransform: "uppercase", marginBottom: 10 }}>Customer Queue · {(s.escalations || []).length} Escalation{(s.escalations || []).length === 1 ? "" : "s"}</div>
              {(s.escalations || []).length === 0 ? <Empty label="No escalations" /> : (s.escalations || []).map((e, i) => (
                <div key={i} style={{ padding: "10px 12px", background: "rgba(224,82,82,0.08)", borderRadius: 8, border: "0.5px solid rgba(224,82,82,0.2)", marginBottom: 6 }}>
                  <div style={{ fontSize: 14, color: C.cream, marginBottom: 3 }}>{e.summary}</div>
                  <div style={{ fontSize: 12, color: C.muted, marginBottom: 8 }}>Order #{e.orderId} · {e.openFor} open · {e.customer}</div>
                  <div style={{ display: "flex", gap: 6 }}>
                    <button onClick={() => window.JD.mutate("approveRefund", e.orderId).then(() => storeQ.reload())} style={bgg}>Approve refund</button>
                    <button style={{ ...bg, fontSize: 12 }}>Reply</button>
                  </div>
                </div>
              ))}
            </div>
            <div style={card()}>
              <div style={ct}>Talk to Store Boss</div>
              <div style={{ maxHeight: 160, overflow: "auto", marginBottom: 8, padding: "6px 0" }}>
                {storeMsgs.length === 0 && <div style={{ fontSize: 13, color: C.muted, fontStyle: "italic", textAlign: "center", padding: "12px 0" }}>No messages yet</div>}
                {storeMsgs.map((m, i) => (
                  <div key={i} style={{ marginBottom: 8, padding: "6px 8px", background: m.role === "user" ? "rgba(159,117,9,0.06)" : "rgba(139,127,212,0.06)", borderRadius: 6, border: "0.5px solid " + (m.role === "user" ? "rgba(159,117,9,0.15)" : "rgba(139,127,212,0.15)") }}>
                    <div style={{ fontSize: 11, color: m.role === "user" ? C.gold : C.purple, letterSpacing: "0.1em", textTransform: "uppercase", marginBottom: 2 }}>{m.role === "user" ? "You" : "Store Boss"}</div>
                    <div style={{ fontSize: 14, color: "rgba(222,214,185,0.82)", lineHeight: 1.5 }}>{m.msg}</div>
                  </div>
                ))}
              </div>
              <div style={{ display: "flex", gap: 6 }}>
                <input value={storeMsg} onChange={e => setStoreMsg(e.target.value)} onKeyDown={e => e.key === "Enter" && sendStoreBoss()} placeholder="Instruct boss agent..." style={{ ...inp, flex: 1 }} />
                <button onClick={sendStoreBoss} style={bg}>Send</button>
              </div>
            </div>
            <div style={card()}>
              <div style={ct}>Trending POD Niches</div>
              {(s.trends || []).length === 0 ? <Empty label="No trend data" /> : (s.trends || []).map(([n, d, c]) => (
                <div key={n} style={{ display: "flex", justifyContent: "space-between", padding: "7px 0", borderBottom: "0.5px solid " + C.border, fontSize: 14 }}>
                  <span style={{ color: "rgba(222,214,185,0.82)" }}>{n}</span>
                  <span style={{ color: c, fontVariantNumeric: "tabular-nums" }}>{d}</span>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    );
  }

  window.JD_TABS = window.JD_TABS || {};
  window.JD_TABS.Store = Store;
})();
