/* ============================================================
   Screen: Invoices & Reports — 請求書・レポート
   ============================================================ */
function Invoices({ ctx }) {
  const { db, toast } = ctx;
  const [tab, setTab] = React.useState("invoices");
  const [preview, setPreview] = React.useState(null);

  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>
        <button className="btn primary" onClick={() => setPreview(db.invoices[1])}><Icon name="plus" size={16} />請求書を作成</button>
      </div>

      <div className="tabs" style={{ marginBottom: 18 }}>
        <div className={"tab" + (tab === "invoices" ? " on" : "")} onClick={() => setTab("invoices")}>請求書</div>
        <div className={"tab" + (tab === "reports" ? " on" : "")} onClick={() => setTab("reports")}>売上レポート</div>
      </div>

      {tab === "invoices" && <InvoiceList ctx={ctx} onOpen={setPreview} />}
      {tab === "reports" && <Reports ctx={ctx} />}

      {preview && <InvoicePreview ctx={ctx} inv={preview} onClose={() => setPreview(null)} />}
    </div>
  );
}

function InvoiceList({ ctx, onOpen }) {
  const { db } = ctx;
  const sum = (st) => db.invoices.filter((i) => i.status === st).reduce((a, i) => a + i.total, 0);
  return (
    <>
      <div className="grid cols-3" style={{ gap: 14, marginBottom: 16 }}>
        <div className="card card-pad"><div className="row gap6" style={{ fontSize: 11.5, color: "var(--ink-3)", fontWeight: 600 }}><Icon name="doc" size={13} />下書き</div><div style={{ marginTop: 8 }}><Money v={sum("draft")} size={20} color="var(--ink-3)" /></div></div>
        <div className="card card-pad"><div className="row gap6" style={{ fontSize: 11.5, color: "var(--st-prog-ink)", fontWeight: 600 }}><Icon name="mail" size={13} />送付済（入金待ち）</div><div style={{ marginTop: 8 }}><Money v={sum("sent")} size={20} color="var(--st-prog-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} />入金済（当期）</div><div style={{ marginTop: 8 }}><Money v={sum("paid")} size={20} color="var(--revenue-ink)" /></div></div>
      </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 className="r">金額</th><th></th></tr></thead>
          <tbody>
            {db.invoices.map((iv) => {
              const c = db.clientById(iv.clientId);
              return (
                <tr key={iv.id} className="clickable" onClick={() => onOpen(iv)}>
                  <td className="mono" style={{ fontSize: 12 }}><b>{iv.id}</b></td>
                  <td><div className="row gap8"><Avatar name={c.name} color={c.color} size={24} square /><span style={{ fontSize: 12.5 }}>{c.name}</span></div></td>
                  <td><span className="muted" style={{ fontSize: 12 }}>{iv.kind}</span></td>
                  <td className="mono muted" style={{ fontSize: 12 }}>{iv.issue}</td>
                  <td className="mono muted" style={{ fontSize: 12 }}>{iv.due}</td>
                  <td><StatusBadge status={iv.status} /></td>
                  <td className="r"><Money v={iv.total} size={13} /></td>
                  <td className="r" style={{ width: 40 }}><Icon name="chevRight" size={15} style={{ color: "var(--ink-4)" }} /></td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </>
  );
}

/* ---------- Reports ---------- */
function Reports({ ctx }) {
  const { db } = ctx;
  const byBiz = [
    { biz: "tour", v: 3200000, label: "物販-ツアー（取り分）" },
    { biz: "ec", v: 1180000, label: "EC" },
    { biz: "warehouse", v: 780000, label: "倉庫業" },
    { biz: "single", v: 920000, label: "物販-単発・卸" },
  ];
  const maxB = Math.max(...byBiz.map((b) => b.v));
  const byClient = [...db.clients].filter((c) => c.confirmedYTD > 0).sort((a, b) => b.confirmedYTD - a.confirmedYTD);
  const maxC = Math.max(...byClient.map((c) => c.confirmedYTD));

  return (
    <div className="col gap16">
      <div className="grid cols-2" style={{ gap: 16 }}>
        <div className="card">
          <div className="card-head" style={{ justifyContent: "space-between" }}><h3>事業別 確定売上（当期）</h3><button className="btn ghost sm"><Icon name="download" size={14} />PDF</button></div>
          <div className="card-pad col gap16">
            {byBiz.map((b) => (
              <div key={b.biz}>
                <div className="row" style={{ justifyContent: "space-between", marginBottom: 6 }}>
                  <span className="relseg-label"><span className="sq" style={{ background: db.businessTypes[b.biz].color }} />{b.label}</span>
                  <Money v={b.v} size={13} />
                </div>
                <div className="prog" style={{ height: 10 }}><i style={{ width: (b.v / maxB) * 100 + "%", background: db.businessTypes[b.biz].color }} /></div>
              </div>
            ))}
          </div>
        </div>

        <div className="card">
          <div className="card-head"><h3>推移（預かり vs 確定）</h3></div>
          <div className="card-pad">
            <TrendChart data={db.trend} />
            <div className="row gap16" style={{ marginTop: 14, justifyContent: "center" }}>
              <span className="relseg-label"><span className="sq" style={{ background: "var(--deposit)" }} />預かり金</span>
              <span className="relseg-label"><span className="sq" style={{ background: "var(--revenue)" }} />確定売上</span>
            </div>
          </div>
        </div>
      </div>

      <div className="card">
        <div className="card-head" style={{ justifyContent: "space-between" }}><h3>クライアント別 確定売上ランキング（当期）</h3><button className="btn ghost sm"><Icon name="download" size={14} />CSV</button></div>
        <div className="card-pad col gap14">
          {byClient.map((c, i) => (
            <div key={c.id} className="row gap12">
              <span className="mono" style={{ fontSize: 12, color: "var(--ink-4)", width: 18 }}>{i + 1}</span>
              <Avatar name={c.name} color={c.color} size={28} square />
              <span style={{ fontSize: 13, width: 180, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{c.name}</span>
              <div className="prog" style={{ flex: 1, height: 12 }}><i style={{ width: (c.confirmedYTD / maxC) * 100 + "%", background: "var(--brand)" }} /></div>
              <Money v={c.confirmedYTD} size={13} />
              {c.heldNow > 0 && <span className="badge dep" style={{ height: 20 }}>預かり {db.yen(c.heldNow)}</span>}
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

/* ---------- Invoice preview (unified format) ---------- */
function InvoicePreview({ ctx, inv, onClose }) {
  const { db, toast } = ctx;
  const c = db.clientById(inv.clientId);
  const lines = invoiceLines(inv, db);
  const sub = lines.reduce((a, l) => a + l.amt, 0);
  const tax = Math.round(sub * 0.1);
  const total = sub + tax;

  return (
    <Modal title={"請求書 " + inv.id} sub={c.name + " 宛 ・ " + inv.kind} onClose={onClose} wide
      foot={<>
        <StatusBadge status={inv.status} />
        <button className="btn" style={{ marginLeft: "auto" }} onClick={() => toast("PDFをダウンロードしました（デモ）")}><Icon name="download" size={15} />PDF</button>
        {inv.status === "draft"
          ? <button className="btn primary" onClick={() => { toast(inv.id + " を送付しました"); onClose(); }}><Icon name="mail" size={15} />確定して送付</button>
          : <button className="btn primary" onClick={() => toast("メールで再送しました（デモ）")}><Icon name="mail" size={15} />再送</button>}
      </>}>
      {/* invoice document */}
      <div style={{ background: "#fff", border: "1px solid var(--border)", borderRadius: 12, padding: "26px 28px" }}>
        <div className="row" style={{ justifyContent: "space-between", alignItems: "flex-start", marginBottom: 24 }}>
          <div>
            <div style={{ fontSize: 21, fontWeight: 700, letterSpacing: ".04em" }}>請求書</div>
            <div className="mono muted" style={{ fontSize: 12, marginTop: 4 }}>{inv.id}</div>
          </div>
          <div className="row gap10" style={{ alignItems: "center" }}>
            <img src="assets/penguin_circle.png" width="44" height="44" alt="" />
            <div style={{ textAlign: "right" }}>
              <b style={{ fontSize: 14 }}>HIGHFIVE株式会社</b>
              <div className="muted" style={{ fontSize: 11, lineHeight: 1.5, marginTop: 2 }}>〒150-0001 東京都渋谷区●●1-2-3<br />登録番号 T1234567890123</div>
            </div>
          </div>
        </div>

        <div className="row" style={{ justifyContent: "space-between", alignItems: "flex-end", marginBottom: 22 }}>
          <div>
            <div style={{ fontSize: 16, fontWeight: 700, borderBottom: "2px solid var(--ink)", paddingBottom: 4, display: "inline-block" }}>{c.name} 御中</div>
            <div className="muted" style={{ fontSize: 12, marginTop: 10, lineHeight: 1.7 }}>
              発行日：{inv.issue}<br />支払期日：{inv.due}<br />{inv.period ? "対象期間：" + inv.period : inv.kind}
            </div>
          </div>
          <div style={{ textAlign: "right", background: "var(--brand-wash)", padding: "12px 18px", borderRadius: 10 }}>
            <div className="muted" style={{ fontSize: 11, fontWeight: 600 }}>ご請求金額（税込）</div>
            <div style={{ fontSize: 26, fontWeight: 700, color: "var(--brand-press)", marginTop: 2 }} className="num">¥{total.toLocaleString("ja-JP")}</div>
          </div>
        </div>

        <table className="tbl" style={{ marginBottom: 4 }}>
          <thead><tr><th>品目</th><th className="r">数量</th><th className="r">単価</th><th className="r">金額</th></tr></thead>
          <tbody>
            {lines.map((l, i) => (
              <tr key={i}>
                <td style={{ fontSize: 12.5 }}>{l.name}{l.note && <div className="sub">{l.note}</div>}</td>
                <td className="r mono" style={{ fontSize: 12 }}>{l.qty}</td>
                <td className="r"><Money v={l.unit} size={12.5} /></td>
                <td className="r"><Money v={l.amt} size={12.5} color={l.amt < 0 ? "#B0492C" : null} /></td>
              </tr>
            ))}
          </tbody>
        </table>
        <div className="col" style={{ alignItems: "flex-end", gap: 6, marginTop: 14, paddingRight: 14 }}>
          <div className="row gap20" style={{ fontSize: 12.5 }}><span className="muted">小計</span><span className="num" style={{ width: 120, textAlign: "right" }}>{db.yen(sub)}</span></div>
          <div className="row gap20" style={{ fontSize: 12.5 }}><span className="muted">消費税（10%）</span><span className="num" style={{ width: 120, textAlign: "right" }}>{db.yen(tax)}</span></div>
          <div className="row gap20" style={{ fontSize: 15, fontWeight: 700, borderTop: "2px solid var(--ink)", paddingTop: 8, marginTop: 2 }}><span>合計</span><span className="num" style={{ width: 120, textAlign: "right" }}>{db.yen(total)}</span></div>
        </div>
      </div>
      <div className="row gap8" style={{ marginTop: 12, fontSize: 11.5, color: "var(--ink-3)" }}><Icon name="layers" size={14} />全社統一テンプレート ・ 適格請求書（インボイス）対応</div>
    </Modal>
  );
}

function invoiceLines(inv, db) {
  if (inv.kind === "ツアー精算") {
    const t = db.tourById(inv.tourId);
    return [
      { name: "ツアー物販 売上（お預かり総額）", note: t.name, qty: 1, unit: t.gross, amt: t.gross },
      { name: `販売手数料（当社取り分 ${t.commission}%）`, qty: 1, unit: -t.settledShare, amt: -t.settledShare },
      { name: "決済手数料（立替分）", qty: 1, unit: -t.paymentFee, amt: -t.paymentFee },
    ];
  }
  if (inv.kind.includes("倉庫")) {
    return [
      { name: "倉庫保管料", note: inv.period + " 月額", qty: 1, unit: 180000, amt: 180000 },
      { name: "発送代行料", note: "375件 × ¥320", qty: 375, unit: 320, amt: 120000 },
    ];
  }
  // 月次請求
  return [
    { name: "EC 代理販売手数料", note: inv.period, qty: 1, unit: 642000, amt: 642000 },
    { name: "倉庫保管料", qty: 1, unit: 140000, amt: 140000 },
    { name: "発送代行料", note: "1,580件 × ¥280", qty: 1580, unit: 280, amt: 442400 },
  ].filter((_, i) => i < (inv.total > 1000000 ? 3 : 1));
}

window.Invoices = Invoices;
