/* ============================================================
   Screen: EC委託販売（月次） + 案件追加モーダル
   ============================================================ */
const PLATFORM_COLOR = { "Shopify Plus": "#5E8E3E", "Shopify": "#5E8E3E", "BASE": "#1C1C1C", "楽天市場": "#BF0000", "STORES": "#0F1B2D" };

function ECProjects({ ctx }) {
  const { db, go, openAdd, consign } = ctx;
  const engs = db.ecEngagements;
  const curTotal = engs.reduce((a, e) => a + e.cur.held, 0);
  const pendingItems = (consign || []).filter((c) => c.status !== "settled");
  const pendingTotal = pendingItems.reduce((a, c) => a + c.held, 0);
  const settledThisQ = engs.reduce((a, e) => a + e.history.filter((h) => h.status === "settled").reduce((b, h) => b + h.share, 0), 0);

  return (
    <div className="page">
      <div className="row" style={{ justifyContent: "space-between", alignItems: "flex-end", marginBottom: 20 }}>
        <div>
          <h1 className="page-title">EC委託販売</h1>
          <p className="page-sub">クライアントECの代理販売（委託）。売上は預かり金として貯まり、<b>月次</b>で精算します。</p>
        </div>
        <button className="btn primary" onClick={() => openAdd("ec")}><Icon name="plus" size={16} />案件を追加</button>
      </div>

      {/* KPIs */}
      <div className="grid cols-4" style={{ gap: 18, marginBottom: 24 }}>
        <div className="card card-pad">
          <div className="row gap6" style={{ fontSize: 11.5, color: "var(--ink-3)", fontWeight: 600 }}><Icon name="globe" size={13} />稼働中の案件</div>
          <div style={{ marginTop: 8, fontSize: 22, fontWeight: 700 }}>{engs.length}<span style={{ fontSize: 13, color: "var(--ink-3)", fontWeight: 500, marginLeft: 4 }}>件</span></div>
        </div>
        <div className="card card-pad">
          <div className="row gap6" style={{ fontSize: 11.5, color: "var(--deposit-ink)", fontWeight: 600 }}><Icon name="lock" size={13} />当月 預かり累計（6月）</div>
          <div style={{ marginTop: 8 }}><Money v={curTotal} size={21} color="var(--deposit-ink)" /></div>
          <div className="muted" style={{ fontSize: 10.5, marginTop: 4 }}>集計中・6月末に締め</div>
        </div>
        <div className="card card-pad" style={{ borderColor: pendingTotal ? "var(--brand-soft)" : "var(--border)" }}>
          <div className="row gap6" style={{ fontSize: 11.5, color: "var(--st-pend-ink)", fontWeight: 600 }}><Icon name="clock" size={13} />月次精算待ち</div>
          <div style={{ marginTop: 8 }}><Money v={pendingTotal} size={21} color="var(--st-pend-ink)" /></div>
          <div className="muted" style={{ fontSize: 10.5, marginTop: 4 }}>{pendingItems.length}件 ・ 5月締め分</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} />精算済 手数料（直近）</div>
          <div style={{ marginTop: 8 }}><Money v={settledThisQ} size={21} color="var(--revenue)" /></div>
          <div className="muted" style={{ fontSize: 10.5, marginTop: 4 }}>当社の確定売上</div>
        </div>
      </div>

      <div className="sec-title" style={{ marginBottom: 14 }}>委託EC案件</div>
      <div className="col" style={{ gap: 18 }}>
        {engs.map((e) => <ECCard key={e.clientId} eng={e} ctx={ctx} />)}
      </div>
    </div>
  );
}

function ECCard({ eng, ctx }) {
  const { db, go } = ctx;
  const c = db.clientById(eng.clientId);
  const curShare = Math.round(eng.cur.held * eng.commission / 100);
  const pColor = PLATFORM_COLOR[eng.platform] || "#666";
  return (
    <div className="card">
      <div className="card-pad" style={{ paddingBottom: 18 }}>
        <div className="row gap12">
          <Avatar name={c.name} color={c.color} size={44} square />
          <div style={{ flex: 1, minWidth: 0 }}>
            <div className="row gap8">
              <b style={{ fontSize: 14.5 }}>{c.name}</b>
              <span className="chip" style={{ height: 22 }}><span className="cdot" style={{ background: pColor, borderRadius: 2 }} />{eng.platform}</span>
              <span className="badge done" style={{ height: 21 }}>稼働中</span>
            </div>
            <div className="muted" style={{ fontSize: 11.5, marginTop: 4 }}>{eng.note} ・ 開始 {eng.since} ・ 委託手数料 {eng.commission}%</div>
          </div>
          <button className="btn sm" onClick={() => go("client", c.id)}>クライアント<Icon name="chevRight" size={14} /></button>
        </div>

        {/* current month accumulating */}
        <div className="row" style={{ gap: 14, marginTop: 18, alignItems: "stretch" }}>
          <div style={{ flex: 1, background: "var(--deposit-soft)", borderRadius: 11, padding: "13px 16px" }}>
            <div className="row" style={{ justifyContent: "space-between" }}>
              <span style={{ fontSize: 11.5, color: "var(--deposit-ink)", fontWeight: 600 }}>当月の預かり（{eng.cur.month}・集計中）</span>
              <span className="badge dep" style={{ height: 20 }}>{eng.cur.orders}件</span>
            </div>
            <div className="row" style={{ alignItems: "baseline", gap: 12, marginTop: 8 }}>
              <Money v={eng.cur.held} size={22} color="var(--deposit-ink)" />
              <Icon name="arrowRight" size={15} style={{ color: "var(--ink-4)" }} />
              <div className="col">
                <span className="muted" style={{ fontSize: 10.5 }}>見込手数料 {eng.commission}%</span>
                <Money v={curShare} size={14} color="var(--revenue)" />
              </div>
            </div>
          </div>
        </div>

        {/* monthly history */}
        <div style={{ marginTop: 20 }}>
          <div className="muted" style={{ fontSize: 11, fontWeight: 600, marginBottom: 8 }}>月次精算の履歴</div>
          <table className="tbl" style={{ fontSize: 12.5 }}>
            <thead><tr><th>対象月</th><th className="r">預かり金</th><th className="r">当社手数料</th><th className="r">クライアント支払</th><th style={{ width: 110 }}>ステータス</th></tr></thead>
            <tbody>
              {eng.history.map((h) => (
                <tr key={h.month}>
                  <td className="mono">{h.month}</td>
                  <td className="r"><Money v={h.held} size={12.5} color="var(--deposit-ink)" /></td>
                  <td className="r"><Money v={h.share} size={12.5} color="var(--revenue)" /></td>
                  <td className="r"><Money v={h.held - h.share} size={12.5} /></td>
                  <td>
                    {h.status === "pending"
                      ? <button className="btn primary sm" style={{ height: 28 }} onClick={() => go("sales")}>月次精算へ</button>
                      : <span className="badge done"><Icon name="check" size={12} />精算済</span>}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

/* ---------- 案件を追加（デモ） ---------- */
const PROJ_TYPES = [
  { key: "tour", label: "ツアー物販", desc: "委託・預かり", cycle: "ツアー終了時に精算", held: true },
  { key: "ec", label: "EC委託", desc: "委託・預かり", cycle: "月次（月末締め）で精算", held: true },
  { key: "fee", label: "倉庫・発送受託", desc: "役務手数料", cycle: "月次請求（預かりなし）", held: false },
  { key: "wholesale", label: "卸（買取）", desc: "自社売上", cycle: "月次請求（預かりなし）", held: false },
];

function AddProjectModal({ ctx, onClose, initialType = "tour" }) {
  const { db, toast } = ctx;
  const [type, setType] = React.useState(initialType);
  const [client, setClient] = React.useState(db.clients[0].id);
  const [name, setName] = React.useState("");
  const t = PROJ_TYPES.find((x) => x.key === type);

  const create = () => { toast(`${t.label}案件「${name || "新規案件"}」を作成しました（デモ）`); onClose(); };

  return (
    <Modal title="案件を追加" sub="クライアントとの新しい取引案件を登録します" onClose={onClose} wide
      foot={<>
        <div className="row gap8" style={{ fontSize: 11.5, color: "var(--ink-3)" }}><Icon name="lock" size={14} />営業/CRMロールが登録</div>
        <button className="btn" style={{ marginLeft: "auto" }} onClick={onClose}>キャンセル</button>
        <button className="btn primary" onClick={create}><Icon name="check" size={16} />案件を作成</button>
      </>}>
      {/* type selector */}
      <div className="fld" style={{ marginBottom: 16 }}>
        <span>案件タイプ</span>
        <div className="grid cols-4" style={{ gap: 8, marginTop: 2 }}>
          {PROJ_TYPES.map((p) => (
            <button key={p.key} onClick={() => setType(p.key)}
              style={{ textAlign: "left", padding: "10px 12px", borderRadius: 10, cursor: "pointer", fontFamily: "inherit",
                border: "1.5px solid " + (type === p.key ? "var(--brand)" : "var(--border-2)"),
                background: type === p.key ? "var(--brand-wash)" : "var(--surface)" }}>
              <div style={{ fontSize: 12.5, fontWeight: 700, color: type === p.key ? "var(--brand-press)" : "var(--ink)" }}>{p.label}</div>
              <div style={{ fontSize: 10.5, color: "var(--ink-3)", marginTop: 2 }}>{p.desc}</div>
            </button>
          ))}
        </div>
      </div>

      {/* settlement cycle indicator */}
      <div className="row gap10" style={{ padding: "11px 14px", borderRadius: 10, marginBottom: 18,
        background: t.held ? "var(--deposit-soft)" : "var(--surface-2)" }}>
        <Icon name={t.held ? "lock" : "checkCircle"} size={16} style={{ color: t.held ? "var(--deposit)" : "var(--revenue)" }} />
        <div style={{ fontSize: 12.5 }}>
          <b>精算サイクル：{t.cycle}</b>
          <div className="muted" style={{ fontSize: 11, marginTop: 1 }}>{t.held ? "顧客の支払いは全額『預かり金』として計上され、手数料のみ自社売上になります。" : "預かり金は発生しません（役務対価・買取売上は全額が自社売上）。"}</div>
        </div>
      </div>

      <div className="grid cols-2" style={{ gap: 14 }}>
        <label className="fld">クライアント
          <select value={client} onChange={(e) => setClient(e.target.value)}>
            {db.clients.map((c) => <option key={c.id} value={c.id}>{c.name}</option>)}
          </select>
        </label>
        <label className="fld">案件名
          <input value={name} onChange={(e) => setName(e.target.value)} placeholder={type === "ec" ? "例）公式EC 2026" : "例）◯◯ TOUR 2026"} />
        </label>

        {type === "tour" && <>
          <label className="fld">開催期間（開始）<input type="date" defaultValue="2026-07-01" /></label>
          <label className="fld">開催期間（終了）<input type="date" defaultValue="2026-09-15" /></label>
          <label className="fld">販売手数料率（%）<input defaultValue="25" /></label>
          <label className="fld">公演数<input defaultValue="10" /></label>
        </>}
        {type === "ec" && <>
          <label className="fld">プラットフォーム
            <select defaultValue="Shopify"><option>Shopify</option><option>Shopify Plus</option><option>BASE</option><option>楽天市場</option><option>STORES</option></select>
          </label>
          <label className="fld">開始日<input type="date" defaultValue="2026-07-01" /></label>
          <label className="fld">販売手数料率（%）<input defaultValue="20" /></label>
          <label className="fld">締め日<select defaultValue="月末"><option>月末</option><option>20日</option><option>15日</option></select></label>
        </>}
        {type === "fee" && <>
          <label className="fld">倉庫保管料（月額）<input defaultValue="120000" /></label>
          <label className="fld">発送代行料（1件）<input defaultValue="320" /></label>
        </>}
        {type === "wholesale" && <>
          <label className="fld">卸率（%）<input defaultValue="60" /></label>
          <label className="fld">対象商品<select><option>兄弟会社制作品</option><option>個別指定</option></select></label>
        </>}
      </div>
    </Modal>
  );
}

Object.assign(window, { ECProjects, AddProjectModal });
