// ════════════════════════════════════════════════════════════════════════════
//  Entity Links & Overlay
//  ---------------------------------------------------------------------------
//  A global, page-agnostic system so any reference to an entity (order, store,
//  product, user/driver, delivery) is clickable everywhere and opens that
//  entity's detail in a right-side drawer — without navigating away.
//
//  Usage:
//    <EntityLink type="order"   id={id} label={orderNumber} />
//    <EntityLink type="store"   id={storeId} label={name} />
//    <EntityLink type="product" id={productId} label={name} />
//    <EntityLink type="user"    id={userId} label={name} />
//    <EntityLink type="delivery" id={deliveryId} label={tracking} />
//
//  Or imperatively:  window.openEntity("order", id)
// ════════════════════════════════════════════════════════════════════════════

const { useState: useStateE, useEffect: useEffectE, useCallback: useCallbackE } = React;

// ── Global drawer store (tiny pub/sub, back-stack of {type,id}) ────────────────

const EntityStore = (() => {
  let stack = [];              // [{ type, id }]
  const subs = new Set();
  const emit = () => subs.forEach(fn => fn(stack));
  return {
    subscribe(fn) { subs.add(fn); return () => subs.delete(fn); },
    getStack() { return stack; },
    open(type, id) {
      if (!type || !id) return;
      const top = stack[stack.length - 1];
      if (top && top.type === type && String(top.id) === String(id)) return; // no-op dup
      stack = [...stack, { type, id }];
      emit();
    },
    back() { stack = stack.slice(0, -1); emit(); },
    close() { stack = []; emit(); },
  };
})();

// Imperative global entry point — usable from anywhere, even non-React code.
window.openEntity = (type, id) => EntityStore.open(type, id);

// ── Clickable reference ────────────────────────────────────────────────────────

const EntityLink = ({ type, id, label, children, mono = true, style = {} }) => {
  if (!id) return <span style={style}>{children ?? label ?? "—"}</span>;
  const onClick = (e) => { e.stopPropagation(); EntityStore.open(type, id); };
  return (
    <span
      className="entity-link"
      onClick={onClick}
      title={`Open ${type}`}
      style={{ fontFamily: mono ? "var(--font-mono)" : "inherit", ...style }}
    >
      {children ?? label ?? String(id).slice(0, 8).toUpperCase()}
    </span>
  );
};

// ── Drawer host (mounted once in App) ──────────────────────────────────────────

const TYPE_META = {
  order:    { label: "Order",    icon: "cart" },
  store:    { label: "Store",    icon: "store" },
  product:  { label: "Product",  icon: "package" },
  user:     { label: "User",     icon: "users" },
  delivery: { label: "Delivery", icon: "truck" },
};

const EntityDrawer = () => {
  const I = window.Icons;
  const [stack, setStack] = useStateE(EntityStore.getStack());

  useEffectE(() => EntityStore.subscribe(setStack), []);

  // Esc closes the top of the stack.
  useEffectE(() => {
    const onKey = (e) => {
      if (e.key === "Escape" && EntityStore.getStack().length) {
        e.stopPropagation();
        EntityStore.back();
      }
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, []);

  const open = stack.length > 0;
  const cur = stack[stack.length - 1];
  const meta = cur ? (TYPE_META[cur.type] || { label: cur.type, icon: "layers" }) : null;
  const Icon = meta ? (I[meta.icon] || I.layers) : null;

  return (
    <>
      <div
        className={"entity-overlay-backdrop" + (open ? " open" : "")}
        onClick={() => EntityStore.close()}
      />
      <div className={"entity-drawer" + (open ? " open" : "")} role="dialog" aria-modal="true">
        {cur && (
          <>
            <div className="entity-drawer-head">
              {stack.length > 1 ? (
                <button className="icon-btn" title="Back" onClick={() => EntityStore.back()}>
                  <I.arrowR size={15} style={{ transform: "rotate(180deg)" }} />
                </button>
              ) : (
                <span className="entity-drawer-kind">
                  {Icon && <Icon size={14} />}
                </span>
              )}
              <span className="entity-drawer-title">{meta.label}</span>
              {stack.length > 1 && (
                <span className="entity-drawer-depth">{stack.length}</span>
              )}
              <div style={{ marginLeft: "auto", display: "flex", gap: 6 }}>
                <button className="icon-btn" title="Close" onClick={() => EntityStore.close()}>
                  <I.x size={15} />
                </button>
              </div>
            </div>
            <div className="entity-drawer-body" key={`${cur.type}:${cur.id}:${stack.length}`}>
              <EntityView type={cur.type} id={cur.id} />
            </div>
          </>
        )}
      </div>
    </>
  );
};

// ── Dispatcher ─────────────────────────────────────────────────────────────────

const EntityView = ({ type, id }) => {
  switch (type) {
    case "order":    return <OrderEntityView id={id} />;
    case "store":    return <StoreEntityView id={id} />;
    case "product":  return <ProductEntityView id={id} />;
    case "user":     return <UserEntityView id={id} />;
    case "delivery": return <DeliveryEntityView id={id} />;
    default:         return <ViewMsg>Unknown entity type “{type}”.</ViewMsg>;
  }
};

// ── Shared view primitives ─────────────────────────────────────────────────────

const ViewMsg = ({ children }) => (
  <div style={{ padding: 24, color: "var(--ink-3)", fontSize: 12.5 }}>{children}</div>
);

const ViewLoading = () => (
  <div style={{ padding: 24, color: "var(--ink-3)", fontSize: 11, fontFamily: "var(--font-mono)", textTransform: "uppercase", letterSpacing: "0.1em" }}>
    Loading…
  </div>
);

const ESection = ({ title, right, children }) => (
  <div style={{ padding: "14px 16px", borderBottom: "1.5px solid var(--hairline-soft)" }}>
    <div style={{ display: "flex", alignItems: "center", marginBottom: 10 }}>
      <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, fontWeight: 700, color: "var(--ink-3)", letterSpacing: "0.1em", textTransform: "uppercase" }}>{title}</div>
      {right && <div style={{ marginLeft: "auto" }}>{right}</div>}
    </div>
    {children}
  </div>
);

const EKv = ({ k, v }) => (
  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", gap: 12, padding: "4px 0" }}>
    <span className="muted" style={{ fontSize: 11.5 }}>{k}</span>
    <span style={{ fontSize: 12.5, fontWeight: 600, color: "var(--ink)", textAlign: "right" }}>{v}</span>
  </div>
);

// A big headline value block at the top of a view.
const EHero = ({ value, sub, chip }) => (
  <div style={{ padding: "16px", borderBottom: "1.5px solid var(--hairline)" }}>
    <div style={{ display: "flex", alignItems: "flex-start", gap: 12 }}>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 26, fontWeight: 700, letterSpacing: "-0.03em", color: "var(--ink)", lineHeight: 1 }}>{value}</div>
        {sub && <div className="muted" style={{ fontSize: 11.5, marginTop: 6, fontFamily: "var(--font-mono)" }}>{sub}</div>}
      </div>
      {chip}
    </div>
  </div>
);

// Small stat tile used in grids inside a view.
const ETile = ({ label, value, accent }) => (
  <div style={{ border: "1.5px solid var(--hairline)", padding: "10px 12px" }}>
    <div className="num" style={{ fontSize: 18, fontWeight: 700, letterSpacing: "-0.02em", color: accent || "var(--ink)" }}>{value}</div>
    <div className="muted" style={{ fontSize: 9.5, marginTop: 3, fontFamily: "var(--font-mono)", textTransform: "uppercase", letterSpacing: "0.08em" }}>{label}</div>
  </div>
);

// A person/store row that is itself an entity link.
const ERefRow = ({ type, id, name, sub, initial }) => (
  <div
    onClick={() => id && EntityStore.open(type, id)}
    style={{ display: "flex", alignItems: "center", gap: 10, padding: "8px 10px", border: "1.5px solid var(--hairline)", cursor: id ? "pointer" : "default", background: "var(--surface)" }}
  >
    <div style={{ width: 30, height: 30, flexShrink: 0, display: "grid", placeItems: "center", background: "var(--surface-2)", border: "1.5px solid var(--hairline-2)", fontSize: 12, fontWeight: 700, fontFamily: "var(--font-mono)", color: "var(--ink)" }}>
      {(initial || name || "?")[0]?.toUpperCase()}
    </div>
    <div style={{ minWidth: 0, flex: 1 }}>
      <div style={{ fontSize: 13, fontWeight: 600, color: "var(--ink)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{name || "—"}</div>
      {sub && <div className="muted" style={{ fontSize: 11, fontFamily: "var(--font-mono)" }}>{sub}</div>}
    </div>
    {id && <window.Icons.arrowR size={13} style={{ color: "var(--ink-3)", flexShrink: 0 }} />}
  </div>
);

// ── ORDER view — reuses the real OrderDetail from the Orders page ──────────────

const OrderEntityView = ({ id }) => {
  const sb = window.supabaseClient;
  const D = window.PipalData;
  const I = window.Icons;
  const [order, setOrder] = useStateE(null);
  const [state, setState] = useStateE("loading"); // loading | ok | missing

  const load = useCallbackE(async () => {
    setState("loading");
    // id may be an order UUID or an order_number — resolve both.
    let q = sb.from("orders").select(window.ORDER_SELECT);
    q = /^[0-9a-f]{8}-/i.test(String(id)) ? q.eq("id", id) : q.or(`id.eq.${id},order_number.eq.${id}`);
    const { data } = await q.limit(1);
    const row = data && data[0];
    if (!row) { setState("missing"); return; }
    const [enriched] = await window.enrichOrders(sb, [row]);
    setOrder(enriched);
    setState("ok");
  }, [id]);

  useEffectE(() => { load(); }, [load]);

  if (state === "loading") return <ViewLoading />;
  if (state === "missing") return <ViewMsg>Order not found.</ViewMsg>;

  // window.OrderDetail renders its own panel-h + everything below it.
  const OrderDetail = window.OrderDetail;
  return (
    <div style={{ display: "flex", flexDirection: "column", height: "100%" }}>
      <OrderDetail order={order} D={D} I={I} sb={sb}
        onStatusChange={(oid, status) => setOrder(o => o && o.id === oid ? { ...o, order_status: status } : o)} />
    </div>
  );
};

// ── STORE view ─────────────────────────────────────────────────────────────────

const StoreEntityView = ({ id }) => {
  const sb = window.supabaseClient;
  const D = window.PipalData;
  const [store, setStore] = useStateE(null);
  const [metrics, setMetrics] = useStateE(null);
  const [recent, setRecent] = useStateE([]);
  const [state, setState] = useStateE("loading");

  useEffectE(() => {
    let alive = true;
    (async () => {
      setState("loading");
      const { data: s } = await sb.from("stores")
        .select("id, name, slug, category, logo_url, phone, seller_id, verification_status, created_at")
        .eq("id", id).single();
      if (!alive) return;
      if (!s) { setState("missing"); return; }

      const [{ data: sm }, { data: orders }] = await Promise.all([
        sb.from("seller_metrics").select("total_orders, orders_last_30_days, revenue_last_30_days, avg_rating").eq("store_id", id).maybeSingle(),
        sb.from("orders").select("id, order_number, total_amount, order_status, created_at").eq("store_id", id).order("created_at", { ascending: false }).limit(6),
      ]);
      if (!alive) return;
      setStore(s); setMetrics(sm || null); setRecent(orders || []); setState("ok");
    })();
    return () => { alive = false; };
  }, [id]);

  if (state === "loading") return <ViewLoading />;
  if (state === "missing") return <ViewMsg>Store not found.</ViewMsg>;

  const chip = { verified: "pos", pending: "warn", unverified: "warn", rejected: "neg" }[store.verification_status] || "warn";

  return (
    <div>
      <EHero
        value={store.name}
        sub={`${store.category || "—"}${store.slug ? " · " + store.slug : ""}`}
        chip={<span className={`chip dot ${chip}`}>{store.verification_status || "unverified"}</span>}
      />
      {metrics && (
        <div style={{ padding: 16, borderBottom: "1.5px solid var(--hairline)", display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
          <ETile label="Revenue 30d" value={D.compactCurrency(Number(metrics.revenue_last_30_days || 0))} />
          <ETile label="Orders 30d" value={metrics.orders_last_30_days ?? 0} />
          <ETile label="Total orders" value={metrics.total_orders ?? 0} />
          <ETile label="Rating" value={metrics.avg_rating ? Number(metrics.avg_rating).toFixed(1) : "—"} accent="var(--warn)" />
        </div>
      )}
      <ESection title="Owner">
        <ERefRow type="user" id={store.seller_id} name="Store owner" sub={store.phone || (store.seller_id ? String(store.seller_id).slice(0, 8).toUpperCase() : "—")} initial="O" />
      </ESection>
      <ESection title="Details">
        <EKv k="Store ID" v={<span className="id">{String(store.id).slice(0, 8).toUpperCase()}</span>} />
        {store.phone && <EKv k="Phone" v={store.phone} />}
        <EKv k="Created" v={new Date(store.created_at).toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" })} />
      </ESection>
      <ESection title={`Recent orders (${recent.length})`}>
        {recent.length === 0
          ? <div className="muted" style={{ fontSize: 12 }}>No orders</div>
          : recent.map(o => (
            <div key={o.id} style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "6px 0", gap: 8 }}>
              <EntityLink type="order" id={o.id} label={o.order_number || String(o.id).slice(0, 8).toUpperCase()} style={{ fontSize: 12 }} />
              <span className="num" style={{ fontSize: 12, fontWeight: 600 }}>{D.compactCurrency(Number(o.total_amount || 0))}</span>
            </div>
          ))}
      </ESection>
    </div>
  );
};

// ── PRODUCT view ───────────────────────────────────────────────────────────────

const ProductEntityView = ({ id }) => {
  const sb = window.supabaseClient;
  const D = window.PipalData;
  const [p, setP] = useStateE(null);
  const [state, setState] = useStateE("loading");

  useEffectE(() => {
    let alive = true;
    (async () => {
      setState("loading");
      const { data } = await sb.from("products")
        .select("id, name, images, price, compare_at_price, status, quantity, low_stock_threshold, sales_count, sku, store_id, created_at, stores(id, name)")
        .eq("id", id).single();
      if (!alive) return;
      if (!data) { setState("missing"); return; }
      setP(data); setState("ok");
    })();
    return () => { alive = false; };
  }, [id]);

  if (state === "loading") return <ViewLoading />;
  if (state === "missing") return <ViewMsg>Product not found.</ViewMsg>;

  const img = Array.isArray(p.images) ? p.images[0] : null;
  const noStock = (p.quantity ?? 0) <= 0;
  const lowStock = !noStock && p.quantity <= (p.low_stock_threshold || 5);
  const stockChip = noStock ? "neg" : lowStock ? "warn" : "pos";
  const stockLabel = noStock ? "out of stock" : lowStock ? "low stock" : "in stock";

  return (
    <div>
      <div style={{ padding: 16, borderBottom: "1.5px solid var(--hairline)", display: "flex", gap: 14 }}>
        <div style={{ width: 72, height: 72, flexShrink: 0, border: "1.5px solid var(--hairline-2)", background: "var(--surface-2)", display: "grid", placeItems: "center", overflow: "hidden" }}>
          {img ? <img src={img} style={{ width: "100%", height: "100%", objectFit: "cover" }} /> : <window.Icons.package size={22} style={{ color: "var(--ink-3)" }} />}
        </div>
        <div style={{ minWidth: 0, flex: 1 }}>
          <div style={{ fontSize: 16, fontWeight: 700, letterSpacing: "-0.02em", color: "var(--ink)" }}>{p.name}</div>
          <div style={{ display: "flex", alignItems: "baseline", gap: 8, marginTop: 6 }}>
            <span style={{ fontSize: 20, fontWeight: 700, letterSpacing: "-0.02em" }}>{D.currency(Number(p.price || 0))}</span>
            {p.compare_at_price && Number(p.compare_at_price) > Number(p.price) && (
              <span className="muted" style={{ fontSize: 12, textDecoration: "line-through" }}>{D.currency(Number(p.compare_at_price))}</span>
            )}
          </div>
          <div style={{ marginTop: 8, display: "flex", gap: 6, flexWrap: "wrap" }}>
            <span className={`chip dot ${stockChip}`}>{stockLabel}</span>
            {p.status && <span className="chip">{p.status}</span>}
          </div>
        </div>
      </div>
      <div style={{ padding: 16, borderBottom: "1.5px solid var(--hairline)", display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
        <ETile label="Stock" value={p.quantity ?? "—"} accent={noStock ? "var(--neg)" : lowStock ? "var(--warn)" : undefined} />
        <ETile label="Sold" value={p.sales_count ?? 0} />
      </div>
      <ESection title="Store">
        <ERefRow type="store" id={p.store_id} name={p.stores?.name || "—"} sub={p.store_id ? String(p.store_id).slice(0, 8).toUpperCase() : "—"} initial={p.stores?.name} />
      </ESection>
      <ESection title="Details">
        <EKv k="Product ID" v={<span className="id">{String(p.id).slice(0, 8).toUpperCase()}</span>} />
        {p.sku && <EKv k="SKU" v={<span className="id">{p.sku}</span>} />}
        <EKv k="Created" v={new Date(p.created_at).toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" })} />
      </ESection>
    </div>
  );
};

// ── USER / DRIVER view ─────────────────────────────────────────────────────────

const UserEntityView = ({ id }) => {
  const sb = window.supabaseClient;
  const D = window.PipalData;
  const [u, setU] = useStateE(null);
  const [driver, setDriver] = useStateE(null);
  const [orders, setOrders] = useStateE([]);
  const [state, setState] = useStateE("loading");

  useEffectE(() => {
    let alive = true;
    (async () => {
      setState("loading");
      const { data: prof } = await sb.from("user_profiles")
        .select("id, display_name, username, phone, email, verification_level, account_status, can_deliver, created_at")
        .eq("id", id).single();
      if (!alive) return;
      if (!prof) { setState("missing"); return; }

      const [{ data: dp }, { data: buyerOrders }] = await Promise.all([
        sb.from("delivery_partners").select("status, vehicle_type, coverage_city, rating, total_deliveries, completed_deliveries").eq("user_id", id).maybeSingle(),
        sb.from("orders").select("id, order_number, total_amount, order_status, created_at").eq("buyer_id", id).order("created_at", { ascending: false }).limit(5),
      ]);
      if (!alive) return;
      setU(prof); setDriver(dp || null); setOrders(buyerOrders || []); setState("ok");
    })();
    return () => { alive = false; };
  }, [id]);

  if (state === "loading") return <ViewLoading />;
  if (state === "missing") return <ViewMsg>User not found.</ViewMsg>;

  const name = u.display_name || u.username || "Unknown";

  return (
    <div>
      <div style={{ padding: 16, borderBottom: "1.5px solid var(--hairline)", display: "flex", gap: 12, alignItems: "center" }}>
        <div style={{ width: 44, height: 44, flexShrink: 0, display: "grid", placeItems: "center", background: "var(--accent)", color: "var(--on-accent)", border: "1.5px solid var(--hairline-2)", fontSize: 16, fontWeight: 700, fontFamily: "var(--font-mono)" }}>
          {name[0]?.toUpperCase()}
        </div>
        <div style={{ minWidth: 0, flex: 1 }}>
          <div style={{ fontSize: 16, fontWeight: 700, letterSpacing: "-0.02em", color: "var(--ink)" }}>{name}</div>
          <div className="muted" style={{ fontSize: 11.5, fontFamily: "var(--font-mono)", marginTop: 2 }}>
            {u.username ? "@" + u.username : ""}{u.phone ? " · " + u.phone : ""}
          </div>
          <div style={{ marginTop: 8, display: "flex", gap: 6, flexWrap: "wrap" }}>
            {u.account_status && <span className={`chip dot ${u.account_status === "active" ? "pos" : "warn"}`}>{u.account_status}</span>}
            {u.verification_level && <span className="chip">{u.verification_level}</span>}
            {u.can_deliver && <span className="chip accent">driver</span>}
          </div>
        </div>
      </div>

      {driver && (
        <ESection title="Delivery partner">
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10, marginBottom: 4 }}>
            <ETile label="Deliveries" value={driver.total_deliveries ?? 0} />
            <ETile label="Rating" value={driver.rating ? Number(driver.rating).toFixed(1) : "—"} accent="var(--warn)" />
          </div>
          <div style={{ marginTop: 8 }}>
            <EKv k="Status" v={driver.status === "pending_approval" ? "pending" : driver.status} />
            <EKv k="Vehicle" v={driver.vehicle_type || "—"} />
            <EKv k="Coverage" v={driver.coverage_city || "—"} />
          </div>
        </ESection>
      )}

      <ESection title="Details">
        {u.email && <EKv k="Email" v={u.email} />}
        <EKv k="User ID" v={<span className="id">{String(u.id).slice(0, 8).toUpperCase()}</span>} />
        <EKv k="Joined" v={new Date(u.created_at).toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" })} />
      </ESection>

      <ESection title={`Recent orders (${orders.length})`}>
        {orders.length === 0
          ? <div className="muted" style={{ fontSize: 12 }}>No orders</div>
          : orders.map(o => (
            <div key={o.id} style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "6px 0", gap: 8 }}>
              <EntityLink type="order" id={o.id} label={o.order_number || String(o.id).slice(0, 8).toUpperCase()} style={{ fontSize: 12 }} />
              <span className="num" style={{ fontSize: 12, fontWeight: 600 }}>{D.compactCurrency(Number(o.total_amount || 0))}</span>
            </div>
          ))}
      </ESection>
    </div>
  );
};

// ── DELIVERY view ──────────────────────────────────────────────────────────────

const DeliveryEntityView = ({ id }) => {
  const sb = window.supabaseClient;
  const D = window.PipalData;
  const [d, setD] = useStateE(null);
  const [state, setState] = useStateE("loading");

  useEffectE(() => {
    let alive = true;
    (async () => {
      setState("loading");
      const { data } = await sb.from("deliveries")
        .select("id, tracking_number, status, delivery_tier, is_flash, pickup_address, delivery_address, distance_km, fee, created_at, driver_id, order_id, orders(id, order_number, total_amount, store_id, stores(id, name))")
        .eq("id", id).single();
      if (!alive) return;
      if (!data) { setState("missing"); return; }
      let driverName = null;
      if (data.driver_id) {
        const { data: dp } = await sb.from("user_profiles").select("display_name, username").eq("id", data.driver_id).maybeSingle();
        driverName = dp?.display_name || dp?.username || null;
      }
      if (!alive) return;
      setD({ ...data, driverName }); setState("ok");
    })();
    return () => { alive = false; };
  }, [id]);

  if (state === "loading") return <ViewLoading />;
  if (state === "missing") return <ViewMsg>Delivery not found.</ViewMsg>;

  const statusChip = { delivered: "pos", failed: "neg", returned: "neg", returning_to_store: "warn", assigned: "info", picked_up: "accent" }[d.status] || "warn";

  return (
    <div>
      <EHero
        value={d.tracking_number || String(d.id).slice(0, 8).toUpperCase()}
        sub={`${d.delivery_tier || "standard"}${d.is_flash ? " · Flash" : ""}${d.distance_km ? " · " + Number(d.distance_km).toFixed(1) + " km" : ""}`}
        chip={<span className={`chip dot ${statusChip}`}>{String(d.status || "").replace(/_/g, " ")}</span>}
      />
      <ESection title="Order">
        <ERefRow type="order" id={d.order_id} name={d.orders?.order_number || (d.order_id ? String(d.order_id).slice(0, 8).toUpperCase() : "—")} sub={d.orders ? D.compactCurrency(Number(d.orders.total_amount || 0)) : null} initial="#" />
      </ESection>
      {d.orders?.store_id && (
        <ESection title="Store">
          <ERefRow type="store" id={d.orders.store_id} name={d.orders?.stores?.name || "—"} sub={String(d.orders.store_id).slice(0, 8).toUpperCase()} initial={d.orders?.stores?.name} />
        </ESection>
      )}
      {d.driver_id && (
        <ESection title="Driver">
          <ERefRow type="user" id={d.driver_id} name={d.driverName || "Driver"} sub={String(d.driver_id).slice(0, 8).toUpperCase()} initial="D" />
        </ESection>
      )}
      <ESection title="Route">
        <EKv k="Pickup" v={<span style={{ fontSize: 11.5, fontWeight: 500 }}>{d.pickup_address || "—"}</span>} />
        <EKv k="Dropoff" v={<span style={{ fontSize: 11.5, fontWeight: 500 }}>{d.delivery_address || "—"}</span>} />
        {d.fee != null && <EKv k="Fee" v={D.currency(Number(d.fee || 0))} />}
      </ESection>
      <ESection title="Details">
        <EKv k="Delivery ID" v={<span className="id">{String(d.id).slice(0, 8).toUpperCase()}</span>} />
        <EKv k="Created" v={new Date(d.created_at).toLocaleString("en-US", { month: "short", day: "numeric", hour: "2-digit", minute: "2-digit" })} />
      </ESection>
    </div>
  );
};

// ── Exports ────────────────────────────────────────────────────────────────────

window.EntityLink = EntityLink;
window.EntityDrawer = EntityDrawer;
window.EntityStore = EntityStore;
