/* ============================================================
   Screen: Sales — 売上一覧 / 締め処理 / 一括入力
   ============================================================ */
function Sales({ ctx }) {
  const { db, tours, openSettle, go, toast } = ctx;
  const [tab, setTab] = React.useState("list");
  const [biz, setBiz] = React.useState("all");
  const [bulk, setBulk] = React.useState(false);

  const rows = db.sales.filter((s) => biz === "all" || s.biz === biz);
  const total = rows.reduce((a, s) => a + s.amount, 0);
  const heldSum = rows.filter((s) => s.biz === "tour").reduce((a, s) => a + s.amount, 0);
  const confSum = total - heldSum;

  return (
    <div className="page">
      <div className="row" style={{ justifyContent: "space-between", alignItems: "flex-end", marginBottom: 18 }}>
        <div>
          <h1 className="page-title">売上管理</h1>
          <p className="page-sub">事業区分・チャネル別に売上を計上し、月次・ツアー単位で締める</p>
        </div>
        <div className="row gap8">
          <button className="btn" onClick={() => toast("CSV取込：Shopify / BASE / Square 連携（デモ）")}><Icon name="upload" size={15} />CSVインポート</button>
          <button className="btn primary" onClick={() => setBulk(true)}><Icon name="plus" size={16} />現場売上を一括入力</button>
        </div>
      </div>

      <div className="tabs" style={{ marginBottom: 18 }}>
        <div className={"tab" + (tab === "list" ? " on" : "")} onClick={() => setTab("list")}>売上一覧</div>
        <div className={"tab" + (tab === "close" ? " on" : "")} onClick={() => setTab("close")}>締め処理</div>
      </div>

      {tab === "list" && <>
        <div className="grid cols-3" style={{ gap: 14, marginBottom: 16 }}>
          <MiniCard label="表示中の売上合計" v={total} icon="wallet" />
          <div className="card card-pad">
            <div className="row gap6" style={{ fontSize: 11.5, color: "var(--deposit-ink)", fontWeight: 600 }}><Icon name="lock" size={13} />うち預かり（ツアー）</div>
            <div style={{ marginTop: 8 }}><Money v={heldSum} size={21} color="var(--deposit-ink)" /></div>
          </div>
          <div className="card card-pad">
            <div className="row gap6" style={{ fontSize: 11.5, color: "var(--revenue-ink)", fontWeight: 600 }}><Icon name="checkCircle" size={13} />うち確定（EC/倉庫/卸/単発）</div>
            <div style={{ marginTop: 8 }}><Money v={confSum} size={21} color="var(--revenue-ink)" /></div>
          </div>
        </div>

        <div className="row gap8" style={{ marginBottom: 14 }}>
          <div className="seg">
            <button className={biz === "all" ? "on" : ""} onClick={() => setBiz("all")}>すべて</button>
            {Object.values(db.businessTypes).map((b) => (
              <button key={b.key} className={biz === b.key ? "on" : ""} onClick={() => setBiz(b.key)}>{b.label}</button>
            ))}
          </div>
          <div className="spacer" />
          <span className="muted" style={{ fontSize: 12.5 }}>{rows.length} 件</span>
          <button className="btn sm" onClick={() => toast("売上CSVを書き出しました（デモ）")}><Icon name="download" size={14} />書き出し</button>
        </div>

        <div className="card" style={{ overflow: "hidden" }}>
          <table className="tbl">
            <thead>
              <tr><th>日付</th><th>事業区分</th><th>クライアント</th><th>内容</th><th>チャネル</th><th>決済</th><th>区分</th><th className="r">金額</th></tr>
            </thead>
            <tbody>
              {rows.map((s) => {
                const c = db.clientById(s.clientId);
                const held = s.biz === "tour";
                return (
                  <tr key={s.id}>
                    <td className="mono" style={{ fontSize: 12, color: "var(--ink-3)", whiteSpace: "nowrap" }}>{s.date.slice(5)}</td>
                    <td><span className="chip" style={{ height: 22 }}><span className="cdot" style={{ background: db.businessTypes[s.biz].color }} />{db.businessTypes[s.biz].label}</span></td>
                    <td><div className="row gap8"><Avatar name={c.name} color={c.color} size={24} square /><span style={{ fontSize: 12.5, whiteSpace: "nowrap" }}>{c.name}</span></div></td>
                    <td style={{ fontSize: 12.5 }}>{db.categories[s.cat]}<div className="sub">{s.note}</div></td>
                    <td><span className="row gap6" style={{ fontSize: 12 }}><Icon name={s.channel === "online" ? "external" : "pin"} size={13} style={{ color: "var(--ink-3)" }} />{s.channel === "online" ? "オンライン" : "現場"}</span></td>
                    <td className="muted" style={{ fontSize: 12 }}>{s.pay}</td>
                    <td>{held ? <span className="badge dep" style={{ height: 21 }}>預かり</span> : <span className="badge rev" style={{ height: 21 }}>確定</span>}</td>
                    <td className="r"><Money v={s.amount} size={13} /></td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </>}

      {tab === "close" && <CloseTab ctx={ctx} />}

      {bulk && <BulkInputModal ctx={ctx} onClose={() => setBulk(false)} />}
    </div>
  );
}

/* ---------- Close processing tab ---------- */
function CloseTab({ ctx }) {
  const { db, tours, consign, openSettle, settleConsign, toast } = ctx;
  const pending = tours.filter((t) => t.status === "pending");
  const ecPending = (consign || []).filter((c) => c.status !== "settled");
  const [settleEc, setSettleEc] = React.useState(null);
  return (
    <div className="grid cols-2" style={{ gap: 16 }}>
      {/* monthly */}
      <div className="card">
        <div className="card-head"><div><h3>月次締め（ツアー外物販）</h3><div className="sub">EC・倉庫業・単発・卸 — 月末締め</div></div></div>
        <div className="card-pad">
          <div className="row" style={{ justifyContent: "space-between", padding: "12px 14px", background: "var(--surface-2)", borderRadius: 10, marginBottom: 10 }}>
            <div><b style={{ fontSize: 13 }}>2026年5月</b><div className="muted" style={{ fontSize: 11.5 }}>締め済 ・ 4件の請求書を発行</div></div>
            <div className="col" style={{ alignItems: "flex-end" }}><Money v={4218600} size={15} /><StatusBadge status="settled" dot={false} /></div>
          </div>
          <div className="row" style={{ justifyContent: "space-between", padding: "14px 14px", background: "var(--brand-wash)", borderRadius: 10, border: "1px solid var(--brand-wash-2)" }}>
            <div><b style={{ fontSize: 13 }}>2026年6月（進行中）</b><div className="muted" style={{ fontSize: 11.5 }}>売上記録の42%を取込済</div></div>
            <Money v={1352400} size={15} />
          </div>
          <div className="prog" style={{ margin: "12px 0 18px" }}><i style={{ width: "42%", background: "var(--brand)" }} /></div>
          <button className="btn primary lg" style={{ width: "100%" }} onClick={() => toast("6月分の月次締めをプレビュー（デモ）")}><Icon name="layers" size={16} />6月分を締める</button>
        </div>
      </div>

      {/* deposit settlements: two cycles */}
      <div className="card">
        <div className="card-head"><div><h3>預かり金の精算</h3><div className="sub">委託契約の預かり金を精算（手数料を確定）</div></div></div>
        <div>
          <div className="row" style={{ padding: "10px 20px", background: "var(--surface-2)", justifyContent: "space-between" }}><span className="sec-title">ツアー精算 — 終了時</span><span className="muted" style={{ fontSize: 11 }}>{pending.length}件</span></div>
          {pending.length === 0 && <div className="muted" style={{ padding: "16px 20px", fontSize: 12.5 }}>精算待ちのツアーはありません</div>}
          {pending.map((t, i) => {
            const c = db.clientById(t.clientId);
            const share = Math.round(t.held * t.commission / 100);
            return (
              <div key={t.id} style={{ padding: "16px 20px", borderBottom: "1px solid var(--border)" }}>
                <div className="row gap10" style={{ marginBottom: 10 }}>
                  <Avatar name={c.name} color={c.color} size={34} square />
                  <div style={{ flex: 1 }}><b style={{ fontSize: 13 }}>{t.name}</b><div className="muted" style={{ fontSize: 11.5 }}>{c.name} ・ {t.end} 終了</div></div>
                  <StatusBadge status="pending" />
                </div>
                <div className="row" style={{ gap: 16, padding: "10px 0", marginBottom: 10 }}>
                  <div className="minis"><span className="ml">預かり金</span><Money v={t.held} size={15} color="var(--deposit-ink)" /></div>
                  <Icon name="arrowRight" size={16} style={{ color: "var(--ink-4)", alignSelf: "flex-end", marginBottom: 4 }} />
                  <div className="minis"><span className="ml">当社取り分 {t.commission}%</span><Money v={share} size={15} color="var(--revenue)" /></div>
                </div>
                <button className="btn primary" style={{ width: "100%" }} onClick={() => openSettle(t)}><Icon name="scale" size={15} />精算する</button>
              </div>
            );
          })}
          <div className="row" style={{ padding: "10px 20px", background: "var(--surface-2)", justifyContent: "space-between" }}><span className="sec-title">EC委託 月次精算 — 月末締め</span><span className="muted" style={{ fontSize: 11 }}>{ecPending.length}件</span></div>
          {ecPending.length === 0 && <div className="muted" style={{ padding: "16px 20px", fontSize: 12.5 }}>月次精算待ちのEC委託はありません</div>}
          {ecPending.map((ec, i) => {
            const c = db.clientById(ec.clientId);
            const share = Math.round(ec.held * ec.commission / 100);
            return (
              <div key={ec.id} style={{ padding: "16px 20px", borderBottom: i < ecPending.length - 1 ? "1px solid var(--border)" : "none" }}>
                <div className="row gap10" style={{ marginBottom: 10 }}>
                  <Avatar name={c.name} color={c.color} size={34} square />
                  <div style={{ flex: 1 }}><b style={{ fontSize: 13 }}>{c.name}</b><div className="muted" style={{ fontSize: 11.5 }}>{ec.channel} ・ {ec.month} 締め分 ・ {ec.orders}件</div></div>
                  <span className="badge dep">EC委託・月次</span>
                </div>
                <div className="row" style={{ gap: 16, padding: "10px 0", marginBottom: 10 }}>
                  <div className="minis"><span className="ml">預かり金</span><Money v={ec.held} size={15} color="var(--deposit-ink)" /></div>
                  <Icon name="arrowRight" size={16} style={{ color: "var(--ink-4)", alignSelf: "flex-end", marginBottom: 4 }} />
                  <div className="minis"><span className="ml">当社取り分 {ec.commission}%</span><Money v={share} size={15} color="var(--revenue)" /></div>
                </div>
                <button className="btn primary" style={{ width: "100%" }} onClick={() => setSettleEc(ec)}><Icon name="scale" size={15} />月次精算する</button>
              </div>
            );
          })}
        </div>
      </div>
      {settleEc && <ConsignSettleModal ctx={ctx} item={settleEc} onClose={() => setSettleEc(null)} />}
    </div>
  );
}

/* ---------- Bulk onsite input modal ---------- */
function BulkInputModal({ ctx, onClose }) {
  const { db, toast } = ctx;
  const goods = db.products.filter((p) => p.clientId === "c-stella");
  const [qty, setQty] = React.useState(goods.map(() => 0));
  const [venue, setVenue] = React.useState("Zepp Tokyo（6/4）");
  const total = goods.reduce((a, p, i) => a + p.price * qty[i], 0);
  const set = (i, v) => setQty((q) => q.map((x, j) => (j === i ? Math.max(0, parseInt(v || 0)) : x)));

  return (
    <Modal title="現場売上の一括入力" sub="公演会場で売れた商品の数量をまとめて記録します" onClose={onClose} wide
      foot={<>
        <div className="row gap8"><span className="muted" style={{ fontSize: 12 }}>合計</span><Money v={total} size={17} /><span className="badge dep" style={{ marginLeft: 6 }}>預かり計上</span></div>
        <button className="btn" style={{ marginLeft: "auto" }} onClick={onClose}>キャンセル</button>
        <button className="btn primary" disabled={total === 0} onClick={() => { toast(`${venue} の現場売上 ${db.yen(total)} を記録しました`); onClose(); }}><Icon name="check" size={16} />記録する</button>
      </>}>
      <div className="row gap12" style={{ marginBottom: 16 }}>
        <label className="fld" style={{ flex: 1 }}>会場・公演
          <select value={venue} onChange={(e) => setVenue(e.target.value)}>
            <option>Zepp Tokyo（6/4）</option><option>Zepp Osaka（6/8）</option><option>Aichi Sky Expo（6/15）</option>
          </select>
        </label>
        <label className="fld" style={{ flex: 1 }}>決済方法
          <select><option>現地決済（端末）</option><option>現金</option><option>QR決済</option></select>
        </label>
      </div>
      <div className="card" style={{ overflow: "hidden" }}>
        <table className="tbl">
          <thead><tr><th>商品</th><th className="r">単価</th><th className="r" style={{ width: 110 }}>数量</th><th className="r">小計</th></tr></thead>
          <tbody>
            {goods.map((p, i) => (
              <tr key={p.id}>
                <td><b style={{ fontSize: 12.5 }}>{p.name}</b><div className="sub mono">{p.sku}</div></td>
                <td className="r"><Money v={p.price} size={12.5} /></td>
                <td className="r">
                  <div className="row" style={{ justifyContent: "flex-end", gap: 6 }}>
                    <button className="qbtn" onClick={() => set(i, qty[i] - 1)}>−</button>
                    <input className="input" value={qty[i]} onChange={(e) => set(i, e.target.value)} style={{ width: 52, height: 32, textAlign: "center", padding: 0 }} />
                    <button className="qbtn" onClick={() => set(i, qty[i] + 1)}>+</button>
                  </div>
                </td>
                <td className="r"><Money v={p.price * qty[i]} size={12.5} color={qty[i] ? "var(--ink)" : "var(--ink-4)"} /></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      <div className="row gap8" style={{ marginTop: 12, fontSize: 12, color: "var(--ink-2)", background: "var(--deposit-soft)", padding: "10px 13px", borderRadius: 9 }}>
        <Icon name="lock" size={15} style={{ color: "var(--deposit)", flex: "none" }} />
        STELLA IDOL PROJECT はツアー＝委託契約のため、この売上は全額 <b>預かり金</b> として計上されます。
      </div>
      <style>{`.qbtn{width:30px;height:32px;border:1px solid var(--border-2);background:var(--surface);border-radius:7px;cursor:pointer;font-size:16px;color:var(--ink-2);font-family:inherit;}.qbtn:hover{background:var(--surface-2);}`}</style>
    </Modal>
  );
}

/* ---------- EC委託 月次精算 modal ---------- */
function ConsignSettleModal({ ctx, item, onClose }) {
  const { db, settleConsign, go } = ctx;
  const [step, setStep] = React.useState(0);
  const c = db.clientById(item.clientId);
  const gross = item.held;
  const share = Math.round(gross * item.commission / 100);
  const fee = item.paymentFee || 0;
  const pay = gross - share - fee;

  if (step === 1) {
    return (
      <Modal title="月次預かりを精算しました" onClose={onClose}
        foot={<>
          <button className="btn" onClick={onClose}>閉じる</button>
          <button className="btn primary" style={{ marginLeft: "auto" }} onClick={() => { onClose(); go("invoices"); }}><Icon name="invoice" size={15} />精算明細・請求書を発行</button>
        </>}>
        <div className="col" style={{ alignItems: "center", textAlign: "center", padding: "8px 0 4px" }}>
          <div style={{ width: 72, height: 72, borderRadius: "50%", background: "var(--revenue-soft)", display: "grid", placeItems: "center", marginBottom: 16 }}>
            <Icon name="checkCircle" size={38} style={{ color: "var(--revenue)" }} />
          </div>
          <h3 style={{ margin: 0, fontSize: 15, lineHeight: 1.45 }}>{c.name} ・ {item.month} EC委託</h3>
          <p className="muted" style={{ margin: "10px 0 0", fontSize: 13 }}>月次の預かり金 <b style={{ color: "var(--deposit-ink)" }}>{db.yen(gross)}</b> を精算しました。</p>
          <div className="row gap16" style={{ marginTop: 20, width: "100%", justifyContent: "center" }}>
            <div className="card card-pad" style={{ flex: 1, textAlign: "center", background: "var(--revenue-soft)", border: "none" }}>
              <div style={{ fontSize: 11.5, color: "var(--revenue-ink)", fontWeight: 600 }}>確定売上に振替</div>
              <div style={{ marginTop: 6 }}><Money v={share} size={20} color="var(--revenue-ink)" /></div>
            </div>
            <div className="card card-pad" style={{ flex: 1, textAlign: "center", background: "#FBE3DC", border: "none" }}>
              <div style={{ fontSize: 11.5, color: "#B0492C", fontWeight: 600 }}>クライアント支払額</div>
              <div style={{ marginTop: 6 }}><Money v={pay} size={20} color="#B0492C" /></div>
            </div>
          </div>
        </div>
      </Modal>
    );
  }

  return (
    <Modal title="EC委託 月次精算" sub={c.name + " ・ " + item.month + " 締め分"} onClose={onClose}
      foot={<>
        <div className="row gap8" style={{ fontSize: 11.5, color: "var(--ink-3)" }}><Icon name="lock" size={14} />経理ロールのみ確定可能</div>
        <button className="btn" style={{ marginLeft: "auto" }} onClick={onClose}>キャンセル</button>
        <button className="btn primary" onClick={() => { settleConsign(item.id, { share, pay }); setStep(1); }}><Icon name="check" size={16} />精算を確定する</button>
      </>}>
      <div className="row gap10" style={{ marginBottom: 16, padding: "12px 14px", background: "var(--deposit-soft)", borderRadius: 10 }}>
        <Avatar name={c.name} color={c.color} size={36} square />
        <div style={{ flex: 1 }}>
          <b style={{ fontSize: 13 }}>{c.name}</b>
          <div className="muted" style={{ fontSize: 11.5 }}>{item.channel} ・ 手数料 {item.commission}% ・ {item.orders}件</div>
        </div>
        <span className="badge dep">月次サイクル</span>
      </div>
      <div className="sec-title" style={{ marginBottom: 10 }}>精算内訳</div>
      <div className="ledger">
        <div className="ldg-row"><span className="row gap8"><Icon name="wallet" size={15} style={{ color: "var(--deposit)" }} />預かり金（{item.month} 月次 EC売上）</span><span className="lv"><Money v={gross} size={14} color="var(--deposit-ink)" /></span></div>
        <div className="hr" />
        <div className="ldg-row" style={{ background: "var(--revenue-soft)" }}><span className="row gap8"><Icon name="checkCircle" size={15} style={{ color: "var(--revenue)" }} />販売手数料（当社取り分 {item.commission}%）</span><span className="lv" style={{ color: "var(--revenue-ink)" }}>+<Money v={share} size={14} color="var(--revenue-ink)" /></span></div>
        <div className="ldg-row sub"><span>決済手数料（当社立替分）</span><span className="lv">−<Money v={fee} size={12.5} /></span></div>
        <div className="ldg-row total"><span>クライアントお支払額</span><span className="lv"><Money v={pay} size={15} color="#fff" /></span></div>
      </div>
      <div className="row gap8" style={{ marginTop: 14, fontSize: 12, color: "var(--ink-2)", background: "var(--surface-2)", padding: "11px 13px", borderRadius: 9 }}>
        <Icon name="alert" size={15} style={{ color: "var(--brand)", flex: "none" }} />
        ツアーと同じ「委託＝預かり」ですが、精算サイクルが<b>月次</b>です。確定すると <b>{db.yen(share)}</b> が確定売上へ振り替わります。
      </div>
    </Modal>
  );
}

Object.assign(window, { Sales });
