/* SUPERMEDIA storefront — Checkout: multi-step flow (details → delivery & payment
 * → review → confirmation), with fizičko / pravno lice (B2B, R-1 faktura) support. */
const { useState: useStateCO, useMemo: useMemoCO, useEffect: useEffectCO } = React;

function Checkout({ cart, setCart, user, onNav }) {
  const { PRODUCTS } = SM_DATA;
  const find = (id) => PRODUCTS.find(p => p.id === id) || (window.SM_EXTRA && window.SM_EXTRA[id]);
  const items = useMemoCO(() => cart.map(c => ({ ...find(c.id), qty: c.qty })).filter(x => x.id), [cart]);

  const [step, setStep] = useStateCO(0); // 0 podaci · 1 dostava+plaćanje · 2 pregled · 3 potvrda
  const [entity, setEntity] = useStateCO('person'); // person | company
  const [delivery, setDelivery] = useStateCO('courier'); // courier | pickup
  const [payment, setPayment] = useStateCO('cod'); // cod | card | bank
  const [agree, setAgree] = useStateCO(false);
  const [order, setOrder] = useStateCO(null);
  const [placing, setPlacing] = useStateCO(false);
  const [promo, setPromo] = useStateCO('');
  const [promoApplied, setPromoApplied] = useStateCO(null);
  const [promoDisc, setPromoDisc] = useStateCO(0);
  const [promoMsg, setPromoMsg] = useStateCO(null);

  const blank = {
    company: '', pib: '', mb: '',
    name: user ? user.name : '', email: user ? user.email : '', phone: '',
    address: '', city: '', zip: '', note: '',
  };
  const [f, setF] = useStateCO(blank);
  const set = (k) => (e) => setF(s => ({ ...s, [k]: e.target.value }));

  const subtotal = items.reduce((s, x) => s + x.price * x.qty, 0);
  const oldTotal = items.reduce((s, x) => s + (x.old || x.price) * x.qty, 0);
  const savings = oldTotal - subtotal;
  const freeShip = subtotal > 30000 || subtotal === 0;
  const shipping = delivery === 'pickup' ? 0 : (freeShip ? 0 : 590);
  const promoDiscount = promoApplied ? Math.min(promoDisc, subtotal) : 0;
  // pravno lice → cene bez PDV-a se prikazuju informativno
  const total = Math.max(0, subtotal + shipping - promoDiscount);
  const vat = Math.round(total - total / 1.2);
  const applyPromo = async () => {
    const code = promo.trim().toUpperCase();
    if (!code) return;
    try {
      const r = await fetch('/sm-api/voucher/validate', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ code, subtotal }) });
      const d = await r.json();
      if (d && d.valid) { setPromoApplied(d.code); setPromoDisc(d.discount); setPromoMsg(null); }
      else { setPromoApplied(null); setPromoDisc(0); setPromoMsg((d && d.error) || 'Vaučer nije važeći.'); }
    } catch (e) { setPromoMsg('Server nije dostupan.'); }
  };
  // re-render Lucide ikonice kad se promeni interni state (App.createIcons ne reaguje na njega)
  useEffectCO(() => { if (window.lucide) window.lucide.createIcons(); }, [step, promoApplied, entity, payment]);

  const wide = { maxWidth: 1180, margin: '0 auto', padding: '0 24px' };

  // empty-cart guard (but not on confirmation screen)
  if (items.length === 0 && step < 3) return (
    <div style={{ ...wide, paddingTop: 22, paddingBottom: 40 }}>
      <h1 style={{ fontSize: 30, marginBottom: 24 }}>Plaćanje</h1>
      <div style={{ textAlign: 'center', padding: '60px 20px', background: '#fff', border: '1px solid var(--sm-border)', borderRadius: 'var(--sm-radius-lg)' }}>
        <img src={SM_DATA.A + '/mascot-genie.png'} alt="" style={{ height: 130, marginBottom: 14 }} />
        <div style={{ fontFamily: 'var(--sm-font-display)', fontWeight: 700, fontSize: 22 }}>Korpa je prazna</div>
        <p style={{ color: 'var(--sm-text-muted)', fontSize: 15, margin: '8px 0 22px' }}>Dodaj proizvode pa nastavi na plaćanje.</p>
        <Button variant="primary" size="lg" onClick={() => onNav({ view: 'home' })} iconLeft={I('arrow-left', 18)}>Nazad na kupovinu</Button>
      </div>
    </div>
  );

  // validation per step
  const step0valid = f.name.trim() && /\S+@\S+\.\S+/.test(f.email) && f.phone.trim() && f.address.trim() && f.city.trim() && f.zip.trim()
    && (entity === 'person' || (f.company.trim() && f.pib.trim().length === 9 && f.mb.trim().length === 8));

  // razdvoji "Ulica 12a" → { streetName, houseNumber } za stari Raiffeisen handler
  // (validateOrderUser zahteva oba polja; streetName ≥3 znaka, houseNumber [0-9A-Za-z/-]+)
  const splitAddress = (addr) => {
    const raw = String(addr || '').trim();
    const m = raw.match(/^(.*?)[\s,]+([0-9]+[0-9A-Za-z/.\-]*)\s*$/);
    if (m && m[1].trim().length >= 3) {
      return { streetName: m[1].trim(), houseNumber: m[2].replace(/\./g, '').trim() || 'bb' };
    }
    // nema prepoznatljivog broja → ceo string u ulicu, broj = "bb"
    return { streetName: raw.length >= 3 ? raw : (raw + ' ulica'), houseNumber: 'bb' };
  };

  // KARTICA → postojeći sertifikovani Raiffeisen tok (/api/online-payment).
  // Taj endpoint sam kreira Order (pending) u "Orders", vrati gateway formData,
  // pa kupca auto-submit formom šaljemo na 3DS gateway. /notify (webhook banke)
  // posle potvrđuje plaćanje. NE pravimo duplu porudžbinu preko /sm-api/orders.
  const startCardPayment = async () => {
    const sp = f.name.trim().split(/\s+/).filter(Boolean);
    const firstName = sp[0] || 'Kupac';
    const lastName = sp.slice(1).join(' ') || '.';
    const { streetName, houseNumber } = splitAddress(f.address);
    const noteParts = [];
    if (f.note) noteParts.push(f.note);
    if (entity === 'company') noteParts.push(`Pravno lice: ${f.company} | PIB ${f.pib} | MB ${f.mb}`);
    const user = {
      firstName, lastName,
      phoneNumber: f.phone.trim(),
      email: f.email.trim(),
      streetName, houseNumber, apartment: '',
      city: f.city.trim(),
      postalCode: f.zip.trim(),
      note: noteParts.join(' — '),
    };
    const cart = items.map(x => ({ id: x.id, quantity: x.qty }));
    let tok = null; try { tok = localStorage.getItem('sm_token'); } catch (e) {}
    const r = await fetch('/api/online-payment', {
      method: 'POST',
      headers: Object.assign({ 'Content-Type': 'application/json' }, tok ? { Authorization: 'Bearer ' + tok } : {}),
      body: JSON.stringify({ user, cart, couponCode: promoApplied || null }),
    });
    const d = await r.json().catch(() => ({}));
    if (!r.ok || !d.success || !d.paymentUrl || !d.formData) {
      throw new Error((d && d.error) || 'Plaćanje karticom trenutno nije dostupno. Pokušajte ponovo ili izaberite drugi način.');
    }
    // auto-submit forma na Raiffeisen 3DS gateway (kupac napušta SPA)
    const form = document.createElement('form');
    form.method = 'POST';
    form.action = d.paymentUrl;
    form.style.display = 'none';
    Object.keys(d.formData).forEach((k) => {
      const inp = document.createElement('input');
      inp.type = 'hidden';
      inp.name = k;
      inp.value = d.formData[k] == null ? '' : String(d.formData[k]);
      form.appendChild(inp);
    });
    document.body.appendChild(form);
    setCart([]); // Order je već kreiran na serveru; isprazni lokalnu korpu pre redirecta
    form.submit();
  };

  const placeOrder = async () => {
    if (placing) return;
    setPlacing(true);
    let tok = null; try { tok = localStorage.getItem('sm_token'); } catch (e) {}
    // KARTICA: idi na postojeći Raiffeisen tok umesto /sm-api/orders
    if (payment === 'card') {
      try {
        await startCardPayment();
        // posle form.submit() browser navigira na gateway — ostavi placing true
        return;
      } catch (e) {
        setPlacing(false);
        alert(e && e.message ? e.message : 'Plaćanje karticom nije uspelo. Pokušajte ponovo.');
        return;
      }
    }
    // POUZEĆE ('cod') i VIRMAN ('bank') → novi tok + novi email
    try {
      const r = await fetch('/sm-api/orders', {
        method: 'POST',
        headers: Object.assign({ 'Content-Type': 'application/json' }, tok ? { Authorization: 'Bearer ' + tok } : {}),
        body: JSON.stringify({
          items: items.map(x => ({ id: x.id, title: x.title, price: x.price, qty: x.qty })),
          entity, payment, delivery, name: f.name, email: f.email, phone: f.phone, address: f.address, city: f.city, zip: f.zip, note: f.note,
          company: f.company, pib: f.pib, mb: f.mb, subtotal, shipping, total, promo: promoApplied || null,
        }),
      });
      const d = await r.json();
      if (!r.ok) { setPlacing(false); alert(d.error || 'Greška pri kreiranju porudžbine.'); return; }
      setOrder({ num: d.num, items, subtotal, shipping, total, promo: promoApplied, promoDiscount, entity, payment, delivery, ...f, vat });
      setCart([]); setStep(3); setPlacing(false); window.scrollTo(0, 0);
    } catch (e) { setPlacing(false); alert('Server nije dostupan. Da li je lokalni server upaljen?'); }
  };

  const goTo = (s) => { setStep(s); window.scrollTo(0, 0); };

  // ---------- CONFIRMATION ----------
  if (step === 3 && order) return <Confirmation order={order} onNav={onNav} />;

  const steps = ['Podaci', 'Dostava i plaćanje', 'Potvrda'];

  return (
    <div style={{ ...wide, paddingTop: 22, paddingBottom: 48 }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', gap: 12, marginBottom: 22 }}>
        <h1 style={{ fontSize: 30, margin: 0 }}>Plaćanje</h1>
        <a onClick={() => onNav({ view: 'cart' })} style={{ display: 'inline-flex', alignItems: 'center', gap: 6, color: 'var(--sm-primary)', fontWeight: 600, fontSize: 14, cursor: 'pointer' }}>{I('arrow-left', 16)} Nazad na korpu</a>
      </div>

      <Stepper steps={steps} active={step} onJump={(i) => { if (i < step) goTo(i); }} />

      <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0,1fr) 372px', gap: 28, alignItems: 'start', marginTop: 26 }}>
        <div>
          {step === 0 && (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
              {/* customer type */}
              <Card>
                <SecTitle n="1" title="Tip kupca" />
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
                  <EntityCard icon="user" title="Fizičko lice" desc="Kupovina za ličnu upotrebu" active={entity === 'person'} onClick={() => setEntity('person')} />
                  <EntityCard icon="building-2" title="Pravno lice" desc="Račun na firmu · R-1 faktura" active={entity === 'company'} onClick={() => setEntity('company')} />
                </div>
                {entity === 'company' && (
                  <div style={{ marginTop: 18, padding: 18, background: 'var(--sm-purple-50)', border: '1px solid var(--sm-purple-100)', borderRadius: 'var(--sm-radius-md)' }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 14, fontFamily: 'var(--sm-font-display)', fontWeight: 700, fontSize: 14, color: 'var(--sm-purple-700)' }}>{I('briefcase', 16)} Podaci o firmi</div>
                    <COField label="Naziv firme" value={f.company} onChange={set('company')} placeholder="SuperMedia d.o.o." />
                    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14, marginTop: 14 }}>
                      <COField label="PIB" value={f.pib} onChange={(e) => setF(s => ({ ...s, pib: e.target.value.replace(/\D/g, '').slice(0, 9) }))} placeholder="9 cifara" hint={f.pib && f.pib.length !== 9 ? 'PIB ima 9 cifara' : null} />
                      <COField label="Matični broj" value={f.mb} onChange={(e) => setF(s => ({ ...s, mb: e.target.value.replace(/\D/g, '').slice(0, 8) }))} placeholder="8 cifara" hint={f.mb && f.mb.length !== 8 ? 'Matični broj ima 8 cifara' : null} />
                    </div>
                  </div>
                )}
              </Card>

              {/* contact */}
              <Card>
                <SecTitle n="2" title={entity === 'company' ? 'Kontakt osoba' : 'Kontakt podaci'} />
                <COField label="Ime i prezime" value={f.name} onChange={set('name')} placeholder="Petar Petrović" />
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14, marginTop: 14 }}>
                  <COField label="Email adresa" type="email" value={f.email} onChange={set('email')} placeholder="ime@email.com" hint={f.email && !/\S+@\S+\.\S+/.test(f.email) ? 'Unesite ispravnu email adresu (npr. ime@email.com)' : null} />
                  <COField label="Telefon" value={f.phone} onChange={set('phone')} placeholder="+381 6x xxx xxx" />
                </div>
              </Card>

              {/* address */}
              <Card>
                <SecTitle n="3" title={entity === 'company' ? 'Adresa isporuke' : 'Adresa za dostavu'} />
                <COField label="Ulica i broj" value={f.address} onChange={set('address')} placeholder="Bulevar oslobođenja 123" />
                <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 14, marginTop: 14 }}>
                  <COField label="Grad" value={f.city} onChange={set('city')} placeholder="Beograd" />
                  <COField label="Poštanski broj" value={f.zip} onChange={(e) => setF(s => ({ ...s, zip: e.target.value.replace(/\D/g, '').slice(0, 5) }))} placeholder="11000" />
                </div>
                <div style={{ marginTop: 14 }}>
                  <COField label="Napomena (opciono)" textarea value={f.note} onChange={set('note')} placeholder="Npr. ostaviti kod komšije, pozvati pre dostave…" />
                </div>
              </Card>

              <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 10 }}>
                {!step0valid && (
                  <div style={{ display: 'flex', alignItems: 'center', gap: 7, fontSize: 13, color: 'var(--sm-text-subtle)' }}>
                    {I('info', 15)} Popunite sva obavezna polja da biste nastavili
                  </div>
                )}
                <Button variant="primary" size="lg" disabled={!step0valid} onClick={() => goTo(1)} iconRight={I('arrow-right', 18)}>Nastavi na dostavu</Button>
              </div>
            </div>
          )}

          {step === 1 && (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
              <Card>
                <SecTitle n="1" title="Način plaćanja" />
                <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
                  <OptionRow icon="banknote" title="Pouzećem" desc="Plati kuriru pri preuzimanju (gotovina ili kartica)" active={payment === 'cod'} onClick={() => setPayment('cod')} />
                  <OptionRow icon="credit-card" title="Platnom karticom" desc="Visa · Mastercard · DinaCard" active={payment === 'card'} onClick={() => setPayment('card')} />
                  <OptionRow icon="building-2" title="Virmanom / na račun" desc={entity === 'company' ? 'Predračun i R-1 faktura na email firme' : 'Uplata po predračunu na tekući račun'} active={payment === 'bank'} onClick={() => setPayment('bank')} />
                </div>
                {entity === 'company' && (
                  <div style={{ marginTop: 16, display: 'flex', gap: 10, alignItems: 'flex-start', padding: '12px 14px', background: 'var(--sm-purple-50)', borderRadius: 'var(--sm-radius-md)', fontSize: 13.5, color: 'var(--sm-purple-700)', lineHeight: 1.5 }}>
                    {I('file-check', 18)}<span>Kao pravno lice dobijaš <b>R-1 fakturu</b> sa iskazanim PDV-om na email firme nakon potvrde porudžbine.</span>
                  </div>
                )}
              </Card>

              <div style={{ display: 'flex', justifyContent: 'space-between', gap: 12 }}>
                <Button variant="ghost" size="lg" onClick={() => goTo(0)} iconLeft={I('arrow-left', 18)}>Nazad</Button>
                <Button variant="primary" size="lg" onClick={() => goTo(2)} iconRight={I('arrow-right', 18)}>Nastavi na potvrdu</Button>
              </div>
            </div>
          )}

          {step === 2 && (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
              <Card>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 16 }}>
                  <SecTitle title={entity === 'company' ? 'Podaci o firmi' : 'Kupac'} flush />
                  <a onClick={() => goTo(0)} style={editLink}>{I('pencil', 14)} Izmeni</a>
                </div>
                {entity === 'company' && <Recap rows={[['Firma', f.company], ['PIB', f.pib], ['Matični broj', f.mb]]} />}
                <Recap rows={[['Kontakt', f.name], ['Email', f.email], ['Telefon', f.phone], ['Adresa', `${f.address}, ${f.zip} ${f.city}`], ...(f.note ? [['Napomena', f.note]] : [])]} />
              </Card>

              <Card>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 16 }}>
                  <SecTitle title="Dostava i plaćanje" flush />
                  <a onClick={() => goTo(1)} style={editLink}>{I('pencil', 14)} Izmeni</a>
                </div>
                <Recap rows={[
                  ['Dostava', delivery === 'courier' ? 'Kurirska dostava (D Express)' : 'Lično preuzimanje'],
                  ['Plaćanje', payment === 'cod' ? 'Pouzećem' : payment === 'card' ? 'Platnom karticom' : 'Virmanom / na račun'],
                ]} />
              </Card>

              <Card>
                <SecTitle title={`Proizvodi (${items.length})`} flush />
                <div style={{ display: 'flex', flexDirection: 'column', gap: 12, marginTop: 14 }}>
                  {items.map(x => (
                    <div key={x.id} style={{ display: 'flex', gap: 14, alignItems: 'center' }}>
                      <div style={{ width: 56, height: 56, flex: 'none', background: x.voucher ? 'linear-gradient(135deg, var(--sm-primary), var(--sm-violet))' : '#fff', border: '1px solid var(--sm-border)', borderRadius: 'var(--sm-radius-sm)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff' }}>
                        {x.voucher ? I('gift', 24) : <img src={x.img} alt="" style={{ maxWidth: '78%', maxHeight: '78%', objectFit: 'contain' }} />}
                      </div>
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{ fontWeight: 600, fontSize: 14.5, lineHeight: 1.3 }}>{x.title}</div>
                        <div style={{ fontSize: 13, color: 'var(--sm-text-muted)' }}>Količina: {x.qty}</div>
                      </div>
                      <span style={{ fontFamily: 'var(--sm-font-body)', fontWeight: 800, fontSize: 15, color: 'var(--sm-price)' }}>{fmt(x.price * x.qty)} din.</span>
                    </div>
                  ))}
                </div>
              </Card>

              <label style={{ display: 'flex', alignItems: 'flex-start', gap: 11, fontSize: 14, color: 'var(--sm-text-muted)', cursor: 'pointer', lineHeight: 1.5, padding: '0 4px' }}>
                <input type="checkbox" checked={agree} onChange={e => setAgree(e.target.checked)} style={{ width: 18, height: 18, marginTop: 1, accentColor: 'var(--sm-primary)', flex: 'none' }} />
                <span>Saglasan/na sam sa <a onClick={(e) => { e.preventDefault(); onNav({ view: 'page', key: 'uslovi' }); }} style={{ color: 'var(--sm-primary)', fontWeight: 600 }}>uslovima korišćenja</a> i <a onClick={(e) => { e.preventDefault(); onNav({ view: 'page', key: 'privatnost' }); }} style={{ color: 'var(--sm-primary)', fontWeight: 600 }}>politikom privatnosti</a>.</span>
              </label>

              <div style={{ display: 'flex', justifyContent: 'space-between', gap: 12 }}>
                <Button variant="ghost" size="lg" onClick={() => goTo(1)} iconLeft={I('arrow-left', 18)}>Nazad</Button>
                <Button variant="primary" size="lg" disabled={!agree || placing} onClick={placeOrder} iconRight={I(payment === 'card' ? 'credit-card' : 'check', 18)}>{placing ? (payment === 'card' ? 'Preusmeravanje…' : 'Slanje…') : (payment === 'card' ? 'Plati karticom' : 'Potvrdi porudžbinu')}</Button>
              </div>
            </div>
          )}
        </div>

        {/* sticky order summary */}
        <aside style={{ background: '#fff', border: '1px solid var(--sm-border)', borderRadius: 'var(--sm-radius-lg)', padding: 24, position: 'sticky', top: 72 }}>
          <h3 style={{ fontSize: 19, marginBottom: 16 }}>Pregled porudžbine</h3>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10, maxHeight: 188, overflowY: 'auto', marginBottom: 14, paddingRight: 4 }}>
            {items.map(x => (
              <div key={x.id} style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
                <div style={{ position: 'relative', width: 44, height: 44, flex: 'none', background: x.voucher ? 'linear-gradient(135deg, var(--sm-primary), var(--sm-violet))' : '#fff', border: '1px solid var(--sm-border)', borderRadius: 8, display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff' }}>
                  {x.voucher ? I('gift', 20) : <img src={x.img} alt="" style={{ maxWidth: '76%', maxHeight: '76%', objectFit: 'contain' }} />}
                  <span style={{ position: 'absolute', top: -7, right: -7, minWidth: 18, height: 18, padding: '0 4px', borderRadius: 9, background: 'var(--sm-ink)', color: '#fff', fontSize: 11, fontWeight: 800, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>{x.qty}</span>
                </div>
                <div style={{ flex: 1, minWidth: 0, fontSize: 13, fontWeight: 600, lineHeight: 1.3, overflow: 'hidden', textOverflow: 'ellipsis', display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical' }}>{x.title}</div>
                <span style={{ fontSize: 13, fontWeight: 800, whiteSpace: 'nowrap' }}>{fmt(x.price * x.qty)}</span>
              </div>
            ))}
          </div>
          {/* promo / vaučer kod */}
          <div style={{ borderTop: '1px solid var(--sm-border)', paddingTop: 14, marginBottom: 2 }}>
            {promoApplied ? (
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10, padding: '10px 12px', background: 'var(--sm-purple-50)', border: '1px solid var(--sm-purple-100)', borderRadius: 'var(--sm-radius-sm)' }}>
                <span style={{ display: 'flex', alignItems: 'center', gap: 8, fontFamily: 'var(--sm-font-display)', fontSize: 13.5, fontWeight: 700, color: 'var(--sm-purple-700)' }}>{I('ticket-percent', 16)} {promoApplied} primenjen</span>
                <button type="button" onClick={() => { setPromoApplied(null); setPromoDisc(0); setPromo(''); setPromoMsg(null); }} style={{ background: 'none', border: 'none', cursor: 'pointer', fontSize: 12.5, fontWeight: 600, color: 'var(--sm-text-muted)', textDecoration: 'underline' }}>Ukloni</button>
              </div>
            ) : (
              <React.Fragment>
                <label style={{ display: 'flex', alignItems: 'center', gap: 7, fontFamily: 'var(--sm-font-display)', fontWeight: 600, fontSize: 13.5, marginBottom: 8, color: 'var(--sm-text)' }}>{I('ticket-percent', 16)} Imaš vaučer ili promo kod?</label>
                <div style={{ display: 'flex', gap: 8 }}>
                  <input value={promo} onChange={(e) => { setPromo(e.target.value); setPromoMsg(null); }} onKeyDown={(e) => { if (e.key === 'Enter') applyPromo(); }} placeholder="npr. SUPER10" style={{ flex: 1, minWidth: 0, height: 44, border: '1.5px solid var(--sm-border)', borderRadius: 'var(--sm-radius-sm)', padding: '0 12px', fontFamily: 'var(--sm-font-body)', fontSize: 14, textTransform: 'uppercase', outline: 'none', background: '#fff', boxSizing: 'border-box' }} />
                  <Button variant="secondary" size="md" onClick={applyPromo} disabled={!promo.trim()}>Primeni</Button>
                </div>
                {promoMsg && <div style={{ fontSize: 12.5, color: 'var(--sm-sale)', marginTop: 6 }}>{promoMsg}</div>}
              </React.Fragment>
            )}
          </div>
          <div style={{ borderTop: '1px solid var(--sm-border)', paddingTop: 14 }}>
            <Line label="Međuzbir" value={fmt(subtotal) + ' din.'} />
            {savings > 0 && <Line label="Ušteda" value={'−' + fmt(savings) + ' din.'} accent />}
            {promoDiscount > 0 && <Line label={'Promo · ' + promoApplied} value={'−' + fmt(promoDiscount) + ' din.'} accent />}
            <Line label="Dostava" value={shipping === 0 ? 'Besplatno' : fmt(shipping) + ' din.'} />
          </div>
          <div style={{ borderTop: '1px solid var(--sm-border)', margin: '14px 0 0', paddingTop: 14, display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
            <span style={{ fontFamily: 'var(--sm-font-display)', fontWeight: 700, fontSize: 17 }}>Ukupno</span>
            <PriceTag price={total} size="lg" align="right" />
          </div>
          <div style={{ fontSize: 12, color: 'var(--sm-text-subtle)', textAlign: 'right', marginTop: 4 }}>Sa PDV-om · od toga PDV {fmt(vat)} din.</div>
        </aside>
      </div>
    </div>
  );
}

/* ---------- confirmation ---------- */
function Confirmation({ order, onNav }) {
  const wide = { maxWidth: 760, margin: '0 auto', padding: '0 24px' };
  return (
    <div style={{ ...wide, paddingTop: 40, paddingBottom: 56 }}>
      <div style={{ position: 'relative', textAlign: 'center', marginBottom: 30, paddingTop: 6, overflow: 'hidden' }}>
        {[
          { t: 8, l: '15%', s: 26, d: 0 }, { t: 52, l: '82%', s: 20, d: .5 }, { t: 100, l: '9%', s: 16, d: 1.1 },
          { t: 28, l: '89%', s: 28, d: .8 }, { t: 124, l: '80%', s: 15, d: .3 }, { t: 2, l: '66%', s: 14, d: 1.4 },
        ].map((p, i) => (
          <span key={i} style={{ position: 'absolute', top: p.t, left: p.l, fontSize: p.s, animation: `sm-twinkle 2.6s ease-in-out ${p.d}s infinite`, pointerEvents: 'none', filter: 'drop-shadow(0 1px 2px rgba(136,81,182,.3))' }}>✨</span>
        ))}
        <div style={{ position: 'relative', width: 168, height: 168, margin: '0 auto 4px' }}>
          <div style={{ position: 'absolute', inset: 0, borderRadius: '50%', background: 'radial-gradient(circle at 50% 55%, rgba(136,81,182,.22), transparent 66%)' }}></div>
          <img src={SM_DATA.A + '/mascot-genie.png'} alt="" style={{ position: 'relative', height: 168, objectFit: 'contain', animation: 'sm-float 5.5s ease-in-out infinite' }} />
          <span style={{ position: 'absolute', right: 22, bottom: 14, width: 44, height: 44, borderRadius: '50%', background: 'var(--sm-success)', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', border: '3px solid #fff', boxShadow: 'var(--sm-shadow-md)', animation: 'sm-pop .5s ease-out .2s both' }}>
            <i data-lucide="check" style={{ width: 24, height: 24, strokeWidth: 3 }} />
          </span>
        </div>
        <div style={{ fontFamily: 'var(--sm-font-techno)', textTransform: 'uppercase', letterSpacing: '.18em', fontSize: 12, fontWeight: 700, color: 'var(--sm-violet)', marginBottom: 10 }}>Tvoja želja je uslišena</div>
        <h1 style={{ fontSize: 34, margin: '0 0 12px', letterSpacing: '-.02em', lineHeight: 1.12 }}>Šaljemo je, {order.name.split(' ')[0]}! Abrakadabra ✨</h1>
        <p style={{ color: 'var(--sm-text-muted)', fontSize: 16.5, margin: '0 auto', maxWidth: 540, lineHeight: 1.6 }}>Duh je mahnuo rukom i tvoja porudžbina <b style={{ color: 'var(--sm-ink)' }}>#{order.num}</b> je krenula ka tebi. Potvrdu smo poslali na <b>{order.email}</b>.{order.entity === 'company' && ' R-1 faktura stiže na email firme.'}</p>
      </div>

      <div style={{ background: '#fff', border: '1px solid var(--sm-border)', borderRadius: 'var(--sm-radius-lg)', overflow: 'hidden' }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', gap: 10, padding: '18px 24px', background: 'var(--sm-purple-50)', borderBottom: '1px solid var(--sm-purple-100)' }}>
          <div>
            <div style={{ fontFamily: 'var(--sm-font-techno)', textTransform: 'uppercase', letterSpacing: '.12em', fontSize: 11, color: 'var(--sm-purple-700)' }}>Broj porudžbine</div>
            <div style={{ fontFamily: 'var(--sm-font-display)', fontWeight: 800, fontSize: 22, color: 'var(--sm-ink)' }}>#{order.num}</div>
          </div>
          <Badge tone="success" size="md">{I('clock', 13)} U obradi</Badge>
        </div>

        <div style={{ padding: 24 }}>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 18, marginBottom: 22 }}>
            <Info label="Dostava" value={order.delivery === 'courier' ? 'Kurirska dostava · 1–3 radna dana' : 'Lično preuzimanje · spremno za 2h'} />
            <Info label="Plaćanje" value={order.payment === 'cod' ? 'Pouzećem' : order.payment === 'card' ? 'Platnom karticom' : 'Virmanom / na račun'} />
            <Info label={order.entity === 'company' ? 'Firma' : 'Primalac'} value={order.entity === 'company' ? order.company : order.name} />
            <Info label="Adresa" value={`${order.address}, ${order.zip} ${order.city}`} />
            {order.entity === 'company' && <Info label="PIB" value={order.pib} />}
            {order.entity === 'company' && <Info label="Matični broj" value={order.mb} />}
          </div>

          <div style={{ borderTop: '1px solid var(--sm-border)', paddingTop: 18, display: 'flex', flexDirection: 'column', gap: 10 }}>
            {order.items.map(x => (
              <div key={x.id} style={{ display: 'flex', justifyContent: 'space-between', fontSize: 14.5 }}>
                <span style={{ color: 'var(--sm-text)' }}>{x.qty}× {x.title}</span>
                <span style={{ fontWeight: 700 }}>{fmt(x.price * x.qty)} din.</span>
              </div>
            ))}
          </div>
          {order.promoDiscount > 0 && (
            <div style={{ marginTop: 12, display: 'flex', justifyContent: 'space-between', fontSize: 14.5, color: 'var(--sm-primary)', fontWeight: 700 }}>
              <span>Promo · {order.promo}</span><span>−{fmt(order.promoDiscount)} din.</span>
            </div>
          )}
          <div style={{ borderTop: '1px solid var(--sm-border)', marginTop: 16, paddingTop: 16, display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
            <span style={{ fontFamily: 'var(--sm-font-display)', fontWeight: 700, fontSize: 18 }}>Ukupno</span>
            <PriceTag price={order.total} size="lg" align="right" />
          </div>
        </div>
      </div>

      <div style={{ display: 'flex', gap: 12, justifyContent: 'center', marginTop: 26, flexWrap: 'wrap' }}>
        <Button variant="outline" size="lg" onClick={() => onNav({ view: 'page', key: 'prati-porudzbinu' })} iconLeft={I('map-pin', 18)}>Prati porudžbinu</Button>
        <Button variant="primary" size="lg" onClick={() => onNav({ view: 'home' })} iconRight={I('arrow-right', 18)}>Nastavi kupovinu</Button>
      </div>
    </div>
  );
}

/* ---------- small building blocks ---------- */
function Card({ children }) {
  return <div style={{ background: '#fff', border: '1px solid var(--sm-border)', borderRadius: 'var(--sm-radius-lg)', padding: 24 }}>{children}</div>;
}
function SecTitle({ n, title, flush }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 11, marginBottom: flush ? 0 : 18 }}>
      {n && <span style={{ width: 28, height: 28, flex: 'none', borderRadius: '50%', background: 'var(--sm-primary)', color: '#fff', fontFamily: 'var(--sm-font-display)', fontWeight: 800, fontSize: 14, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>{n}</span>}
      <h3 style={{ fontSize: 18, margin: 0, fontFamily: 'var(--sm-font-display)', fontWeight: 700 }}>{title}</h3>
    </div>
  );
}
function EntityCard({ icon, title, desc, active, onClick }) {
  return (
    <button type="button" onClick={onClick} style={{
      textAlign: 'left', cursor: 'pointer', padding: '16px 16px', borderRadius: 'var(--sm-radius-md)',
      border: active ? '2px solid var(--sm-primary)' : '1.5px solid var(--sm-border)',
      backgroundColor: active ? 'var(--sm-purple-50)' : '#fff', transition: 'border-color .15s', display: 'flex', gap: 13, alignItems: 'flex-start',
    }}>
      <span style={{ width: 40, height: 40, flex: 'none', borderRadius: 'var(--sm-radius-sm)', backgroundColor: active ? 'var(--sm-primary)' : 'var(--sm-purple-50)', color: active ? '#fff' : 'var(--sm-primary)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>{I(icon, 21)}</span>
      <span style={{ minWidth: 0 }}>
        <span style={{ display: 'block', fontFamily: 'var(--sm-font-display)', fontWeight: 700, fontSize: 15.5, color: 'var(--sm-ink)' }}>{title}</span>
        <span style={{ display: 'block', fontSize: 12.5, color: 'var(--sm-text-muted)', lineHeight: 1.4, marginTop: 2 }}>{desc}</span>
      </span>
    </button>
  );
}
function OptionRow({ icon, title, desc, right, note, active, onClick }) {
  return (
    <button type="button" onClick={onClick} style={{
      display: 'flex', alignItems: 'center', gap: 14, textAlign: 'left', cursor: 'pointer', padding: '15px 16px', width: '100%',
      borderRadius: 'var(--sm-radius-md)', border: active ? '2px solid var(--sm-primary)' : '1.5px solid var(--sm-border)',
      backgroundColor: active ? 'var(--sm-purple-50)' : '#fff', transition: 'border-color .15s',
    }}>
      <span style={{ width: 20, height: 20, flex: 'none', borderRadius: '50%', border: active ? '6px solid var(--sm-primary)' : '2px solid var(--sm-gray-300)', transition: 'border .15s' }} />
      <span style={{ width: 38, height: 38, flex: 'none', borderRadius: 'var(--sm-radius-sm)', background: 'var(--sm-purple-50)', color: 'var(--sm-primary)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>{I(icon, 20)}</span>
      <span style={{ flex: 1, minWidth: 0 }}>
        <span style={{ display: 'block', fontFamily: 'var(--sm-font-display)', fontWeight: 700, fontSize: 15, color: 'var(--sm-ink)' }}>{title}</span>
        <span style={{ display: 'block', fontSize: 13, color: 'var(--sm-text-muted)', lineHeight: 1.4 }}>{desc}</span>
        {note && <span style={{ display: 'block', fontSize: 12, color: 'var(--sm-success)', fontWeight: 600, marginTop: 2 }}>{note}</span>}
      </span>
      {right && <span style={{ fontFamily: 'var(--sm-font-display)', fontWeight: 800, fontSize: 15, color: right === 'Besplatno' ? 'var(--sm-success)' : 'var(--sm-ink)', whiteSpace: 'nowrap' }}>{right}</span>}
    </button>
  );
}
function COField({ label, value, onChange, placeholder, type = 'text', hint, textarea }) {
  const base = { width: '100%', border: '1.5px solid var(--sm-border)', borderRadius: 'var(--sm-radius-sm)', padding: '0 15px', fontFamily: 'var(--sm-font-body)', fontSize: 15, outline: 'none', boxSizing: 'border-box', background: '#fff', transition: 'border-color .15s' };
  const focus = (e) => e.currentTarget.style.borderColor = 'var(--sm-primary)';
  const blur = (e) => e.currentTarget.style.borderColor = hint ? 'var(--sm-sale)' : 'var(--sm-border)';
  return (
    <div>
      <label style={{ display: 'block', fontFamily: 'var(--sm-font-display)', fontWeight: 600, fontSize: 13.5, marginBottom: 6, color: 'var(--sm-text)' }}>{label}</label>
      {textarea
        ? <textarea value={value} onChange={onChange} placeholder={placeholder} onFocus={focus} onBlur={blur} rows={2} style={{ ...base, height: 'auto', padding: '11px 15px', resize: 'vertical', lineHeight: 1.5, borderColor: hint ? 'var(--sm-sale)' : 'var(--sm-border)' }} />
        : <input type={type} value={value} onChange={onChange} placeholder={placeholder} onFocus={focus} onBlur={blur} style={{ ...base, height: 48, borderColor: hint ? 'var(--sm-sale)' : 'var(--sm-border)' }} />}
      {hint && <div style={{ fontSize: 12, color: 'var(--sm-sale)', marginTop: 5 }}>{hint}</div>}
    </div>
  );
}
function Recap({ rows }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 9 }}>
      {rows.map(([k, v], i) => (
        <div key={i} style={{ display: 'flex', gap: 14, fontSize: 14.5 }}>
          <span style={{ flex: '0 0 130px', color: 'var(--sm-text-muted)' }}>{k}</span>
          <span style={{ fontWeight: 600, color: 'var(--sm-text)' }}>{v}</span>
        </div>
      ))}
    </div>
  );
}
function Info({ label, value }) {
  return (
    <div>
      <div style={{ fontFamily: 'var(--sm-font-techno)', textTransform: 'uppercase', letterSpacing: '.1em', fontSize: 11, color: 'var(--sm-text-subtle)', marginBottom: 4 }}>{label}</div>
      <div style={{ fontWeight: 600, fontSize: 14.5, lineHeight: 1.4 }}>{value}</div>
    </div>
  );
}
function Stepper({ steps, active, onJump }) {
  const isMobile = useIsMobile();
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 0, background: '#fff', border: '1px solid var(--sm-border)', borderRadius: 'var(--sm-radius-pill)', padding: isMobile ? '10px 14px' : '10px 18px', overflow: 'hidden' }}>
      {steps.map((s, i) => {
        const done = i < active, cur = i === active;
        return (
          <React.Fragment key={i}>
            <button type="button" onClick={() => onJump(i)} style={{ display: 'flex', alignItems: 'center', gap: 9, background: 'none', border: 'none', cursor: i < active ? 'pointer' : 'default', padding: '2px 4px', flex: 'none' }}>
              <span style={{ width: 26, height: 26, flex: 'none', borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'var(--sm-font-display)', fontWeight: 800, fontSize: 13, backgroundColor: done || cur ? 'var(--sm-primary)' : 'var(--sm-gray-100)', color: done || cur ? '#fff' : 'var(--sm-text-subtle)' }}>
                {done ? <i data-lucide="check" style={{ width: 15, height: 15, strokeWidth: 3 }} /> : i + 1}
              </span>
              <span style={{ fontFamily: 'var(--sm-font-display)', fontWeight: cur ? 700 : 600, fontSize: 14.5, color: cur ? 'var(--sm-ink)' : done ? 'var(--sm-text)' : 'var(--sm-text-subtle)', whiteSpace: 'nowrap', display: (!isMobile || cur) ? 'inline' : 'none' }}>{s}</span>
            </button>
            {i < steps.length - 1 && <span style={{ flex: 1, minWidth: isMobile ? 10 : 16, height: 2, margin: isMobile ? '0 7px' : '0 12px', backgroundColor: i < active ? 'var(--sm-primary)' : 'var(--sm-border)', borderRadius: 2 }} />}
          </React.Fragment>
        );
      })}
    </div>
  );
}
const editLink = { display: 'inline-flex', alignItems: 'center', gap: 5, color: 'var(--sm-primary)', fontWeight: 600, fontSize: 13.5, cursor: 'pointer' };
function Line({ label, value, accent }) {
  return <div style={{ display: 'flex', justifyContent: 'space-between', padding: '6px 0', fontSize: 15 }}><span style={{ color: 'var(--sm-text-muted)' }}>{label}</span><span style={{ fontWeight: 700, color: accent ? 'var(--sm-primary)' : 'var(--sm-text)' }}>{value}</span></div>;
}

Object.assign(window, { Checkout });
