// Portal C — Affiliate Mobile App (Neumorphic, in phone frame)
function PortalC() {
  const s = YJ.useStore();
  const toast = useToast();
  const broker = s.brokers.find(b => b.id === s.currentBrokerId) || s.brokers[0];
  const [tab, setTab] = useState("home");

  // Compute broker's stats
  const myOrders = s.orders.filter(o => o.brokerId === broker.id);
  const earnFromOrders = myOrders.reduce((a, o) => a + o.amount * 0.05, 0);
  // Use seed totalEarn as baseline + any new commission earned at runtime
  const myCommission = Math.max(broker.totalEarn || 0, earnFromOrders);
  const cashWallet = Math.max(0, myCommission - (broker.withdrawn || 0));
  const myCustomers = Array.from(new Set(myOrders.map(o => o.customerId))).map(cid => {
    const cust = s.customers.find(c => c.id === cid);
    const cOrders = myOrders.filter(o => o.customerId === cid);
    return { cust, orders: cOrders, maxMaai: Math.max(...cOrders.map(o => o.maai)) };
  });

  const expPct = (broker.exp % 1000) / 10; // arbitrary scale

  return (
    <div className="phone-stage">
      <div className="phone">
        <div className="phone-screen" style={{ paddingBottom: 80 }}>
          <div className="phone-status">
            <span>9:41</span>
            <span style={{ display: "flex", gap: 6, alignItems: "center" }}>
              <svg width="16" height="10" viewBox="0 0 16 10" fill="currentColor"><rect x="0" y="6" width="3" height="4" rx="1"/><rect x="4" y="4" width="3" height="6" rx="1"/><rect x="8" y="2" width="3" height="8" rx="1"/><rect x="12" y="0" width="3" height="10" rx="1"/></svg>
              <span style={{ fontSize: 10 }}>5G</span>
              <svg width="22" height="10" viewBox="0 0 22 10" fill="none" stroke="currentColor" strokeWidth="1"><rect x="0.5" y="0.5" width="18" height="9" rx="2"/><rect x="2" y="2" width="14" height="6" rx="1" fill="currentColor"/><rect x="19" y="3" width="2" height="4" rx="1" fill="currentColor"/></svg>
            </span>
          </div>

          {tab === "home" && <PhoneHome broker={broker} myCommission={myCommission} cashWallet={cashWallet} expPct={expPct} setTab={setTab} />}
          {tab === "quest" && <PhoneQuest broker={broker} myCustomers={myCustomers} />}
          {tab === "products" && <PhoneProducts toast={toast} brokerId={broker.id} />}
          {tab === "wallet" && <PhoneWallet broker={broker} cashWallet={cashWallet} totalEarn={myCommission} toast={toast} />}
          {tab === "leaderboard" && <PhoneLeaderboard />}
        </div>

        <PhoneNav tab={tab} setTab={setTab} />
      </div>

      <div style={{ marginTop: 16, display: "flex", gap: 8, alignItems: "center" }}>
        <span style={{ fontSize: 12, color: "var(--ink-3)" }}>สลับมุมมองนายหน้า:</span>
        <select className="neu-input" style={{ padding: "8px 12px", width: "auto" }} value={broker.id} onChange={e => YJ.actions.switchBroker(e.target.value)}>
          {s.brokers.map(b => <option key={b.id} value={b.id}>{b.name} (Lv{b.level})</option>)}
        </select>
      </div>
    </div>
  );
}

function PhoneHome({ broker, myCommission, cashWallet, expPct, setTab }) {
  const s = YJ.useStore();
  return (
    <div style={{ padding: "16px 18px 24px" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 12, marginTop: 8 }}>
        <div style={{ width: 56, height: 56, borderRadius: 18, background: "linear-gradient(135deg, var(--accent), var(--accent-2))", color: "#fff", display: "grid", placeItems: "center", fontWeight: 700, fontSize: 22, boxShadow: "var(--neu-out-sm)" }}>
          {broker.avatar}
        </div>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 12, color: "var(--ink-3)" }}>สวัสดีตอนเช้า</div>
          <div style={{ fontWeight: 600, fontSize: 16 }}>{broker.name}</div>
        </div>
        <div style={{ position: "relative", width: 44, height: 44 }}>
          <svg width="44" height="44" viewBox="0 0 44 44" className="ring-progress">
            <circle cx="22" cy="22" r="18" className="bg" strokeWidth="4" />
            <circle cx="22" cy="22" r="18" className="fg" strokeWidth="4" strokeDasharray={2 * Math.PI * 18} strokeDashoffset={2 * Math.PI * 18 * (1 - expPct / 100)} />
          </svg>
          <div style={{ position: "absolute", inset: 0, display: "grid", placeItems: "center", fontSize: 11, fontWeight: 700, color: "var(--accent)" }}>Lv{broker.level}</div>
        </div>
      </div>

      {/* EXP bar */}
      <div style={{ marginTop: 14, padding: "12px 16px", borderRadius: 18, boxShadow: "var(--neu-in-sm)" }}>
        <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12, marginBottom: 6 }}>
          <span style={{ color: "var(--ink-3)" }}>EXP สะสม</span>
          <span className="mono" style={{ fontWeight: 600 }}>{fmtNum(broker.exp)} / {fmtNum(Math.ceil(broker.exp / 1000) * 1000)}</span>
        </div>
        <div className="progress-line"><div style={{ width: expPct + "%" }}></div></div>
      </div>

      {/* Wallet card big */}
      <div style={{ marginTop: 16, padding: 20, borderRadius: 22, background: "linear-gradient(135deg, var(--accent), var(--accent-2))", color: "#fff", boxShadow: "var(--neu-out-sm)" }}>
        <div style={{ fontSize: 12, opacity: .85, textTransform: "uppercase", letterSpacing: ".08em" }}>กระเป๋าเงินสด</div>
        <div className="mono" style={{ fontSize: 30, fontWeight: 700, marginTop: 4 }}>{fmtTHB(cashWallet)}</div>
        <div style={{ fontSize: 11, opacity: .8, marginTop: 6 }}>รวมรายได้สะสม {fmtTHB(myCommission)}</div>
        <div style={{ display: "flex", gap: 8, marginTop: 14 }}>
          <button className="neu-btn" style={{ flex: 1, background: "#fff", color: "var(--accent)", justifyContent: "center" }} onClick={() => setTab("wallet")}>ถอนเงิน</button>
          <button className="neu-btn" style={{ flex: 1, background: "rgba(255,255,255,.2)", color: "#fff", boxShadow: "none", justifyContent: "center" }} onClick={() => setTab("products")}>แชร์ลิงก์</button>
        </div>
      </div>

      {/* Quick stats */}
      <div style={{ marginTop: 16, display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 10 }}>
        {[
          { label: "ลิงก์ที่แชร์", value: "37" },
          { label: "ลูกค้าใหม่", value: fmtNum(new Set(s.orders.filter(o => o.brokerId === broker.id && o.maai === 1).map(o => o.customerId)).size) },
          { label: "ปิดยอด", value: fmtNum(s.orders.filter(o => o.brokerId === broker.id).length) },
        ].map(x => (
          <div key={x.label} style={{ padding: 12, borderRadius: 14, boxShadow: "var(--neu-in-sm)", textAlign: "center" }}>
            <div className="mono" style={{ fontSize: 18, fontWeight: 700 }}>{x.value}</div>
            <div style={{ fontSize: 11, color: "var(--ink-3)" }}>{x.label}</div>
          </div>
        ))}
      </div>

      {/* Featured products to share */}
      <div style={{ marginTop: 18, fontSize: 13, fontWeight: 600, display: "flex", justifyContent: "space-between" }}>
        <span>โปรเด่นวันนี้</span>
        <button onClick={() => setTab("products")} style={{ background: "none", border: "none", color: "var(--accent)", fontSize: 12, fontWeight: 500 }}>ดูทั้งหมด →</button>
      </div>
      <div style={{ marginTop: 10, display: "grid", gap: 10 }}>
        {s.products.slice(0, 3).map(p => {
          const br = s.brands.find(b => b.id === p.brandId);
          return (
            <div key={p.id} style={{ padding: 12, borderRadius: 16, boxShadow: "var(--neu-out-sm)", display: "grid", gridTemplateColumns: "48px 1fr auto", gap: 12, alignItems: "center" }}>
              <div className="skeleton-img" style={{ width: 48, height: 48, fontSize: 7 }}>IMG</div>
              <div>
                <div style={{ fontSize: 13, fontWeight: 500, lineHeight: 1.3 }}>{p.name}</div>
                <div style={{ fontSize: 11, color: "var(--ink-3)" }}>{br?.name} · คอม ฿{Math.round(p.price * 0.05)}</div>
              </div>
              <button className="neu-btn sm" onClick={() => { navigator.clipboard?.writeText(`yjm.co/r/${broker.id}/${p.id}`); }}><Ico.copy /></button>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function PhoneQuest({ broker, myCustomers }) {
  return (
    <div style={{ padding: "16px 18px 24px" }}>
      <div style={{ fontWeight: 700, fontSize: 18, marginTop: 8 }}>เส้นทางผจญภัย</div>
      <div style={{ fontSize: 12, color: "var(--ink-3)", marginBottom: 16 }}>ติดตามลูกค้าที่กดผ่านลิงก์ของคุณตามไม้ 1-4</div>

      {myCustomers.length === 0 && <div className="empty">ยังไม่มีลูกค้าผ่านลิงก์ของคุณ</div>}

      <div style={{ display: "grid", gap: 12 }}>
        {myCustomers.map(({ cust, orders, maxMaai }) => (
          <div key={cust.id} style={{ padding: 14, borderRadius: 18, boxShadow: "var(--neu-out-sm)" }}>
            <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 10 }}>
              <div style={{ fontWeight: 600, fontSize: 14 }}>{cust.name}</div>
              <span className="pill">{cust.phone}</span>
            </div>
            <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 6 }}>
              {[1, 2, 3, 4].map(m => {
                const hit = orders.find(o => o.maai === m);
                return (
                  <div key={m} style={{
                    padding: "10px 8px", borderRadius: 12,
                    boxShadow: hit ? "none" : "var(--neu-in-sm)",
                    background: hit ? "linear-gradient(135deg, var(--accent), var(--accent-2))" : "transparent",
                    color: hit ? "#fff" : "var(--ink-3)",
                    textAlign: "center",
                  }}>
                    <div style={{ fontSize: 10, opacity: .85 }}>ไม้ {m}</div>
                    <div style={{ fontSize: 11, fontWeight: 600, marginTop: 2 }}>{hit ? "✓ ปิด" : "—"}</div>
                    {hit && <div className="mono" style={{ fontSize: 10, marginTop: 2 }}>฿{Math.round(hit.amount * 0.05)}</div>}
                  </div>
                );
              })}
            </div>
            <div style={{ marginTop: 10, fontSize: 11, color: "var(--ink-3)" }}>
              ความคืบหน้า: ไม้ {maxMaai}/4 — {orders.length} ออเดอร์ · รวม ฿{Math.round(orders.reduce((a, o) => a + o.amount * 0.05, 0))}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

function PhoneProducts({ toast, brokerId }) {
  const s = YJ.useStore();
  const [gpFilter, setGpFilter] = useState("all");
  const visible = s.products.filter(p => {
    if (gpFilter === "all") return true;
    const b = s.brands.find(br => br.id === p.brandId);
    return b && b.gp === Number(gpFilter);
  });

  const copy = async (productId) => {
    const url = `https://yjm.co/r/${brokerId}/${productId}`;
    try { await navigator.clipboard.writeText(url); } catch {}
    toast.push("คัดลอกลิงก์แล้ว — แชร์ได้ทันที");
  };

  return (
    <div style={{ padding: "16px 18px 24px" }}>
      <div style={{ fontWeight: 700, fontSize: 18, marginTop: 8 }}>คลังสินค้าดึงลิงก์</div>
      <div style={{ fontSize: 12, color: "var(--ink-3)", marginBottom: 14 }}>เลือกสินค้าตามเกรด GP ที่ได้ค่าคอมสูง</div>

      <div style={{ display: "flex", gap: 4, padding: 4, borderRadius: 12, boxShadow: "var(--neu-in-sm)", marginBottom: 14 }}>
        {[["all", "ทั้งหมด"], ["60", "GP 60%"], ["50", "GP 50%"], ["40", "GP 40%"]].map(([k, l]) => (
          <button key={k} className={"neu-btn sm " + (gpFilter === k ? "primary" : "ghost")} style={{ flex: 1, justifyContent: "center" }} onClick={() => setGpFilter(k)}>{l}</button>
        ))}
      </div>

      <div style={{ display: "grid", gap: 12 }}>
        {visible.map(p => {
          const br = s.brands.find(b => b.id === p.brandId);
          const commission = Math.round(p.price * 0.05);
          return (
            <div key={p.id} style={{ padding: 14, borderRadius: 16, boxShadow: "var(--neu-out-sm)" }}>
              <div style={{ display: "flex", gap: 12 }}>
                <div className="skeleton-img" style={{ width: 64, height: 64, fontSize: 8, flexShrink: 0 }}>IMG</div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 13, fontWeight: 500, lineHeight: 1.3 }}>{p.name}</div>
                  <div style={{ fontSize: 11, color: "var(--ink-3)", marginTop: 4 }}>{br?.name} · GP {br?.gp}%</div>
                  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 8 }}>
                    <div>
                      <span className="mono" style={{ fontSize: 14, fontWeight: 700 }}>{fmtTHB(p.price)}</span>
                      <span style={{ marginLeft: 8, color: "var(--ok)", fontSize: 12, fontWeight: 600 }}>+฿{commission} คอม</span>
                    </div>
                  </div>
                </div>
              </div>
              <div style={{ display: "flex", gap: 8, marginTop: 10 }}>
                <button className="neu-btn primary" style={{ flex: 1, justifyContent: "center" }} onClick={() => copy(p.id)}>
                  <Ico.copy /> คัดลอกลิงก์
                </button>
                <button className="neu-btn sm">แชร์</button>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function PhoneWallet({ broker, cashWallet, totalEarn, toast }) {
  const confirm = useConfirm();
  const [amount, setAmount] = useState(Math.min(500, cashWallet) || 0);
  const btnRef = useRef(null);

  const handleWithdraw = async () => {
    if (amount <= 0 || amount > cashWallet) return toast.push("จำนวนไม่ถูกต้อง", "danger");
    const ok = await confirm.ask({ title: "ถอนเงินด่วน", body: `ถอน ${fmtTHB(amount)} เข้าบัญชี ${broker.name} — เงินถึงภายใน 30 นาที`, confirmLabel: "ยืนยันถอน" });
    if (!ok) return;
    YJ.actions.brokerWithdraw(broker.id, amount);
    if (btnRef.current) shootCoins(btnRef.current, 14);
    toast.push("ส่งคำสั่งถอน " + fmtTHB(amount) + " — รอเงินเข้า");
  };

  const history = [
    { d: Date.now() - 2 * 86400000, a: 2400, status: "success" },
    { d: Date.now() - 7 * 86400000, a: 1800, status: "success" },
    { d: Date.now() - 14 * 86400000, a: 3200, status: "success" },
  ];

  return (
    <div style={{ padding: "16px 18px 24px" }}>
      <div style={{ fontWeight: 700, fontSize: 18, marginTop: 8 }}>กระเป๋าเงิน</div>

      <div style={{ marginTop: 14, padding: 20, borderRadius: 22, background: "linear-gradient(135deg, var(--accent), var(--accent-2))", color: "#fff" }}>
        <div style={{ fontSize: 12, opacity: .85 }}>ยอดเงินสดสะสม</div>
        <div className="mono" style={{ fontSize: 32, fontWeight: 700, marginTop: 4 }}>{fmtTHB(cashWallet)}</div>
        <div style={{ fontSize: 11, opacity: .8 }}>รายได้สะสมตลอดชีวิต {fmtTHB(totalEarn)} · ถอนไปแล้ว {fmtTHB(broker.withdrawn || 0)}</div>
      </div>

      <div style={{ marginTop: 16, padding: 18, borderRadius: 18, boxShadow: "var(--neu-out-sm)" }}>
        <div style={{ fontSize: 12, fontWeight: 600, color: "var(--ink-2)", marginBottom: 10 }}>ถอนด่วน — เข้าทันที 30 นาที</div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 6, marginBottom: 12 }}>
          {[500, 1000, Math.floor(cashWallet)].map((v, i) => (
            <button key={i} className={"neu-btn sm " + (amount === v ? "primary" : "")} onClick={() => setAmount(v)} disabled={v <= 0 || v > cashWallet}>{v <= 0 ? "—" : "฿" + fmtNum(v)}</button>
          ))}
        </div>
        <input className="neu-input mono" type="number" value={amount} onChange={e => setAmount(Number(e.target.value))} />
        <button ref={btnRef} className="neu-btn primary" style={{ marginTop: 10, width: "100%", justifyContent: "center" }} onClick={handleWithdraw}>ถอน {fmtTHB(amount)}</button>
      </div>

      <div style={{ marginTop: 16, fontSize: 13, fontWeight: 600 }}>ประวัติการถอน</div>
      <div style={{ marginTop: 10, display: "grid", gap: 8 }}>
        {history.map((h, i) => (
          <div key={i} style={{ padding: 12, borderRadius: 12, boxShadow: "var(--neu-in-sm)", display: "flex", justifyContent: "space-between" }}>
            <div>
              <div className="mono" style={{ fontWeight: 600 }}>{fmtTHB(h.a)}</div>
              <div style={{ fontSize: 11, color: "var(--ink-3)" }}>{fmtDate(h.d)}</div>
            </div>
            <span className="pill ok">โอนแล้ว</span>
          </div>
        ))}
      </div>
      {confirm.node}
    </div>
  );
}

function PhoneLeaderboard() {
  const s = YJ.useStore();
  const top = YJ.select.topBrokers(s, 5);
  const podium = top.slice(0, 3);
  return (
    <div style={{ padding: "16px 18px 24px" }}>
      <div style={{ fontWeight: 700, fontSize: 18, marginTop: 8 }}>แท่นเกียรติยศ</div>
      <div style={{ fontSize: 12, color: "var(--ink-3)", marginBottom: 18 }}>ท็อปนายหน้าประจำเดือน — รางวัลพิเศษทุกเดือน</div>

      {/* Podium */}
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 8, alignItems: "end", marginBottom: 18 }}>
        {[1, 0, 2].map((idx, col) => {
          const x = podium[idx];
          if (!x) return <div key={col}></div>;
          const height = [110, 140, 90][col];
          const colors = ["linear-gradient(180deg,#c4cad6,#8a93a8)", "linear-gradient(180deg,#ffd54a,#f1a721)", "linear-gradient(180deg,#e5965f,#a16438)"];
          return (
            <div key={col} style={{ textAlign: "center" }}>
              <div style={{ width: 48, height: 48, borderRadius: 14, background: "linear-gradient(135deg, var(--accent), var(--accent-2))", color: "#fff", display: "grid", placeItems: "center", fontWeight: 700, fontSize: 18, margin: "0 auto 6px", boxShadow: "var(--neu-out-sm)" }}>{x.broker.avatar}</div>
              <div style={{ fontSize: 12, fontWeight: 600 }}>{x.broker.name.split(" ")[0]}</div>
              <div className="mono" style={{ fontSize: 11, color: "var(--ink-3)" }}>฿{fmtNum(x.earn)}</div>
              <div style={{ marginTop: 8, height, borderRadius: "14px 14px 4px 4px", background: colors[col], display: "grid", placeItems: "center", fontWeight: 700, fontSize: 22, color: "#fff" }}>{idx + 1}</div>
            </div>
          );
        })}
      </div>

      {/* List rest */}
      <div style={{ display: "grid", gap: 8 }}>
        {top.slice(3).map((x, i) => (
          <div key={x.broker.id} style={{ padding: 12, borderRadius: 14, boxShadow: "var(--neu-in-sm)", display: "flex", alignItems: "center", gap: 10 }}>
            <div className="mono" style={{ width: 24, color: "var(--ink-3)", fontWeight: 600 }}>{i + 4}</div>
            <div style={{ width: 32, height: 32, borderRadius: 10, background: "var(--accent-soft)", color: "var(--accent)", display: "grid", placeItems: "center", fontWeight: 700 }}>{x.broker.avatar}</div>
            <div style={{ flex: 1, fontSize: 13 }}>{x.broker.name}</div>
            <div className="mono" style={{ fontWeight: 600 }}>{fmtTHB(x.earn)}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

function PhoneNav({ tab, setTab }) {
  const items = [
    { id: "home", label: "หน้าแรก", ico: "⌂" },
    { id: "quest", label: "ไม้ 1-4", ico: "◎" },
    { id: "products", label: "สินค้า", ico: "▤" },
    { id: "leaderboard", label: "ท็อป", ico: "♛" },
    { id: "wallet", label: "เงิน", ico: "₿" },
  ];
  return (
    <div style={{ position: "absolute", left: 14, right: 14, bottom: 14, padding: 8, background: "var(--bg)", borderRadius: 26, boxShadow: "var(--neu-out), 0 4px 18px rgba(20,40,80,.12)", display: "grid", gridTemplateColumns: "repeat(5, 1fr)", gap: 4 }}>
      {items.map(it => (
        <button key={it.id} onClick={() => setTab(it.id)} style={{
          border: "none", background: tab === it.id ? "linear-gradient(135deg, var(--accent), var(--accent-2))" : "transparent",
          color: tab === it.id ? "#fff" : "var(--ink-2)",
          padding: "10px 6px", borderRadius: 18, fontSize: 11, fontWeight: 500,
          boxShadow: tab === it.id ? "var(--neu-out-sm)" : "none",
          display: "grid", placeItems: "center", gap: 2, cursor: "pointer", transition: "all .15s",
        }}>
          <span style={{ fontSize: 16 }}>{it.ico}</span>
          {it.label}
        </button>
      ))}
    </div>
  );
}

window.PortalC = PortalC;
