/* global React */
(function(){
const { useState } = React;

/* =============================================================
   PromotePost.jsx — promoted-posts flow (P1-10)
   --------------------------------------------------------------
   4 scenes: budget+duration → preview → payment → done.
   Models a Zarinpal-style Iranian gateway redirect.
   ============================================================= */

const fmtFa = (n) => String(n).replace(/\d/g, d => "۰۱۲۳۴۵۶۷۸۹"[d]);
const fmtToman = (rial) => fmtFa(Math.round(rial).toLocaleString("fa-IR"));

const BUDGETS = [
  { id: "tiny",  amount: 50000,  label: "۵۰ هزار تومن",  reach: "۱۲۰۰–۱۸۰۰", desc: "آزمایشی" },
  { id: "small", amount: 100000, label: "۱۰۰ هزار تومن", reach: "۲۵۰۰–۳۸۰۰", desc: "پربازده" },
  { id: "med",   amount: 200000, label: "۲۰۰ هزار تومن", reach: "۵۰۰۰–۸۰۰۰", desc: "محبوب", popular: true },
  { id: "big",   amount: 500000, label: "۵۰۰ هزار تومن", reach: "۱۴۰۰۰–۲۲۰۰۰", desc: "گسترده" },
];

const DURATIONS = [
  { id: "d1", days: 1, label: "۱ روز" },
  { id: "d3", days: 3, label: "۳ روز", popular: true },
  { id: "d7", days: 7, label: "یک هفته" },
];

const GATEWAYS = [
  { id: "zarinpal", name: "زرین‌پال",  color: "#FFB400", glyph: "Z" },
  { id: "mellat",   name: "بانک ملت",  color: "#E2202E", glyph: "م" },
  { id: "saman",    name: "بانک سامان", color: "#1C75BC", glyph: "س" },
];

window.PromotePost = function PromotePost({ open, post, onClose }) {
  const [scene, setScene] = useState("budget");
  const [budget, setBudget] = useState("med");
  const [duration, setDuration] = useState("d3");
  const [gateway, setGateway] = useState("zarinpal");
  const [paying, setPaying] = useState(false);

  if (!open) return null;
  const b = BUDGETS.find(x => x.id === budget);
  const d = DURATIONS.find(x => x.id === duration);
  const g = GATEWAYS.find(x => x.id === gateway);
  const total = b.amount * d.days;
  const close = () => { onClose?.(); setTimeout(() => setScene("budget"), 200); };

  const pay = () => {
    setPaying(true);
    setTimeout(() => { setPaying(false); setScene("done"); }, 1800);
  };

  return (
    <div className="kd-promote" role="dialog" aria-modal="true">
      <div className="kd-promote__backdrop" onClick={close} />
      <div className="kd-promote__sheet">
        <button className="kd-report__close" onClick={close} aria-label="بستن">
          <Icon name="close" size={16} stroke={2.2} />
        </button>

        {/* steps */}
        <div className="kd-promote__steps">
          {["budget", "review", "pay", "done"].map((s, i) => (
            <span key={s} className={`kd-promote__step ${scene === s ? "is-on" : ""} ${["budget","review","pay","done"].indexOf(scene) > i ? "is-done" : ""}`}>
              {fmtFa(i + 1)}
            </span>
          ))}
        </div>

        {scene === "budget" && (
          <React.Fragment>
            <h2 className="kd-report__h">پستت رو تبلیغ بزن</h2>
            <p className="kd-report__sub">پستت روی فید کاربرای هم‌سلیقه می‌ره. پرداخت یکباره — نه اشتراک.</p>

            <h3 className="kd-promote__h3">بودجه روزانه</h3>
            <div className="kd-promote__budgets">
              {BUDGETS.map(opt => (
                <button key={opt.id}
                  className={`kd-promote__budget ${budget === opt.id ? "is-on" : ""}`}
                  onClick={() => setBudget(opt.id)}>
                  {opt.popular && <span className="kd-promote__badge">محبوب</span>}
                  <span className="kd-promote__budget-amount">{opt.label}</span>
                  <span className="kd-promote__budget-reach">{opt.reach} بازدید/روز</span>
                  <span className="kd-promote__budget-desc">{opt.desc}</span>
                </button>
              ))}
            </div>

            <h3 className="kd-promote__h3">مدت</h3>
            <div className="kd-promote__durations">
              {DURATIONS.map(opt => (
                <button key={opt.id}
                  className={`kd-promote__duration ${duration === opt.id ? "is-on" : ""}`}
                  onClick={() => setDuration(opt.id)}>
                  {opt.label}
                  {opt.popular && <span className="kd-promote__badge kd-promote__badge--sm">✓</span>}
                </button>
              ))}
            </div>

            <div className="kd-promote__nav">
              <span className="kd-promote__total">
                مجموع: <b>{fmtToman(total)} تومن</b>
              </span>
              <button className="kd-btn kd-btn--primary kd-btn--lg" onClick={() => setScene("review")}>
                ادامه <Icon name="back" size={16} stroke={2.4} />
              </button>
            </div>
          </React.Fragment>
        )}

        {scene === "review" && (
          <React.Fragment>
            <button className="kd-login__back" onClick={() => setScene("budget")}>
              <Icon name="chevron" size={14} stroke={2.4} /> برگرد
            </button>
            <h2 className="kd-report__h">یه نگاه آخر</h2>
            <p className="kd-report__sub">قبل از پرداخت، می‌خوای دوباره نگاه کنی؟</p>

            <div className="kd-promote__review">
              <div className="kd-promote__review-row"><span>بودجه روزانه</span><b>{b.label}</b></div>
              <div className="kd-promote__review-row"><span>مدت</span><b>{d.label}</b></div>
              <div className="kd-promote__review-row"><span>بازدید تخمینی</span><b>{b.reach} × {fmtFa(d.days)} روز</b></div>
              <div className="kd-promote__review-row"><span>کارمزد</span><b>۰ تومن</b></div>
              <div className="kd-promote__review-row kd-promote__review-row--total"><span>قابل پرداخت</span><b>{fmtToman(total)} تومن</b></div>
            </div>

            <div className="kd-promote__nav">
              <button className="kd-setup__skip" onClick={() => setScene("budget")}>تغییر بدم</button>
              <button className="kd-btn kd-btn--primary kd-btn--lg" onClick={() => setScene("pay")}>
                پرداخت
              </button>
            </div>
          </React.Fragment>
        )}

        {scene === "pay" && (
          <React.Fragment>
            <button className="kd-login__back" onClick={() => setScene("review")}>
              <Icon name="chevron" size={14} stroke={2.4} /> برگرد
            </button>
            <h2 className="kd-report__h">روش پرداخت</h2>
            <p className="kd-report__sub">یکی از درگاه‌های ایرانی رو انتخاب کن.</p>

            <div className="kd-promote__gateways">
              {GATEWAYS.map(gw => (
                <button key={gw.id}
                  className={`kd-promote__gateway ${gateway === gw.id ? "is-on" : ""}`}
                  onClick={() => setGateway(gw.id)}>
                  <span className="kd-promote__gateway-glyph" style={{ background: gw.color }}>{gw.glyph}</span>
                  <span>{gw.name}</span>
                  <span className="kd-promote__radio">{gateway === gw.id && <i />}</span>
                </button>
              ))}
            </div>

            <p className="kd-promote__pay-summary">قابل پرداخت: <b>{fmtToman(total)} تومن</b></p>

            <div className="kd-promote__nav">
              <button className="kd-btn kd-btn--primary kd-btn--lg" style={{ width: "100%" }} disabled={paying} onClick={pay}>
                {paying ? "در حال انتقال به درگاه…" : `پرداخت با ${g.name}`}
              </button>
            </div>
            <p className="kd-promote__pay-foot">پرداخت رمزگذاری‌شده روی درگاه رسمی. اطلاعات کارتت پیش ما نمی‌مونه.</p>
          </React.Fragment>
        )}

        {scene === "done" && (
          <div className="kd-promote__done">
            <div className="kd-login__success-ring"><Icon name="check" size={40} stroke={3} /></div>
            <h2 className="kd-report__h" style={{ textAlign: "center" }}>تبلیغت شروع شد</h2>
            <p className="kd-report__sub" style={{ textAlign: "center" }}>
              تو ۱۵ دقیقه آینده پستت روی فید کاربرای هم‌سلیقه می‌ره.
            </p>

            <div className="kd-promote__dash">
              <div className="kd-promote__dash-h">پیش‌نمایش عملکرد</div>
              <div className="kd-promote__dash-grid">
                <div><b>۰</b><span>بازدید</span></div>
                <div><b>۰</b><span>لایک</span></div>
                <div><b>{fmtFa(d.days)} روز</b><span>باقی‌مونده</span></div>
                <div><b>{fmtToman(total)}</b><span>تومن مصرف</span></div>
              </div>
              <p className="kd-promote__dash-foot">جزئیات کامل توی صفحه‌ی پروفایلت موجوده.</p>
            </div>

            <button className="kd-btn kd-btn--primary kd-btn--md" style={{ width: "100%", marginTop: 16 }} onClick={close}>
              برگرد
            </button>
          </div>
        )}
      </div>
    </div>
  );
};
})();
