/* ============================================================
   TIKTOK LIVE OFFICE — window.TiktokOffice
   ============================================================ */
(function () {
  const { useState } = React;
  const { useT, useLang, Icon, Panel, Badge, Avatar, Stat, DataTable, PageHead, BarChart } = window.UI;
  const baht = (n) => "฿" + Math.round(n).toLocaleString();

  function RoomTabs({ rooms, active, onChange }) {
    const { lang } = useLang();
    return <div className="seg">{rooms.map((r) => <button key={r.key} className={active === r.key ? "on" : ""} onClick={() => onChange(r.key)}>{r.en}{lang === "th" ? <span style={{ color: "var(--tx-ghost)", marginLeft: 6, fontSize: 11 }}>{r.th}</span> : null}</button>)}</div>;
  }

  function LiveOrders() {
    const t = useT(); const D = window.DATA;
    const cols = [
      { key: "id", label: "ORDER", render: (r) => <span className="mono strong">{r.id}</span> },
      { key: "date", label: t("DATE", "วันที่"), render: (r) => <span className="mono" style={{ color: "var(--tx-faint)" }}>{r.date}</span> },
      { key: "ch", label: t("CHANNEL", "ช่อง"), render: (r) => <Badge kind="info">{r.ch}</Badge> },
      { key: "host", label: t("HOST", "พิธีกร"), render: (r) => <span style={{ display: "inline-flex", alignItems: "center", gap: 7 }}><Avatar ini={r.host[0]} size={22} ac1="oklch(0.74 0.16 200)" ac2="oklch(0.68 0.2 350)" />{r.host}</span> },
      { key: "type", label: t("SOURCE", "ที่มา"), render: (r) => <Badge kind={r.type === "Live" ? "accent" : "neutral"} dot>{r.type}</Badge> },
      { key: "gmv", label: "GMV", sortable: true, render: (r) => <span className="num strong">{baht(r.gmv)}</span> },
      { key: "comm", label: t("COMMISSION", "ค่าคอม"), sortable: true, render: (r) => <span className="num">{baht(r.comm)}</span> },
      { key: "status", label: t("PAYOUT", "การจ่าย"), render: (r) => <Badge kind={r.st} dot>{r.status}</Badge> },
    ];
    const gmvToday = D.tiktokOrders.reduce((s, o) => s + o.gmv, 0);
    return (
      <div className="fade-in">
        <div className="grid" style={{ gridTemplateColumns: "repeat(4,1fr)", marginBottom: 16 }}>
          <Stat label={t("GMV today", "GMV วันนี้")} value={baht(gmvToday)} delta="+22.1%" accent="var(--tiktok)" />
          <Stat label={t("Live orders", "ออเดอร์จากไลฟ์")} value={D.tiktokOrders.length} delta={t("from 2 streams", "2 ช่อง")} deltaDir="flat" accent="var(--tiktok)" />
          <Stat label={t("Avg order value", "ยอดเฉลี่ย/ออเดอร์")} value={baht(gmvToday / D.tiktokOrders.length)} delta="+5.4%" accent="var(--tiktok)" />
          <Stat label={t("Commission due", "ค่าคอมรอจ่าย")} value={baht(D.kpi.commissionDue)} deltaDir="flat" delta={t("3 orders", "3 รายการ")} accent="var(--warn)" />
        </div>
        <Panel title={t("Live orders", "ออเดอร์จากไลฟ์")} th={t("imported from TikTok Orders", "นำเข้าจาก TikTok")} right={<><button className="chip"><Icon name="import" size={14} />{t("Import orders", "นำเข้า")}</button><button className="btn primary"><Icon name="plug" size={15} />{t("Match shifts", "จับคู่กะ")}</button></>}>
          <DataTable columns={cols} rows={D.tiktokOrders} initialSort={{ key: "gmv", dir: "desc" }} />
        </Panel>
      </div>
    );
  }

  function Commission() {
    const t = useT(); const D = window.DATA;
    const byHost = {};
    D.tiktokOrders.forEach((o) => { byHost[o.host] = byHost[o.host] || { gmv: 0, comm: 0, due: 0, orders: 0 }; byHost[o.host].gmv += o.gmv; byHost[o.host].comm += o.comm; byHost[o.host].orders++; if (o.st === "warn") byHost[o.host].due += o.comm; });
    return (
      <div className="fade-in">
        <div className="panel" style={{ borderColor: "oklch(0.80 0.15 78 / 0.4)", background: "oklch(0.80 0.15 78 / 0.07)", marginBottom: 16, padding: "14px 18px", display: "flex", alignItems: "center", gap: 14 }}>
          <span style={{ color: "var(--warn)" }}><Icon name="coin" size={22} /></span>
          <div style={{ flex: 1 }}>
            <div style={{ fontWeight: 700, fontSize: 13.5 }}>{baht(D.kpi.commissionDue)} {t("commission pending payout", "ค่าคอมรอจ่าย")}</div>
            <div style={{ fontSize: 12, color: "var(--tx-dim)" }}>{t("3 orders across 1 host — awaiting approval", "3 รายการ — รออนุมัติจ่าย")}</div>
          </div>
          <button className="btn primary">{t("Approve payout", "อนุมัติจ่าย")}</button>
        </div>
        <div className="grid" style={{ gridTemplateColumns: "repeat(2,1fr)" }}>
          {Object.keys(byHost).map((h) => {
            const v = byHost[h];
            return (
              <Panel key={h}>
                <div className="panel-pad" style={{ display: "flex", gap: 16, alignItems: "center" }}>
                  <Avatar ini={h[0]} size={52} ac1="oklch(0.74 0.16 200)" ac2="oklch(0.68 0.2 350)" />
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 16, fontWeight: 700 }}>{h}</div>
                    <div style={{ fontSize: 12, color: "var(--tx-faint)" }}>{t("Live Host", "พิธีกรไลฟ์")} · {v.orders} {t("orders", "ออเดอร์")}</div>
                  </div>
                  {v.due > 0 ? <Badge kind="warn">{t("due", "รอจ่าย")} {baht(v.due)}</Badge> : <Badge kind="ok" dot>{t("paid", "จ่ายแล้ว")}</Badge>}
                </div>
                <div style={{ borderTop: "1px solid var(--hairline-soft)", padding: "14px 18px", display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 10 }}>
                  {[[baht(v.gmv), "GMV"], [baht(v.comm), t("commission", "ค่าคอม")], ["8%", t("rate", "เรท")]].map((c, i) => (
                    <div key={i}><div className="mono" style={{ fontSize: 16, fontWeight: 700 }}>{c[0]}</div><div style={{ fontSize: 10.5, color: "var(--tx-faint)" }}>{c[1]}</div></div>
                  ))}
                </div>
              </Panel>
            );
          })}
        </div>
      </div>
    );
  }

  function Channels() {
    const t = useT();
    const bars = [{ label: "Live A", v: 31200, label2: "฿31K", color: "var(--tiktok)" }, { label: "Live B", v: 19800, label2: "฿20K", color: "var(--tiktok-pink)" }];
    return (
      <div className="fade-in">
        <div className="grid" style={{ gridTemplateColumns: "minmax(0,1fr) 320px", alignItems: "start" }}>
          <Panel title={t("Channel performance", "ผลงานแยกช่อง")} th="GMV / commission">
            <div className="panel-pad"><BarChart data={bars} height={210} /></div>
          </Panel>
          <Panel title={t("Top channel", "ช่องเด่น")}>
            <div className="panel-pad">
              <div className="imgph" style={{ height: 120, marginBottom: 12, fontSize: 10 }}>{t("live thumbnail", "ภาพไลฟ์")}</div>
              <div style={{ fontSize: 15, fontWeight: 700 }}>AIT Live A</div>
              <div style={{ fontSize: 12, color: "var(--tx-faint)", marginBottom: 12 }}>{t("Host", "พิธีกร")}: ตูน · {t("3 streams this week", "3 ไลฟ์สัปดาห์นี้")}</div>
              {[["GMV", "฿31,200"], [t("Orders", "ออเดอร์"), "3"], [t("Avg viewers", "ผู้ชมเฉลี่ย"), "1,240"]].map((r, i) => (
                <div key={i} style={{ display: "flex", justifyContent: "space-between", fontSize: 12.5, padding: "6px 0", borderBottom: i < 2 ? "1px solid var(--hairline-soft)" : "none" }}><span style={{ color: "var(--tx-faint)" }}>{r[0]}</span><span className="mono" style={{ fontWeight: 600 }}>{r[1]}</span></div>
              ))}
            </div>
          </Panel>
        </div>
      </div>
    );
  }

  function TiktokOffice({ onNav }) {
    const t = useT();
    const Hero = window.OfficeHero;
    const [room, setRoom] = useState("orders");
    const rooms = [
      { key: "orders", en: "Live Orders", th: "ออเดอร์ไลฟ์" },
      { key: "commission", en: "Commission", th: "ค่าคอม" },
      { key: "channels", en: "Channels", th: "ช่อง" },
    ];
    return (
      <div className="main">
        <Hero office="tiktok" />
        <PageHead
          crumbs={<><a onClick={() => onNav("city")}>{t("System Map", "แผนที่ระบบ")}</a><Icon name="chev" size={12} /><span style={{ color: "var(--tiktok)" }}>TikTok Live Office</span></>}
          title="TikTok Live Office" th="ออฟฟิศไลฟ์ติ๊กต็อก" live
          right={<RoomTabs rooms={rooms} active={room} onChange={setRoom} />} />
        {room === "orders" && <LiveOrders />}
        {room === "commission" && <Commission />}
        {room === "channels" && <Channels />}
      </div>
    );
  }
  window.TiktokOffice = TiktokOffice;
})();
