// Portal B — Supplier / Store Owner
function PortalB() {
  const s = YJ.useStore();
  const toast = useToast();
  const confirm = useConfirm();
  const [view, setView] = useState("dashboard");
  const [editProduct, setEditProduct] = useState(null);
  const [addProductOpen, setAddProductOpen] = useState(false);

  const brand = s.brands.find(b => b.id === s.currentBrandId) || s.brands[0];
  const brandProducts = s.products.filter(p => p.brandId === brand.id);
  const brandOrders = s.orders.filter(o => o.brandId === brand.id);
  const gross = brandOrders.reduce((a, o) => a + o.amount, 0);
  const supplierShare = gross * (1 - brand.gp / 100);
  const payout = s.supplierPayouts.find(p => p.brandId === brand.id) || { supplierShare, withdrawn: 0 };
  const available = supplierShare - (payout.withdrawn || 0);

  // Build maai3/4 (repeat) report
  const maaiRepeatOrders = brandOrders.filter(o => o.maai >= 3);
  const maai3 = brandOrders.filter(o => o.maai === 3);
  const maai4 = brandOrders.filter(o => o.maai === 4);
  const totalCustomers = new Set(brandOrders.map(o => o.customerId)).size;
  const repeatCustomers = new Set(maaiRepeatOrders.map(o => o.customerId)).size;
  const repeatRate = totalCustomers ? (repeatCustomers / totalCustomers) * 100 : 0;

  const withdrawRef = useRef(null);
  const handleWithdraw = async () => {
    if (available <= 0) return toast.push("ไม่มียอดถอน", "danger");
    const ok = await confirm.ask({ title: "เบิกถอนรายได้", body: `ถอน ${fmtTHB(available)} เข้าบัญชี ${brand.bankAcc} — เงินจะเข้าใน 1-2 วันทำการ`, confirmLabel: "ยืนยันถอน" });
    if (!ok) return;
    YJ.actions.supplierWithdraw(brand.id, available);
    if (withdrawRef.current) shootCoins(withdrawRef.current, 10);
    toast.push("ส่งคำสั่งถอน " + fmtTHB(available));
  };

  return (
    <div>
      <div className="page-head">
        <div>
          <h1>{brand.name} — Supplier Portal</h1>
          <div className="sub">GP {brand.gp}% · {brand.category} · เข้าร่วมเมื่อ {fmtDate(brand.joined)}</div>
        </div>
        <BrandSwitcher />
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "220px 1fr", gap: 24 }}>
        <SubTabs value={view} onChange={setView} items={[
          { id: "dashboard", label: "ภาพรวมร้าน", ico: "DB" },
          { id: "products", label: "จัดการสินค้า", ico: "PD" },
          { id: "repeat", label: "ลูกค้าซื้อซ้ำ", ico: "RP" },
          { id: "payout", label: "เบิกถอนรายได้", ico: "PT" },
        ]} />

        <div style={{ display: "grid", gap: 18 }}>
          {view === "dashboard" && (
            <>
              <div className="grid cols-4">
                <Stat label="ยอดขายสะสม" value={fmtTHB(gross)} />
                <Stat label="ออเดอร์สะสม" value={fmtNum(brandOrders.length)} />
                <Stat label={`ส่วนแบ่งสุทธิ (${100 - brand.gp}%)`} value={fmtTHB(supplierShare)} accent />
                <Stat label="ยอดถอนได้" value={fmtTHB(available)} />
              </div>

              <Section title="ยอดขาย 30 วันล่าสุด">
                <HeatRow data={Array.from({ length: 30 }, (_, i) => {
                  const cutoff = Date.now() - (29 - i) * 86400000;
                  return brandOrders.filter(o => o.createdAt >= cutoff && o.createdAt < cutoff + 86400000).reduce((a, o) => a + o.amount, 0);
                })} />
              </Section>

              <Section title="สถานะสต๊อกสินค้า" right={<button className="neu-btn primary sm" onClick={() => setAddProductOpen(true)}>+ เพิ่มสินค้า</button>}>
                <div className="grid cols-2">
                  {brandProducts.map(p => (
                    <div key={p.id} style={{ padding: 14, borderRadius: 14, boxShadow: "var(--neu-in-sm)", display: "grid", gridTemplateColumns: "1fr auto", gap: 10 }}>
                      <div>
                        <div style={{ fontWeight: 500, fontSize: 14 }}>{p.name}</div>
                        <div style={{ fontSize: 12, color: "var(--ink-3)", marginTop: 2 }}>ขายแล้ว {fmtNum(p.sold)} ชิ้น · {fmtTHB(p.price)}</div>
                      </div>
                      <div style={{ textAlign: "right" }}>
                        <div className="mono" style={{ fontWeight: 700 }}>{p.stock}</div>
                        <div style={{ fontSize: 11, color: p.stock < 50 ? "var(--danger)" : "var(--ok)" }}>
                          {p.stock < 50 ? "สต๊อกใกล้หมด" : "พร้อมขาย"}
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              </Section>
            </>
          )}

          {view === "products" && (
            <Section
              title="Product Catalog"
              sub="เพิ่ม / แก้ไข / ลบสินค้า — ตั้งค่า Telesales discount"
              right={<button className="neu-btn primary" onClick={() => setAddProductOpen(true)}>+ เพิ่มสินค้า</button>}
            >
              <table className="neu-table">
                <thead><tr><th>สินค้า</th><th>ราคา</th><th>สต๊อก</th><th>ขายแล้ว</th><th>TS Discount</th><th></th></tr></thead>
                <tbody>
                  {brandProducts.map(p => (
                    <tr key={p.id}>
                      <td>
                        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                          <div className="skeleton-img" style={{ width: 40, height: 40, fontSize: 8 }}>IMG</div>
                          <div style={{ fontWeight: 500 }}>{p.name}</div>
                        </div>
                      </td>
                      <td className="mono">{fmtTHB(p.price)}</td>
                      <td className="mono" style={{ color: p.stock < 50 ? "var(--danger)" : "inherit" }}>{p.stock}</td>
                      <td className="mono">{fmtNum(p.sold)}</td>
                      <td className="mono">-{fmtTHB(p.telesalesDiscount)}</td>
                      <td>
                        <div style={{ display: "flex", gap: 6, justifyContent: "flex-end" }}>
                          <button className="neu-btn sm" onClick={() => setEditProduct(p)}>แก้ไข</button>
                          <button className="neu-btn sm danger" onClick={async () => {
                            const ok = await confirm.ask({ title: "ลบสินค้า?", body: `ลบ "${p.name}" ออกจากระบบ — ทำแล้วยกเลิกไม่ได้`, confirmLabel: "ลบ", danger: true });
                            if (ok) { YJ.actions.deleteProduct(p.id); toast.push("ลบสินค้าแล้ว"); }
                          }}>ลบ</button>
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </Section>
          )}

          {view === "repeat" && (
            <>
              <div className="grid cols-3">
                <Stat label="ลูกค้าที่ซื้อซ้ำ (ไม้ 3+4)" value={fmtNum(repeatCustomers)} sub={`${repeatRate.toFixed(0)}% ของลูกค้าทั้งหมด`} />
                <Stat label="ไม้ 3 — ซื้อซ้ำปี 1" value={fmtNum(maai3.length)} sub={fmtTHB(maai3.reduce((a, o) => a + o.amount, 0))} />
                <Stat label="ไม้ 4 — ซื้อซ้ำปี 2+" value={fmtNum(maai4.length)} sub={fmtTHB(maai4.reduce((a, o) => a + o.amount, 0))} accent />
              </div>

              <Section title="LTV ของลูกค้าที่ซื้อซ้ำ" sub="ทีม Telesales ปิดยอดให้คุณได้กี่ครั้ง — กำไรซื้อซ้ำที่คุณจะได้รับโดยไม่ต้องลงทุนเพิ่ม">
                <table className="neu-table">
                  <thead><tr><th>ลูกค้า</th><th>ซื้อครั้งแรก</th><th>จำนวนครั้ง</th><th>LTV รวม</th><th>ไม้ล่าสุด</th></tr></thead>
                  <tbody>
                    {Array.from(new Set(brandOrders.map(o => o.customerId))).map(cid => {
                      const cust = s.customers.find(c => c.id === cid);
                      const orders = brandOrders.filter(o => o.customerId === cid).sort((a, b) => a.createdAt - b.createdAt);
                      const ltv = orders.reduce((a, o) => a + o.amount, 0);
                      const last = orders[orders.length - 1];
                      return (
                        <tr key={cid}>
                          <td>
                            <div style={{ fontWeight: 500 }}>{cust?.name}</div>
                            <div style={{ fontSize: 11, color: "var(--ink-3)" }}>{cust?.phone}</div>
                          </td>
                          <td style={{ fontSize: 12 }}>{fmtDate(orders[0]?.createdAt)}</td>
                          <td className="mono">{orders.length}</td>
                          <td className="mono" style={{ fontWeight: 600 }}>{fmtTHB(ltv)}</td>
                          <td><span className="pill">ไม้ {last?.maai}</span></td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </Section>
            </>
          )}

          {view === "payout" && (
            <>
              <div className="grid cols-3">
                <Stat label="ยอดขายรวม (Gross)" value={fmtTHB(gross)} />
                <Stat label={`หัก GP ${brand.gp}% (ส่วน YJmall)`} value={fmtTHB(gross * brand.gp / 100)} />
                <Stat label={`ส่วนของแบรนด์ ${100 - brand.gp}%`} value={fmtTHB(supplierShare)} accent />
              </div>

              <Section title="เบิกถอนรายได้" sub={`เข้าบัญชี ${brand.bankAcc}`}>
                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 18 }}>
                  <div style={{ padding: 22, borderRadius: 18, boxShadow: "var(--neu-in-sm)" }}>
                    <div style={{ fontSize: 12, color: "var(--ink-3)" }}>ถอนแล้ว</div>
                    <div className="mono" style={{ fontSize: 24, fontWeight: 700 }}>{fmtTHB(payout.withdrawn || 0)}</div>
                  </div>
                  <div style={{ padding: 22, borderRadius: 18, background: "linear-gradient(135deg, var(--accent), var(--accent-2))", color: "#fff" }}>
                    <div style={{ fontSize: 12, opacity: .8 }}>พร้อมถอน</div>
                    <div className="mono" style={{ fontSize: 28, fontWeight: 700, marginTop: 4 }}>{fmtTHB(available)}</div>
                    <button ref={withdrawRef} className="neu-btn" style={{ background: "#fff", color: "var(--accent)", marginTop: 12, justifyContent: "center", width: "100%" }} onClick={handleWithdraw} disabled={available <= 0}>
                      ถอนเข้าบัญชี
                    </button>
                  </div>
                </div>

                <div style={{ marginTop: 18 }}>
                  <div style={{ fontSize: 13, fontWeight: 600, marginBottom: 10 }}>ประวัติการเบิก</div>
                  <table className="neu-table">
                    <thead><tr><th>วันที่</th><th>จำนวนเงิน</th><th>สถานะ</th><th>Ref</th></tr></thead>
                    <tbody>
                      {(payout.history || [
                        { d: Date.now() - 7 * 86400000, a: 18400, ref: "WD-220184" },
                        { d: Date.now() - 22 * 86400000, a: 22600, ref: "WD-219782" },
                      ]).map((h, i) => (
                        <tr key={i}><td>{fmtDate(h.d)}</td><td className="mono">{fmtTHB(h.a)}</td><td><span className="pill ok">โอนแล้ว</span></td><td className="mono" style={{ color: "var(--ink-3)" }}>{h.ref}</td></tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </Section>
            </>
          )}
        </div>
      </div>

      {editProduct && <ProductModal product={editProduct} brandId={brand.id} onClose={() => setEditProduct(null)} onSave={(p) => {
        YJ.actions.upsertProduct(p); toast.push("บันทึก " + p.name); setEditProduct(null);
      }} />}
      {addProductOpen && <ProductModal brandId={brand.id} onClose={() => setAddProductOpen(false)} onSave={(p) => {
        YJ.actions.upsertProduct(p); toast.push("เพิ่ม " + p.name); setAddProductOpen(false);
      }} />}
      {confirm.node}
    </div>
  );
}

function BrandSwitcher() {
  const s = YJ.useStore();
  const brands = s.brands.filter(b => !b.isHouse && b.status === "active");
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 8, padding: "6px 6px 6px 14px", borderRadius: 14, boxShadow: "var(--neu-in-sm)" }}>
      <span style={{ fontSize: 12, color: "var(--ink-3)" }}>สลับมุมมองแบรนด์:</span>
      <select className="neu-input" style={{ padding: "8px 12px", boxShadow: "none", width: "auto" }} value={s.currentBrandId} onChange={e => YJ.actions.switchBrand(e.target.value)}>
        {brands.map(b => <option key={b.id} value={b.id}>{b.name}</option>)}
      </select>
    </div>
  );
}

function ProductModal({ product, brandId, onClose, onSave }) {
  const [p, setP] = useState(product || { name: "", price: 0, stock: 0, telesalesDiscount: 0, brandId });
  const isEdit = !!product;
  return (
    <Modal open onClose={onClose} title={isEdit ? "แก้ไขสินค้า" : "เพิ่มสินค้าใหม่"} size="lg"
      footer={<>
        <button className="neu-btn ghost" onClick={onClose}>ยกเลิก</button>
        <button className="neu-btn primary" disabled={!p.name || !p.price} onClick={() => onSave({ ...p, brandId })}>{isEdit ? "บันทึก" : "เพิ่มสินค้า"}</button>
      </>}
    >
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
        <div style={{ display: "grid", gap: 14 }}>
          <Field label="ชื่อสินค้า"><input className="neu-input" value={p.name} onChange={e => setP({ ...p, name: e.target.value })} /></Field>
          <Field label="ราคาขาย"><NumberInput value={p.price} onChange={v => setP({ ...p, price: v })} prefix="฿" /></Field>
          <Field label="สต๊อก"><NumberInput value={p.stock} onChange={v => setP({ ...p, stock: v })} /></Field>
          <Field label="ส่วนลดสำหรับ Telesales (On-top)">
            <NumberInput value={p.telesalesDiscount || 0} onChange={v => setP({ ...p, telesalesDiscount: v })} prefix="-฿" />
            <div style={{ fontSize: 11, color: "var(--ink-3)", marginTop: 6 }}>ทีม Telesales จะใช้ส่วนลดนี้ปิดยอดได้ทันที</div>
          </Field>
        </div>
        <div style={{ display: "grid", gap: 14 }}>
          <Field label="รูป / วิดีโอสินค้า">
            <div className="skeleton-img" style={{ height: 140 }}>คลิกเพื่ออัปโหลด<br/>(jpg / png / mp4)</div>
          </Field>
          <Field label="รายละเอียดและสรรพคุณ">
            <textarea className="neu-input" rows={5} placeholder="ใส่รายละเอียดสินค้า สรรพคุณ และวิธีใช้..." value={p.description || ""} onChange={e => setP({ ...p, description: e.target.value })} />
          </Field>
        </div>
      </div>
    </Modal>
  );
}

window.PortalB = PortalB;
