/* Relay — Reports screen */
function ReportsScreen({ allOrders, now }) {
  const { PLATFORMS } = window.RelayData;
  const [range, setRange] = React.useState("today");
  const [typeFilter, setTypeFilter] = React.useState("all");
  const [sort, setSort] = React.useState({ col: "revenue", dir: "desc" });

  const ranges = [
    { id: "today", label: "Bugün" },
    { id: "yesterday", label: "Dün" },
    { id: "7d", label: "Son 7 gün" },
    { id: "30d", label: "Son 30 gün" },
  ];

  const DAY = 86400000;
  const startOfToday = new Date(); startOfToday.setHours(0, 0, 0, 0);
  const t0 = startOfToday.getTime();

  function inRange(ts) {
    if (range === "today") return ts >= t0;
    if (range === "yesterday") return ts >= t0 - DAY && ts < t0;
    if (range === "7d") return ts >= t0 - 6 * DAY;
    if (range === "30d") return ts >= t0 - 29 * DAY;
    return true;
  }

  const scoped = React.useMemo(() => allOrders.filter((o) =>
    inRange(o.placedAt) && (typeFilter === "all" || o.type === typeFilter)
  ), [allOrders, range, typeFilter]);

  const sold = scoped.filter((o) => o.status !== "cancelled");
  const cancelled = scoped.filter((o) => o.status === "cancelled");
  const revenue = sold.reduce((s, o) => s + o.total, 0);
  const aov = sold.length ? revenue / sold.length : 0;
  const items = sold.reduce((s, o) => s + o.items.reduce((a, it) => a + it.qty, 0), 0);

  // per-platform breakdown
  const byPlatform = React.useMemo(() => {
    const m = {};
    sold.forEach((o) => {
      const p = m[o.platformId] || (m[o.platformId] = { id: o.platformId, orders: 0, revenue: 0, items: 0 });
      p.orders++; p.revenue += o.total; p.items += o.items.reduce((a, it) => a + it.qty, 0);
    });
    let rows = Object.values(m).map((r) => ({ ...r, aov: r.orders ? r.revenue / r.orders : 0, ...PLATFORMS[r.id] }));
    rows.sort((a, b) => {
      const d = sort.dir === "asc" ? 1 : -1;
      return (a[sort.col] > b[sort.col] ? 1 : a[sort.col] < b[sort.col] ? -1 : 0) * d;
    });
    return rows;
  }, [sold, sort]);

  // trend chart: revenue by day (7d/30d) or by hour bucket (today/yesterday)
  const chart = React.useMemo(() => {
    if (range === "today" || range === "yesterday") {
      const base = range === "today" ? t0 : t0 - DAY;
      const buckets = [["09",9],["12",12],["15",15],["18",18],["21",21]].map(([lbl,h]) => ({ label: lbl, value: 0 }));
      sold.forEach((o) => {
        const h = new Date(o.placedAt).getHours();
        let idx = h < 11 ? 0 : h < 14 ? 1 : h < 17 ? 2 : h < 20 ? 3 : 4;
        buckets[idx].value += o.total;
      });
      return buckets.map((b) => ({ ...b, top: b.value ? Math.round(b.value) : "" }));
    }
    const days = range === "7d" ? 7 : 30;
    const step = range === "7d" ? 1 : 5;
    const out = [];
    for (let d = days - 1; d >= 0; d -= step) {
      const dayStart = t0 - d * DAY;
      const dayEnd = dayStart + step * DAY;
      const v = sold.filter((o) => o.placedAt >= dayStart && o.placedAt < dayEnd).reduce((s, o) => s + o.total, 0);
      const dt = new Date(dayStart);
      out.push({ label: dt.toLocaleDateString("tr-TR", { day: "2-digit", month: "short" }), value: v, top: v ? Math.round(v / 1000) + "k" : "" });
    }
    return out;
  }, [sold, range]);

  const shareRows = byPlatform.map((r) => ({ id: r.id, label: r.name, color: r.color, value: r.revenue }));

  function exportToast(fmt) {
    const rangeLabels = { today: "Bugünkü", yesterday: "Dünkü", "7d": "Son 7 günlük", "30d": "Son 30 günlük" };
    const label = rangeLabels[range] || range;
    window.__relayToast && window.__relayToast(`${label} rapor ${fmt} formatında dışa aktarılıyor…`);
  }

  const th = { fontSize: 10.5, fontWeight: 600, color: "var(--text-3)", textTransform: "uppercase", letterSpacing: ".05em", padding: "0 0 0 0" };

  return (
    <Scroller>
      <PageHeader title="Raporlar" icon={<I.reports size={18} />} subtitle="Bağlı tüm kanallardaki satış performansı.">
        <Btn kind="default" onClick={() => exportToast("Excel")}><I.receipt size={15} />Excel'e Aktar</Btn>
        <Btn kind="default" onClick={() => exportToast("PDF")}><I.printer size={15} />PDF'e Aktar</Btn>
      </PageHeader>

      {/* filters */}
      <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 18, flexWrap: "wrap" }}>
        <Segmented options={ranges} value={range} onChange={setRange} />
        <span style={{ width: 1, height: 22, background: "var(--border)" }} />
        <Segmented options={[{ id: "all", label: "Tümü" }, { id: "food", label: "Yemek" }, { id: "retail", label: "Perakende" }]} value={typeFilter} onChange={setTypeFilter} />
        <div style={{ flex: 1 }} />
        <span style={{ fontSize: 12.5, color: "var(--text-3)" }}>seçili aralıkta {scoped.length} sipariş</span>
      </div>

      {/* KPI cards */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 12, marginBottom: 18 }}>
        <BigStat label="Ciro" value={"AED " + Math.round(revenue).toLocaleString()} sub={`${sold.length} sipariş`} accent="var(--text)" />
        <BigStat label="Ort. Sipariş Değeri" value={"AED " + aov.toFixed(0)} sub={`${items} ürün satıldı`} />
        <BigStat label="Tamamlanan" value={sold.length} sub={`${cancelled.length} iptal edilen`} accent="var(--ready)" />
        <BigStat label="İptal Oranı" value={(scoped.length ? (cancelled.length / scoped.length) * 100 : 0).toFixed(1) + "%"} sub="kapsamdaki siparişlerin" accent={cancelled.length ? "var(--cancelled)" : "var(--text)"} />
      </div>

      {/* charts row */}
      <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: 16, marginBottom: 18 }}>
        <Panel title={range === "today" || range === "yesterday" ? "Günün saatlerine göre ciro" : "Ciro trendi"} note="AED">
          <BarChart data={chart} accent="var(--new)" />
        </Panel>
        <Panel title="Platforma göre ciro payı" note={`${byPlatform.length} aktif`}>
          {shareRows.length ? <ShareBar rows={shareRows} total={revenue} /> : <Empty />}
        </Panel>
      </div>

      {/* platform table (sortable) */}
      <Panel title="Kanal kırılımı" note="Sıralamak için bir sütuna tıklayın">
        <div style={{ display: "grid", gridTemplateColumns: "1.5fr 1fr 1fr 1fr 1fr", gap: 12, padding: "4px 4px 10px", borderBottom: "1px solid var(--border)" }}>
          <SortTH label="Platform" col="name" sort={sort} setSort={setSort} />
          <SortTH label="Sipariş" col="orders" sort={sort} setSort={setSort} align="right" />
          <SortTH label="Ürün" col="items" sort={sort} setSort={setSort} align="right" />
          <SortTH label="Ort. Değer" col="aov" sort={sort} setSort={setSort} align="right" />
          <SortTH label="Ciro" col="revenue" sort={sort} setSort={setSort} align="right" />
        </div>
        {byPlatform.length === 0 ? <Empty /> : byPlatform.map((r) => (
          <div key={r.id} style={{ display: "grid", gridTemplateColumns: "1.5fr 1fr 1fr 1fr 1fr", gap: 12, padding: "11px 4px", borderBottom: "1px solid var(--border)", alignItems: "center" }}>
            <PlatformBadge pid={r.id} withName size={22} />
            <span className="mono" style={{ textAlign: "right", fontSize: 13.5 }}>{r.orders}</span>
            <span className="mono" style={{ textAlign: "right", fontSize: 13.5, color: "var(--text-2)" }}>{r.items}</span>
            <span className="mono" style={{ textAlign: "right", fontSize: 13.5, color: "var(--text-2)" }}>{r.aov.toFixed(0)}</span>
            <span className="mono" style={{ textAlign: "right", fontSize: 14, fontWeight: 600 }}>{Math.round(r.revenue).toLocaleString()}</span>
          </div>
        ))}
        {byPlatform.length > 0 && (
          <div style={{ display: "grid", gridTemplateColumns: "1.5fr 1fr 1fr 1fr 1fr", gap: 12, padding: "11px 4px 2px", alignItems: "center" }}>
            <span style={{ fontSize: 12.5, fontWeight: 700, textTransform: "uppercase", letterSpacing: ".04em", color: "var(--text-2)" }}>Toplam</span>
            <span className="mono" style={{ textAlign: "right", fontSize: 13.5, fontWeight: 700 }}>{sold.length}</span>
            <span className="mono" style={{ textAlign: "right", fontSize: 13.5, fontWeight: 700 }}>{items}</span>
            <span className="mono" style={{ textAlign: "right", fontSize: 13.5, fontWeight: 700 }}>{aov.toFixed(0)}</span>
            <span className="mono" style={{ textAlign: "right", fontSize: 14, fontWeight: 700 }}>{Math.round(revenue).toLocaleString()}</span>
          </div>
        )}
      </Panel>
    </Scroller>
  );
}

function BigStat({ label, value, sub, accent }) {
  return (
    <div style={{ background: "var(--surface)", border: "1px solid var(--border)", borderRadius: "var(--radius)", padding: "15px 17px", boxShadow: "var(--shadow-sm)" }}>
      <div style={{ fontSize: 11, fontWeight: 600, color: "var(--text-3)", textTransform: "uppercase", letterSpacing: ".05em" }}>{label}</div>
      <div className="mono" style={{ fontSize: 26, fontWeight: 600, color: accent || "var(--text)", marginTop: 6, lineHeight: 1 }}>{value}</div>
      <div style={{ fontSize: 12, color: "var(--text-3)", marginTop: 6 }}>{sub}</div>
    </div>
  );
}

function Panel({ title, note, children }) {
  return (
    <div style={{ background: "var(--surface)", border: "1px solid var(--border)", borderRadius: "var(--radius)", padding: "16px 18px", boxShadow: "var(--shadow-sm)" }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 14 }}>
        <h3 style={{ margin: 0, fontSize: 14, fontWeight: 600 }}>{title}</h3>
        {note && <span style={{ fontSize: 11.5, color: "var(--text-3)", fontWeight: 500 }}>{note}</span>}
      </div>
      {children}
    </div>
  );
}

function Empty() {
  return <div style={{ textAlign: "center", color: "var(--text-3)", fontSize: 13, padding: "28px 0" }}>Bu aralıkta veri bulunmuyor.</div>;
}

Object.assign(window, { ReportsScreen, Panel, BigStat });
