/* ============================================================
   bezikaron — путь покупки. Гость-чекаут, короткие шаги,
   крупные поля/кнопки (45+), прозрачность списаний.
   mode: 'order' (разовый) | 'subscribe' (подписка).
   ============================================================ */

function Checkout({ mode, initialPackage, initialPlan, initialSubTier, initialMonument, preselected, onClose, onDone, onSwitchToSubscribe }) {
  const D = window.DATA;
  const isSub = mode === 'subscribe';

  const [step, setStep] = React.useState(0);
  const [form, setForm] = React.useState({
    pkg: initialPackage || 'plus',
    plan: initialPlan || 'year',
    subTier: initialSubTier || 'extended',
    monument: initialMonument || 'single',
    placeMethod: 'search',
    cemetery: '', deceased: '', photoAttached: false,
    name: '', phone: '', email: '', when: 'any', comment: '',
    payMethod: 'card',
  });
  const set = (patch) => setForm((f) => ({ ...f, ...patch }));
  const scrollRef = React.useRef(null);

  // шаги: если уровень/услуга уже выбраны на лендинге — пропускаем первый шаг выбора
  const steps = preselected ? ['place', 'details', 'pay'] : ['service', 'place', 'details', 'pay'];
  const total = steps.length;
  const cur = steps[step];

  React.useEffect(() => { if (scrollRef.current) scrollRef.current.scrollTop = 0; }, [step]);

  const pkg = D.packages.find((p) => p.id === form.pkg);
  const orderPrice = pkg ? window.PRICE.pkg(pkg.id, form.monument) : 0;
  const subPrice = window.PRICE.sub(form.monument, form.subTier, form.plan);

  // валидация шага
  const canNext = (() => {
    if (cur === 'place') {
      if (form.placeMethod === 'search') return form.cemetery && form.deceased;
      if (form.placeMethod === 'photo') return form.photoAttached;
      return true; // help — без обязательных полей
    }
    if (cur === 'details') return form.name.trim() && form.phone.trim().length >= 7;
    return true;
  })();

  const [verifying, setVerifying] = React.useState(false);
  const advance = () => { if (step < total - 1) setStep(step + 1); else onDone({ ...form, mode }); };
  const next = () => {
    // после шага «место» — проверка/подтверждение надгробия (если есть что проверять)
    if (cur === 'place' && (form.placeMethod === 'search' || form.placeMethod === 'photo')) {
      setVerifying(true);
      return;
    }
    advance();
  };
  const onVerified = () => { setVerifying(false); advance(); };
  const back = () => { if (step > 0) setStep(step - 1); else onClose(); };

  const price = isSub ? `${window.fmt(subPrice.perMonth)} ₪/חודש` : `${window.fmt(orderPrice)} ₪`;

  if (verifying) {
    return <VerifyStep method={form.placeMethod} form={form} onDone={onVerified} />;
  }

  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: 'var(--bg)' }}>
      {/* шапка: назад + прогресс */}
      <div style={{ paddingTop: 56, paddingInline: 22, paddingBottom: 14, background: 'var(--bg)', borderBottom: '1px solid var(--line-soft)' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 14 }}>
          <button onClick={back} aria-label="חזרה" style={{
            width: 40, height: 40, borderRadius: 999, border: '1px solid var(--line)', background: 'var(--surface)',
            display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', color: 'var(--ink)', flexShrink: 0,
          }}><Icon name="arrowL" size={19} /></button>
          <div style={{ flex: 1 }}>
            <div className="faint" style={{ fontSize: 13, fontWeight: 700 }}>שלב {step + 1} מתוך {total}</div>
            <div style={{ fontWeight: 700, fontSize: 15 }}>{STEP_TITLE[isSub ? 'sub' : 'order'][cur]}</div>
          </div>
          <span className="chip" style={{ background: 'var(--accent-tint)', borderColor: 'transparent', color: 'var(--accent-deep)' }}>{price}</span>
        </div>
        {/* прогресс-полоса */}
        <div style={{ display: 'flex', gap: 6 }}>
          {steps.map((_, i) => (
            <div key={i} style={{ flex: 1, height: 5, borderRadius: 999, background: i <= step ? 'var(--accent)' : 'var(--line)', transition: 'background .3s ease' }} />
          ))}
        </div>
      </div>

      {/* контент шага */}
      <div ref={scrollRef} className="no-scrollbar" style={{ flex: 1, overflowY: 'auto', padding: '24px 22px 20px' }}>
        <div key={cur} className="fade-up">
          {cur === 'service' && (isSub ? <PlanStep form={form} set={set} /> : <ServiceStep form={form} set={set} />)}
          {cur === 'place' && <PlaceStep form={form} set={set} />}
          {cur === 'details' && <DetailsStep form={form} set={set} isSub={isSub} />}
          {cur === 'pay' && <PayStep form={form} set={set} isSub={isSub} pkg={pkg} orderPrice={orderPrice} subPrice={subPrice} />}
        </div>
      </div>

      {/* sticky CTA — зона большого пальца */}
      <div style={{ padding: '14px 22px calc(14px + 20px)', background: 'color-mix(in oklch, var(--bg) 90%, transparent)', backdropFilter: 'blur(10px)', borderTop: '1px solid var(--line-soft)' }}>
        {cur === 'pay' && (
          <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', gap: 8, marginBottom: 12, color: 'var(--ink-soft)', fontSize: 13 }}>
            <Icon name="lock" size={15} style={{ color: 'var(--accent-deep)' }} />
            תשלום מאובטח · איננו שומרים את פרטי הכרטיס
          </div>
        )}
        <button className="btn btn-primary" disabled={!canNext} onClick={next}
          style={{ opacity: canNext ? 1 : 0.45, cursor: canNext ? 'pointer' : 'not-allowed' }}>
          {cur === 'pay' ? (isSub ? `להפעיל מנוי · ${window.fmt(subPrice.perMonth)} ₪/חודש` : `לתשלום ${window.fmt(orderPrice)} ₪`) : 'להמשיך'}
          {cur !== 'pay' && <Icon name="arrow" size={20} stroke={2} />}
        </button>
      </div>
    </div>
  );
}

const STEP_TITLE = {
  order: { service: 'בחירת שירות', place: 'היכן נמצא הקבר', details: 'פרטי קשר', pay: 'תשלום' },
  sub:   { service: 'בחירת תוכנית',  place: 'היכן נמצא הקבר', details: 'פרטי קשר', pay: 'הפעלת מנוי' },
};

// ---------- Шаг: услуга (разовый) ----------
function ServiceStep({ form, set }) {
  const D = window.DATA;
  return (
    <div>
      <h2 className="t-h2" style={{ marginBottom: 16 }}>איזה טיפול דרוש?</h2>

      <span className="field-label">סוג המצבה</span>
      <window.MonumentToggle value={form.monument} onChange={(v) => set({ monument: v })} />

      <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
        {D.packages.map((p) => {
          const on = form.pkg === p.id;
          return (
            <button key={p.id} onClick={() => set({ pkg: p.id })} style={selectCard(on)}>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12 }}>
                <div style={{ textAlign: 'start' }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    <span className="t-h3" style={{ fontSize: 19 }}>{p.name}</span>
                    {p.popular && <span style={{ fontSize: 11, fontWeight: 700, color: 'var(--accent-deep)', background: 'var(--accent-tint)', padding: '3px 8px', borderRadius: 999 }}>נפוץ</span>}
                  </div>
                  <p className="t-small" style={{ marginTop: 3 }}>{p.summary}</p>
                </div>
                <Radio on={on} />
              </div>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 6, marginTop: 12 }}>
                <span className="t-price" style={{ fontSize: 22 }}>{window.fmt(p.price[form.monument])} ₪</span>
                <span className="faint" style={{ fontSize: 13 }}>חד-פעמי</span>
              </div>
            </button>
          );
        })}
      </div>
      <p className="t-small" style={{ marginTop: 16, display: 'flex', gap: 8, alignItems: 'flex-start' }}>
        <Icon name="help" size={16} style={{ color: 'var(--bronze-deep)', flexShrink: 0, marginTop: 1 }} />
        {D.typeNote}
      </p>
    </div>
  );
}

// ---------- Шаг: план (подписка) ----------
function PlanStep({ form, set }) {
  const sub = window.DATA.subscription;
  return (
    <div>
      <h2 className="t-h2" style={{ marginBottom: 6 }}>{sub.title}</h2>
      <p className="t-lead" style={{ marginBottom: 18 }}>בחרו סוג מצבה, רמת טיפול ואמצעי תשלום.</p>

      <span className="field-label">סוג המצבה</span>
      <window.MonumentToggle value={form.monument} onChange={(v) => set({ monument: v })} />

      <span className="field-label">רמת הטיפול</span>
      <window.SubTierCards type={form.monument} value={form.subTier} onChange={(v) => set({ subTier: v })} />

      <p className="t-small" style={{ margin: '12px 2px 0', display: 'flex', gap: 8, alignItems: 'flex-start' }}>
        <Icon name="heart" size={16} style={{ color: 'var(--accent-deep)', flexShrink: 0, marginTop: 1 }} />
        {sub.sharedNote}
      </p>

      <div style={{ height: 1, background: 'var(--line)', margin: '20px 0 4px' }} />

      <span className="field-label">אמצעי תשלום</span>
      <window.BillingOptions type={form.monument} tier={form.subTier} value={form.plan} onChange={(v) => set({ plan: v })} />

      <p className="t-small" style={{ marginTop: 14, textAlign: 'center' }}>{sub.cancelNote}</p>
    </div>
  );
}

// ---------- Шаг: место (3 пути) ----------
function PlaceStep({ form, set }) {
  const D = window.DATA;
  const methods = [
    { id: 'search', icon: 'search', label: 'יודע/ת את בית העלמין והשם' },
    { id: 'photo', icon: 'upload', label: 'אצרף תמונה של המקום' },
    { id: 'help', icon: 'help', label: 'עזרו לי למצוא' },
  ];
  return (
    <div>
      <h2 className="t-h2" style={{ marginBottom: 6 }}>היכן נמצא הקבר?</h2>
      <p className="t-lead" style={{ marginBottom: 18 }}>לא יודעים את המיקום המדויק — זו לא בעיה. בחרו מה שנוח לכם.</p>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginBottom: 22 }}>
        {methods.map((m) => {
          const on = form.placeMethod === m.id;
          return (
            <button key={m.id} onClick={() => set({ placeMethod: m.id })} style={{
              ...selectCard(on), padding: 16, display: 'flex', alignItems: 'center', gap: 14, flexDirection: 'row',
            }}>
              <IconDisc name={m.icon} size={42} />
              <span className="t-body" style={{ fontWeight: 700, flex: 1, textAlign: 'start' }}>{m.label}</span>
              <Radio on={on} />
            </button>
          );
        })}
      </div>

      {form.placeMethod === 'search' && (
        <div className="fade-up" style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <div>
            <label className="field-label">בית עלמין</label>
            <select className="field" value={form.cemetery} onChange={(e) => set({ cemetery: e.target.value })}>
              <option value="">בחרו בית עלמין…</option>
              {D.cemeteries.map((c) => <option key={c} value={c}>{c}</option>)}
            </select>
          </div>
          <div>
            <label className="field-label">שם על המצבה</label>
            <input className="field" value={form.deceased} onChange={(e) => set({ deceased: e.target.value })} placeholder="לדוגמה: שרה לוי" />
          </div>
        </div>
      )}

      {form.placeMethod === 'photo' && (
        <div className="fade-up">
          <label className="field-label">תמונת המקום</label>
          <button onClick={() => set({ photoAttached: !form.photoAttached })} style={{
            width: '100%', padding: '26px 16px', borderRadius: 'var(--r-lg)', cursor: 'pointer',
            border: form.photoAttached ? '1.5px solid var(--accent)' : '1.5px dashed var(--line)',
            background: form.photoAttached ? 'var(--accent-tint)' : 'var(--surface)',
            display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 10, color: 'var(--ink-soft)',
          }}>
            <Icon name={form.photoAttached ? 'check' : 'camera'} size={30} style={{ color: form.photoAttached ? 'var(--accent-deep)' : 'var(--ink-faint)' }} stroke={form.photoAttached ? 2 : 1.6} />
            <span style={{ fontWeight: 700, fontSize: 16, color: form.photoAttached ? 'var(--accent-deep)' : 'var(--ink)' }}>
              {form.photoAttached ? 'התמונה נוספה' : 'לחצו כדי לצרף תמונה'}
            </span>
            {!form.photoAttached && <span className="t-small">מתאימה כל תמונה של המצבה או של נקודת ציון</span>}
          </button>
          <p className="t-small" style={{ marginTop: 12 }}>איש המקצוע ימצא את המקום לפי התמונה ונקודות הציון.</p>
        </div>
      )}

      {form.placeMethod === 'help' && (
        <div className="fade-up card" style={{ padding: 18, display: 'flex', gap: 14 }}>
          <IconDisc name="heart" size={44} tone="bronze" />
          <div>
            <h3 className="t-h3" style={{ fontSize: 18, marginBottom: 6 }}>אנחנו נעזור למצוא</h3>
            <p className="t-small">לאחר ההזמנה מנהל אישי יצור איתכם קשר, יברר את הפרטים וימצא את המקום הנכון בעצמו. די במה שאתם זוכרים.</p>
          </div>
        </div>
      )}
    </div>
  );
}

// ---------- Подтверждение надгробия (после шага «место») ----------
function VerifyStep({ method, form, onDone }) {
  const isPhoto = method === 'photo';
  const checks = isPhoto
    ? ['התמונה הועלתה', 'המצבה זוהתה', 'אומת מול מרשם בית העלמין']
    : ['הקבר נמצא', 'השם והחלקה אומתו', 'אומת מול מרשם בית העלמין'];
  const [done, setDone] = React.useState(0);
  const [complete, setComplete] = React.useState(false);

  React.useEffect(() => {
    const reduce = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    const t = reduce ? 220 : 760;
    const timers = [];
    checks.forEach((_, i) => timers.push(setTimeout(() => setDone(i + 1), t * (i + 1))));
    timers.push(setTimeout(() => setComplete(true), t * (checks.length + 1)));
    timers.push(setTimeout(() => onDone(), t * (checks.length + 1) + (reduce ? 350 : 1300)));
    return () => timers.forEach(clearTimeout);
  }, []);

  const subject = form.placeMethod === 'search'
    ? { line1: form.cemetery ? form.cemetery.split(',')[0] : 'בית עלמין', line2: form.deceased || 'שם על המצבה' }
    : { line1: 'התמונה שלכם', line2: 'המצבה בתמונה' };

  const Bracket = ({ pos }) => {
    const m = 10;
    const base = { position: 'absolute', width: 22, height: 22, borderColor: 'var(--accent)', borderStyle: 'solid', borderWidth: 0 };
    const map = {
      tl: { top: m, insetInlineStart: m, borderTopWidth: 2.5, borderInlineStartWidth: 2.5, borderTopLeftRadius: 6 },
      tr: { top: m, insetInlineEnd: m, borderTopWidth: 2.5, borderInlineEndWidth: 2.5, borderTopRightRadius: 6 },
      bl: { bottom: m, insetInlineStart: m, borderBottomWidth: 2.5, borderInlineStartWidth: 2.5, borderBottomLeftRadius: 6 },
      br: { bottom: m, insetInlineEnd: m, borderBottomWidth: 2.5, borderInlineEndWidth: 2.5, borderBottomRightRadius: 6 },
    };
    return <span className={complete ? '' : 'scan-bracket'} style={{ ...base, ...map[pos], opacity: complete ? 1 : undefined }} />;
  };

  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: 'var(--bg)', paddingTop: 56 }}>
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center', padding: '0 26px 40px' }}>
        {/* объект проверки со сканером */}
        <div style={{
          position: 'relative', height: 178, borderRadius: 'var(--r-lg)', overflow: 'hidden',
          background: 'var(--surface-2)', border: complete ? '1.5px solid var(--accent)' : '1px solid var(--line)',
          display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 12,
          margin: '0 auto 26px', maxWidth: 320, width: '100%', transition: 'border-color .3s ease',
        }}>
          <div style={{
            width: 60, height: 60, borderRadius: 16, background: 'var(--surface)',
            border: '1px solid var(--line)', display: 'flex', alignItems: 'center', justifyContent: 'center',
            color: 'var(--accent-deep)',
          }}>
            <Icon name={isPhoto ? 'camera' : 'pin'} size={30} />
          </div>
          <div style={{ textAlign: 'center', padding: '0 16px' }}>
            <div style={{ fontWeight: 700, fontSize: 15, color: 'var(--ink)' }}>{subject.line1}</div>
            <div className="t-small" style={{ marginTop: 2 }}>{subject.line2}</div>
          </div>
          <Bracket pos="tl" /><Bracket pos="tr" /><Bracket pos="bl" /><Bracket pos="br" />
          {!complete && <span className="scan-line" />}
          {complete && (
            <div className="pop" style={{
              position: 'absolute', inset: 0, background: 'color-mix(in oklch, var(--accent-tint) 88%, transparent)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>
              <div style={{
                width: 66, height: 66, borderRadius: 999, background: 'var(--accent)', color: 'var(--on-accent)',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                boxShadow: '0 10px 28px color-mix(in oklch, var(--accent) 42%, transparent)',
              }}><Icon name="check" size={34} stroke={2.4} /></div>
            </div>
          )}
        </div>

        <h2 className="t-h2" style={{ textAlign: 'center', fontSize: 23, marginBottom: 8 }}>
          {complete ? 'המידע אומת והתקבל' : 'בודקים את פרטי המצבה'}
        </h2>
        <p className="t-small" style={{ textAlign: 'center', marginBottom: 22 }}>
          {complete ? 'המצבה אומתה — מעבירים לאיש המקצוע.' : 'זה ייקח כמה שניות.'}
        </p>

        <div className="card" style={{ padding: 16, maxWidth: 340, width: '100%', margin: '0 auto' }}>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 13 }}>
            {checks.map((c, i) => {
              const ok = i < done;
              const active = i === done && !complete;
              return (
                <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 12, opacity: ok || active ? 1 : 0.45, transition: 'opacity .3s ease' }}>
                  <span style={{
                    width: 26, height: 26, borderRadius: 999, flexShrink: 0,
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    background: ok ? 'var(--accent)' : 'var(--surface-2)',
                    border: ok ? 'none' : '1.5px solid var(--line)',
                    color: ok ? 'var(--on-accent)' : 'var(--accent)',
                    transition: 'background .25s ease',
                  }}>
                    {ok ? <Icon name="check" size={15} stroke={2.4} />
                      : active ? <span className="spin" style={{ width: 14, height: 14, borderRadius: 999, border: '2px solid var(--accent-tint)', borderTopColor: 'var(--accent)' }} />
                      : <span style={{ width: 7, height: 7, borderRadius: 999, background: 'var(--line)' }} />}
                  </span>
                  <span className="t-body" style={{ fontWeight: ok ? 700 : 600, color: ok || active ? 'var(--ink)' : 'var(--ink-faint)' }}>{c}</span>
                </div>
              );
            })}
          </div>
        </div>

        <p className="t-small" style={{ textAlign: 'center', marginTop: 18, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 7 }}>
          <Icon name="lock" size={14} style={{ color: 'var(--accent-deep)' }} /> הנתונים מאומתים בערוץ מאובטח
        </p>
      </div>
    </div>
  );
}

// ---------- Шаг: контакт ----------
function DetailsStep({ form, set, isSub }) {
  const [open, setOpen] = React.useState(false);
  return (
    <div>
      <h2 className="t-h2" style={{ marginBottom: 6 }}>לאן לשלוח את הדוח?</h2>
      <p className="t-lead" style={{ marginBottom: 20 }}>אין צורך בהרשמה. הפרטים האלה רק כדי לעדכן אתכם.</p>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
        <div>
          <label className="field-label">השם שלך</label>
          <input className="field" value={form.name} onChange={(e) => set({ name: e.target.value })} placeholder="איך לפנות אליכם" />
        </div>
        <div>
          <label className="field-label">טלפון</label>
          <input className="field" type="tel" inputMode="tel" value={form.phone} onChange={(e) => set({ phone: e.target.value })} placeholder="+972 …" />
        </div>
        <div>
          <label className="field-label">דוא"ל <span className="faint" style={{ fontWeight: 400 }}>— לא חובה</span></label>
          <input className="field" type="email" inputMode="email" value={form.email} onChange={(e) => set({ email: e.target.value })} placeholder="לדוח התמונות" />
        </div>

        {!open ? (
          <button onClick={() => setOpen(true)} className="btn btn-quiet btn-sm" style={{ width: '100%', justifyContent: 'space-between' }}>
            הוספת בקשה או מועד <Icon name="arrow" size={18} />
          </button>
        ) : (
          <div className="fade-up" style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
            <div>
              <label className="field-label">מתי נוח לבצע</label>
              <select className="field" value={form.when} onChange={(e) => set({ when: e.target.value })}>
                <option value="any">בזמן הקרוב</option>
                <option value="week">תוך שבוע</option>
                <option value="date">לתאריך מסוים</option>
                <option value="anniv">ליום השנה</option>
              </select>
            </div>
            <div>
              <label className="field-label">בקשה <span className="faint" style={{ fontWeight: 400 }}>— לא חובה</span></label>
              <textarea className="field" rows={3} style={{ resize: 'none', minHeight: 92 }} value={form.comment} onChange={(e) => set({ comment: e.target.value })} placeholder="מה חשוב לקחת בחשבון" />
            </div>
          </div>
        )}
      </div>
      <p className="t-small" style={{ marginTop: 18, display: 'flex', gap: 8, alignItems: 'flex-start' }}>
        <Icon name="shield" size={16} style={{ color: 'var(--accent-deep)', flexShrink: 0, marginTop: 1 }} />
        אפשר ליצור חשבון מאוחר יותר — לא חובה, אחרי התשלום.
      </p>
    </div>
  );
}

// ---------- Шаг: оплата ----------
function PayStep({ form, set, isSub, pkg, orderPrice, subPrice }) {
  const D = window.DATA;
  const methods = [
    { id: 'card', label: 'כרטיס אשראי' },
    { id: 'applepay', label: 'Apple Pay' },
    { id: 'bit', label: 'Bit' },
  ];
  return (
    <div>
      <h2 className="t-h2" style={{ marginBottom: 18 }}>בדקו את ההזמנה</h2>

      {/* сводка */}
      <div className="card" style={{ padding: 18, marginBottom: 16 }}>
        <Row label={isSub ? 'מנוי' : 'שירות'} value={isSub ? D.subscription.title : pkg.name} />
        {isSub && <Row label="רמת הטיפול" value={subPrice.tierName} />}
        <Row label="סוג המצבה" value={window.MONUMENT_LABEL(form.monument)} />
        <Row label="מקום" value={placeSummary(form)} />
        <div className="divider" style={{ margin: '14px 0' }} />
        {isSub ? (
          <div>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
              <span style={{ fontWeight: 700, fontSize: 17 }}>סה"כ</span>
              <span className="t-price">{window.fmt(subPrice.perMonth)} ₪/חודש</span>
            </div>
            <p className="t-small" style={{ marginTop: 8, display: 'flex', alignItems: 'center', gap: 8 }}>
              <Icon name="calendar" size={16} style={{ color: 'var(--accent-deep)' }} /> {subPrice.bill}. אפשר לבטל בכל עת.
            </p>
          </div>
        ) : (
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
            <span style={{ fontWeight: 700, fontSize: 17 }}>סה"כ</span>
            <span className="t-price">{window.fmt(orderPrice)} ₪</span>
          </div>
        )}
      </div>

      {/* способ оплаты */}
      <span className="field-label">אמצעי תשלום</span>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginBottom: 18 }}>
        {methods.map((m) => {
          const on = form.payMethod === m.id;
          return (
            <button key={m.id} onClick={() => set({ payMethod: m.id })} style={{
              ...selectCard(on), padding: 16, flexDirection: 'row', alignItems: 'center', gap: 12, display: 'flex',
            }}>
              <Icon name={m.id === 'card' ? 'doc' : 'lock'} size={22} style={{ color: 'var(--ink-soft)' }} />
              <span className="t-body" style={{ fontWeight: 700, flex: 1, textAlign: 'start' }}>{m.label}</span>
              <Radio on={on} />
            </button>
          );
        })}
      </div>

      <div style={{ display: 'flex', gap: 12, padding: 16, borderRadius: 'var(--r)', background: 'var(--surface-2)' }}>
        <Icon name="lock" size={20} style={{ color: 'var(--accent-deep)', flexShrink: 0 }} />
        <p className="t-small">התשלום מתבצע בשירות המאובטח <b>pay.bezikaron</b>. איננו רואים ואיננו שומרים את פרטי הכרטיס שלכם.</p>
      </div>
    </div>
  );
}

// ---------- мелочи ----------
function Radio({ on }) {
  return (
    <span style={{
      width: 24, height: 24, borderRadius: 999, flexShrink: 0,
      border: on ? '7px solid var(--accent)' : '2px solid var(--line)',
      background: 'var(--surface)', transition: 'border .15s ease',
    }} />
  );
}
function Row({ label, value }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', gap: 16, padding: '5px 0' }}>
      <span className="t-small" style={{ flexShrink: 0 }}>{label}</span>
      <span className="t-body" style={{ fontWeight: 700, textAlign: 'end' }}>{value}</span>
    </div>
  );
}
function selectCard(on) {
  return {
    width: '100%', padding: 18, borderRadius: 'var(--r-lg)', cursor: 'pointer',
    background: on ? 'var(--accent-tint)' : 'var(--surface)',
    border: on ? '1.5px solid var(--accent)' : '1.5px solid var(--line)',
    boxShadow: on ? 'none' : 'var(--shadow-soft)',
    display: 'flex', flexDirection: 'column', transition: 'all .15s ease',
  };
}
function placeSummary(form) {
  if (form.placeMethod === 'search') return form.cemetery ? form.cemetery.split(',')[0] : '—';
  if (form.placeMethod === 'photo') return 'לפי תמונה';
  return 'נעזור למצוא';
}

Object.assign(window, { Checkout });
