/* Relay — All Orders screen (full history, filter + sort) */
function AllOrdersScreen({ allOrders, now, onOpen }) {
  const { PLATFORMS, STATUS, FLOW_LABELS } = window.RelayData;
  const [search, setSearch] = React.useState("");
  const [typeFilter, setTypeFilter] = React.useState("all");
  const [statusFilter, setStatusFilter] = React.useState("all");
  const [platFilter, setPlatFilter] = React.useState("all");
  const [sort, setSort] = React.useState({ col: "placedAt", dir: "desc" });

  const platOptions = [{ id: "all", label: "Tüm kanallar" }, ...Object.values(PLATFORMS).map((p) => ({ id: p.id, label: p.name }))];

  const rows = React.useMemo(() => {
    const q = search.trim().toLowerCase();
    let r = allOrders.filter((o) => {
      if (typeFilter !== "all" && o.type !== typeFilter) return false;
      if (statusFilter !== "all" && o.status !== statusFilter) return false;
      if (platFilter !== "all" && o.platformId !== platFilter) return false;
      if (q) {
        const hay = (o.customer + " " + o.id + " " + o.channelRef + " " + PLATFORMS[o.platformId].name).toLowerCase();
        if (!hay.includes(q)) return false;
      }
      return true;
    });
    const dir = sort.dir === "asc" ? 1 : -1;
    r = [...r].sort((a, b) => {
      let av = a[sort.col], bv = b[sort.col];
      if (sort.col === "items") { av = a.items.reduce((s, it) => s + it.qty, 0); bv = b.items.reduce((s, it) => s + it.qty, 0); }
      if (sort.col === "platform") { av = PLATFORMS[a.platformId].name; bv = PLATFORMS[b.platformId].name; }
      return (av > bv ? 1 : av < bv ? -1 : 0) * dir;
    });
    return r;
  }, [allOrders, search, typeFilter, statusFilter, platFilter, sort]);

  const statusOpts = [{ id: "all", label: "Tüm durumlar" }, ...["new", "preparing", "ready", "completed", "cancelled"].map((k) => ({ id: k, label: STATUS[k].label }))];
  const COLS = "150px 120px 1fr 90px 80px 120px 130px 90px";

  const Select = ({ value, onChange, options }) => (
    <select value={value} onChange={(e) => onChange(e.target.value)} style={{
      appearance: "none", padding: "7px 30px 7px 11px", borderRadius: "var(--radius-sm)", border: "1px solid var(--border)",
      background: "var(--surface) url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' fill='none' stroke='%238b95a2' stroke-width='2'%3E%3Cpath d='M2 4l4 4 4-4'/%3E%3C/svg%3E\") no-repeat right 11px center",
      fontSize: 12.5, fontWeight: 600, color: "var(--text)", cursor: "pointer",
    }}>{options.map((o) => <option key={o.id} value={o.id}>{o.label}</option>)}</select>
  );

  return (
    <Scroller>
      <PageHeader title="Tüm siparişler" icon={<I.orders size={18} />} subtitle={`Tüm kanallardaki ve durumlardaki ${allOrders.length} sipariş.`}>
        <div style={{ position: "relative" }}>
          <span style={{ position: "absolute", left: 11, top: "50%", transform: "translateY(-50%)", color: "var(--text-3)" }}><I.search size={15} /></span>
          <input value={search} onChange={(e) => setSearch(e.target.value)} placeholder="Sipariş ara…" style={{ padding: "8px 12px 8px 34px", borderRadius: "var(--radius-sm)", border: "1px solid var(--border)", background: "var(--surface)", fontSize: 13, width: 220, outline: "none" }} />
        </div>
      </PageHeader>

      {/* filter bar */}
      <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 14, flexWrap: "wrap" }}>
        <Segmented options={[{ id: "all", label: "Tümü" }, { id: "food", label: "Yemek" }, { id: "retail", label: "Perakende" }]} value={typeFilter} onChange={setTypeFilter} />
        <Select value={statusFilter} onChange={setStatusFilter} options={statusOpts} />
        <Select value={platFilter} onChange={setPlatFilter} options={platOptions} />
        <div style={{ flex: 1 }} />
        <span style={{ fontSize: 12.5, color: "var(--text-3)" }}>{rows.length} sonuç</span>
      </div>

      {/* table */}
      <div style={{ background: "var(--surface)", border: "1px solid var(--border)", borderRadius: "var(--radius)", overflow: "hidden", boxShadow: "var(--shadow-sm)" }}>
        <div style={{ display: "grid", gridTemplateColumns: COLS, gap: 12, padding: "12px 18px", borderBottom: "1px solid var(--border)", background: "var(--surface-2)" }}>
          <SortTH label="Tarih" col="placedAt" sort={sort} setSort={setSort} />
          <SortTH label="Sipariş ID" col="id" sort={sort} setSort={setSort} />
          <SortTH label="Kanal / Müşteri" col="platform" sort={sort} setSort={setSort} />
          <SortTH label="Tür" col="type" sort={sort} setSort={setSort} />
          <SortTH label="Ürün" col="items" sort={sort} setSort={setSort} align="right" />
          <SortTH label="Toplam" col="total" sort={sort} setSort={setSort} align="right" />
          <SortTH label="Durum" col="status" sort={sort} setSort={setSort} />
          <span style={{ fontSize: 10.5, fontWeight: 600, color: "var(--text-3)", textTransform: "uppercase", letterSpacing: ".05em", textAlign: "right" }}>—</span>
        </div>
        <div>
          {rows.length === 0 && <div style={{ padding: "48px", textAlign: "center", color: "var(--text-3)", fontSize: 13.5 }}>Bu filtrelere uygun sipariş bulunamadı.</div>}
          {rows.slice(0, 200).map((o) => (
            <div key={o.id} onClick={() => onOpen(o)} style={{ display: "grid", gridTemplateColumns: COLS, gap: 12, padding: "11px 18px", borderBottom: "1px solid var(--border)", alignItems: "center", cursor: "pointer", transition: "background .1s" }}
              onMouseEnter={(e) => e.currentTarget.style.background = "var(--surface-2)"}
              onMouseLeave={(e) => e.currentTarget.style.background = "transparent"}>
              <div style={{ fontSize: 12.5 }}>
                <div className="mono" style={{ fontWeight: 600 }}>{clockTime(o.placedAt)}</div>
                <div style={{ fontSize: 11, color: "var(--text-3)" }}>{new Date(o.placedAt).toLocaleDateString("tr-TR", { day: "2-digit", month: "short" })}</div>
              </div>
              <span className="mono" style={{ fontSize: 12, color: "var(--text-2)" }}>{o.id}</span>
              <div style={{ display: "flex", alignItems: "center", gap: 9, minWidth: 0 }}>
                <PlatformBadge pid={o.platformId} size={24} />
                <div style={{ minWidth: 0 }}>
                  <div style={{ fontWeight: 600, fontSize: 13, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{o.customer}</div>
                  <div style={{ fontSize: 11, color: "var(--text-3)" }}>{PLATFORMS[o.platformId].name} · {o.fulfillment}</div>
                </div>
              </div>
              <span style={{ color: "var(--text-2)" }}><TypeIcon type={o.type} /></span>
              <span className="mono" style={{ textAlign: "right", fontSize: 13, color: "var(--text-2)" }}>{o.items.reduce((s, it) => s + it.qty, 0)}</span>
              <span className="mono" style={{ textAlign: "right", fontSize: 13.5, fontWeight: 600 }}>{fmtMoney(o.total)}</span>
              <span><StatusPill status={o.status} type={o.type} /></span>
              <span style={{ textAlign: "right", color: "var(--text-3)" }}><I.arrowRight size={15} /></span>
            </div>
          ))}
        </div>
      </div>
      {rows.length > 200 && <div style={{ textAlign: "center", color: "var(--text-3)", fontSize: 12.5, padding: "14px 0" }}>İlk 200 sipariş gösteriliyor (Toplam {rows.length})</div>}
    </Scroller>
  );
}

Object.assign(window, { AllOrdersScreen });
