/* Interactive revenue calculator */
const { useState, useMemo } = React;

function Slider({ label, value, onChange, min, max, step, fmt }) {
  return (
    <div className="field">
      <div className="field-lab">
        <span className="nm">{label}</span>
        <span className="vl">{fmt ? fmt(value) : value}</span>
      </div>
      <input type="range" min={min} max={max} step={step} value={value}
        onChange={(e) => onChange(parseFloat(e.target.value))} />
    </div>
  );
}

function PriceInput({ label, value, onChange, hint }) {
  return (
    <div className="field">
      <div className="field-lab"><span className="nm">{label}</span><span className="mono small muted">{hint}</span></div>
      <div style={{ position: "relative" }}>
        <span className="num" style={{ position: "absolute", left: 12, top: "50%", transform: "translateY(-50%)", color: "var(--ink-mute)" }}>$</span>
        <input className="numinput" style={{ paddingLeft: 26 }} type="number" min="0" step="0.5" value={value}
          onChange={(e) => onChange(parseFloat(e.target.value) || 0)} />
      </div>
    </div>
  );
}

function RevenueCalculator() {
  const [account, setAccount] = useState("company");
  const [sbp, setSbp] = useState(true);
  const [monthlyPrice, setMonthlyPrice] = useState(7.99);
  const [yearlyPrice, setYearlyPrice] = useState(49.99);
  const [payingUsers, setPayingUsers] = useState(1200);
  const [annualShare, setAnnualShare] = useState(25);
  const [iosShare, setIosShare] = useState(60);
  const [margin, setMargin] = useState(35);
  const [citRate, setCitRate] = useState(10);

  const r = useMemo(() => {
    const annual = payingUsers * (annualShare / 100);
    const monthly = payingUsers - annual;
    const gross = monthly * monthlyPrice + annual * (yearlyPrice / 12);

    const fee = sbp ? 0.15 : 0.30;
    const blended = fee; // same band both stores under SBP / new-dev
    const platformFee = gross * blended;
    const proceeds = gross - platformFee;

    let incomeTax, taxLabel, taxNote;
    if (account === "individual") {
      incomeTax = gross * 0.07; // PIT 2% + VAT 5%
      taxLabel = "Thuế TNCN + VAT (≈7% doanh thu)";
      taxNote = "Khấu trừ trực tiếp trên doanh thu gộp.";
    } else {
      const profit = proceeds * (margin / 100);
      incomeTax = profit * (citRate / 100);
      taxLabel = `Thuế TNDN (CIT ${citRate}% × lợi nhuận)`;
      taxNote = citRate === 0 ? "Năm miễn thuế cho startup / SME mới." :
        citRate === 10 ? "Ưu đãi ngành phần mềm." : "Thuế suất tiêu chuẩn.";
    }
    const bankFx = proceeds * 0.015;
    const net = proceeds - incomeTax - bankFx;

    return { gross, platformFee, proceeds, incomeTax, bankFx, net, blended, taxLabel, taxNote,
      monthly, annual };
  }, [account, sbp, monthlyPrice, yearlyPrice, payingUsers, annualShare, iosShare, margin, citRate]);

  const waterfall = [
    { lab: "Doanh thu gộp", val: r.gross, type: "start" },
    { lab: `− Phí nền tảng (${(r.blended * 100).toFixed(0)}%)`, val: -r.platformFee, type: "cut" },
    { lab: "− " + r.taxLabel, val: -r.incomeTax, type: "cut" },
    { lab: "− Phí NH & đổi ngoại tệ (1.5%)", val: -r.bankFx, type: "cut" },
    { lab: "Thực nhận / tháng", val: r.net, type: "end" },
  ];

  return (
    <section className="section" id="calc" style={{ paddingTop: 0 }}>
      <div className="wrap">
        <SecHead num="04" eyebrow="Công cụ · Ước tính doanh thu"
          title="Các con số của <span class='serif-it' style='color:var(--accent)'>bạn</span>"
          lede="Điều chỉnh giá gói, lượng người trả phí và loại tài khoản để xem doanh thu thực nhận thay đổi thế nào theo từng trường hợp." />

        <div className="tool" style={{ overflow: "hidden" }}>
          <div className="row between center" style={{ padding: "16px 24px", borderBottom: "1px solid var(--line)", flexWrap: "wrap", gap: 12 }}>
            <span className="tool-tag"><span className="dot"></span>Bảng điều khiển</span>
            <Segmented accent value={account} onChange={setAccount}
              options={[{ value: "individual", label: "Cá nhân" }, { value: "company", label: "Doanh nghiệp" }]} />
          </div>

          <div style={{ display: "grid", gridTemplateColumns: "minmax(0,1fr) minmax(0,1.05fr)" }} className="calc-body">
            {/* CONTROLS */}
            <div style={{ padding: "clamp(22px,3vw,34px)", borderRight: "1px solid var(--line)", display: "grid", gap: 22 }}>
              <div className="grid2" style={{ gap: 16 }}>
                <PriceInput label="Gói tháng" value={monthlyPrice} onChange={setMonthlyPrice} hint="USD" />
                <PriceInput label="Gói năm" value={yearlyPrice} onChange={setYearlyPrice} hint="USD" />
              </div>
              <Slider label="Số người đăng ký trả phí" value={payingUsers} onChange={setPayingUsers}
                min={50} max={20000} step={50} fmt={(v) => v.toLocaleString("vi-VN") + " user"} />
              <Slider label="Tỷ lệ chọn gói năm" value={annualShare} onChange={setAnnualShare}
                min={0} max={100} step={5} fmt={(v) => v + "%"} />
              <Slider label="Tỷ lệ iOS / Android" value={iosShare} onChange={setIosShare}
                min={0} max={100} step={5} fmt={(v) => `${v}% iOS · ${100 - v}% Android`} />

              <div className="field">
                <div className="field-lab"><span className="nm">Apple Small Business (15%)</span></div>
                <Segmented value={sbp} onChange={setSbp}
                  options={[{ value: true, label: "Có · 15%" }, { value: false, label: "Không · 30%" }]} />
              </div>

              {account === "company" && (
                <div style={{ display: "grid", gap: 22, paddingTop: 20, borderTop: "1px dashed var(--line)" }}>
                  <p className="mono" style={{ fontSize: 11, letterSpacing: ".1em", textTransform: "uppercase", color: "var(--accent)", margin: 0 }}>Riêng cho doanh nghiệp</p>
                  <Slider label="Biên lợi nhuận ước tính (sau chi phí)" value={margin} onChange={setMargin}
                    min={5} max={80} step={5} fmt={(v) => v + "%"} />
                  <div className="field">
                    <div className="field-lab"><span className="nm">Thuế suất CIT</span></div>
                    <Segmented value={citRate} onChange={setCitRate}
                      options={[{ value: 0, label: "Miễn 0%" }, { value: 10, label: "Phần mềm 10%" }, { value: 20, label: "Chuẩn 20%" }]} />
                  </div>
                </div>
              )}
            </div>

            {/* RESULTS */}
            <div style={{ padding: "clamp(22px,3vw,34px)", background: "var(--card)" }}>
              <p className="mono" style={{ fontSize: 11, letterSpacing: ".12em", textTransform: "uppercase", color: "var(--ink-mute)", margin: "0 0 6px" }}>Thực nhận mỗi tháng</p>
              <div className="num" style={{ fontFamily: "var(--serif)", fontSize: "clamp(40px,6vw,64px)", lineHeight: 1, color: "var(--green)", letterSpacing: "-0.02em" }}>
                {fmtUSD(r.net)}
              </div>
              <p className="num muted" style={{ margin: "8px 0 0", fontSize: 15 }}>
                ≈ {fmtVND(r.net * USD_VND)} <span style={{ color: "var(--ink-faint)" }}>· tỷ giá {USD_VND.toLocaleString("vi-VN")}₫</span>
              </p>
              <div className="row" style={{ gap: 20, marginTop: 14, flexWrap: "wrap" }}>
                <div>
                  <span className="mono small muted">Năm (×12)</span><br />
                  <span className="num" style={{ fontSize: 19 }}>{fmtUSD(r.net * 12)}</span>
                </div>
                <div style={{ borderLeft: "1px solid var(--line)", paddingLeft: 20 }}>
                  <span className="mono small muted">Tỷ lệ giữ lại</span><br />
                  <span className="num" style={{ fontSize: 19 }}>{r.gross > 0 ? ((r.net / r.gross) * 100).toFixed(0) : 0}%</span>
                </div>
              </div>

              <hr className="rule" style={{ margin: "24px 0 18px" }} />

              <div className="stack" style={{ gap: 0 }}>
                {waterfall.map((s, i) => {
                  const pct = r.gross > 0 ? Math.abs(s.val) / r.gross * 100 : 0;
                  const color = s.type === "start" ? "var(--ink)" : s.type === "end" ? "var(--green)" : "var(--taupe-deep)";
                  return (
                    <div key={i} style={{ padding: "11px 0", borderBottom: i < waterfall.length - 1 ? "1px solid var(--line-soft)" : "none" }}>
                      <div className="row between center" style={{ marginBottom: 7 }}>
                        <span style={{ fontSize: 13.5, color: s.type === "cut" ? "var(--ink-soft)" : "var(--ink)", fontWeight: s.type === "end" ? 600 : 400 }}>{s.lab}</span>
                        <span className="num" style={{ fontSize: 15, color, fontWeight: s.type === "end" ? 600 : 400 }}>
                          {s.val < 0 ? "−" : ""}{fmtUSD(Math.abs(s.val))}
                        </span>
                      </div>
                      <div style={{ height: 6, background: "var(--paper-3)", borderRadius: 2 }}>
                        <div style={{ height: "100%", width: Math.min(100, pct) + "%", background: color, borderRadius: 2, transition: "width .3s" }} />
                      </div>
                    </div>
                  );
                })}
              </div>
              <p className="small muted" style={{ marginTop: 16 }}>{r.taxNote} Doanh thu gói năm đã chuẩn hóa về tháng. Ước tính minh họa.</p>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { RevenueCalculator });
