/* OrderPanel v1 — slide-in drawer, 2 kroki
 * Krok 1: wybór pakietu
 * Krok 2: imię + email → od razu Stripe
 * Trigger: window.OW_ORDER(packageName) lub bez argumentu
 */

const OP_SANS  = '"Inter", system-ui, sans-serif';
const OP_SERIF = '"Instrument Serif", serif';
const OP_ACCENT = '#c87a52';
const OP_INK    = '#2b1f17';
const OP_BG     = '#faf5e9';
const OP_BORDER = '#e0d2b8';
const OP_MUTED  = '#8a7565';

const PACKAGES = [
  { name: 'Wspomnienie', sub: '5 zdjęć · ~35 sek', price: 179 },
  { name: 'Rodzinny',    sub: '12 zdjęć · ~1,5 min', price: 349 },
  { name: 'Saga',        sub: '20 zdjęć · ~2 min', price: 549, hot: true },
  { name: 'Kronika',     sub: '30 zdjęć · ~2,5 min · lektor', price: 899 },
];

const OP_KEYFRAMES = `
.ow-op-overlay { transition: opacity .3s; }
.ow-op-drawer  { transition: transform .35s cubic-bezier(.2,.7,.2,1); }
.ow-op-pkg:hover { border-color: ${OP_ACCENT} !important; background: #fff8f3 !important; }
.ow-op-input:focus { outline: none; border-color: ${OP_ACCENT} !important; box-shadow: 0 0 0 3px rgba(200,122,82,0.15); }
.ow-op-btn-primary:hover { background: #b06840 !important; }
.ow-op-btn-secondary:hover { background: #f0e8d8 !important; }
`;

function StepDots({ step }) {
  return (
    <div style={{ display: 'flex', gap: 6, alignItems: 'center', justifyContent: 'center', marginBottom: 32 }}>
      {[1,2].map(n => (
        <div key={n} style={{
          width: n === step ? 24 : 8, height: 8, borderRadius: 999,
          background: n === step ? OP_ACCENT : n < step ? '#d4b896' : OP_BORDER,
          transition: 'width .25s, background .25s',
        }} />
      ))}
    </div>
  );
}

function Step1({ selected, onSelect, onNext }) {
  return (
    <div>
      <StepDots step={1} />
      <h2 style={{ fontFamily: OP_SERIF, fontSize: 28, fontWeight: 400, color: OP_INK, margin: '0 0 6px' }}>
        Wybierz pakiet
      </h2>
      <p style={{ fontSize: 14, color: OP_MUTED, marginBottom: 24 }}>Możesz zmienić zdanie po obejrzeniu przykładu.</p>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        {PACKAGES.map(p => (
          <div key={p.name} className="ow-op-pkg" onClick={() => onSelect(p.name)}
            style={{
              border: `2px solid ${selected === p.name ? OP_ACCENT : OP_BORDER}`,
              background: selected === p.name ? '#fff8f3' : '#fff',
              borderRadius: 12, padding: '16px 20px',
              cursor: 'pointer', transition: 'border-color .2s, background .2s',
              display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12,
            }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
              <div style={{
                width: 20, height: 20, borderRadius: '50%', flexShrink: 0,
                border: `2px solid ${selected === p.name ? OP_ACCENT : OP_BORDER}`,
                background: selected === p.name ? OP_ACCENT : 'transparent',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}>
                {selected === p.name && <div style={{ width: 8, height: 8, borderRadius: '50%', background: '#fff' }} />}
              </div>
              <div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                  <span style={{ fontWeight: 600, fontSize: 15, color: OP_INK }}>{p.name}</span>
                  {p.hot && <span style={{ fontSize: 10, fontWeight: 700, letterSpacing: 1, color: '#fff', background: OP_ACCENT, padding: '2px 8px', borderRadius: 999 }}>POPULARNY</span>}
                </div>
                <div style={{ fontSize: 12, color: OP_MUTED, marginTop: 2 }}>{p.sub}</div>
              </div>
            </div>
            <div style={{ fontFamily: OP_SERIF, fontSize: 22, fontWeight: 400, color: OP_INK, whiteSpace: 'nowrap' }}>{p.price} zł</div>
          </div>
        ))}
      </div>
      <button className="ow-op-btn-primary" disabled={!selected} onClick={onNext}
        style={{
          marginTop: 24, width: '100%', background: selected ? OP_ACCENT : OP_BORDER,
          color: '#fff', border: 'none', padding: '16px', borderRadius: 10,
          fontSize: 15, fontWeight: 700, cursor: selected ? 'pointer' : 'default',
          fontFamily: OP_SANS, transition: 'background .2s',
        }}>
        Dalej →
      </button>
    </div>
  );
}

function Step2({ pkg, form, onChange, onPay, onBack, loading }) {
  const valid = form.name.trim() && form.email.includes('@');
  const inputStyle = {
    width: '100%', padding: '12px 14px', borderRadius: 8, boxSizing: 'border-box',
    border: `1.5px solid ${OP_BORDER}`, fontSize: 14, fontFamily: OP_SANS,
    color: OP_INK, background: '#fff', outline: 'none',
  };
  return (
    <div>
      <StepDots step={2} />
      <h2 style={{ fontFamily: OP_SERIF, fontSize: 28, fontWeight: 400, color: OP_INK, margin: '0 0 4px' }}>
        Twoje dane
      </h2>
      <p style={{ fontSize: 13, color: OP_MUTED, marginBottom: 24 }}>
        Pakiet: <strong style={{ color: OP_INK }}>{pkg?.name} — {pkg?.price} zł</strong>
      </p>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        <div>
          <label style={{ fontSize: 12, fontWeight: 600, color: OP_MUTED, letterSpacing: 0.5, display: 'block', marginBottom: 6 }}>IMIĘ *</label>
          <input className="ow-op-input" style={inputStyle} placeholder="Anna"
            value={form.name} onChange={e => onChange('name', e.target.value)} />
        </div>
        <div>
          <label style={{ fontSize: 12, fontWeight: 600, color: OP_MUTED, letterSpacing: 0.5, display: 'block', marginBottom: 6 }}>EMAIL *</label>
          <input className="ow-op-input" style={inputStyle} type="email" placeholder="anna@example.com"
            value={form.email} onChange={e => onChange('email', e.target.value)} />
        </div>
      </div>
      <div style={{ marginTop: 20, background: '#f5f0e8', borderRadius: 10, padding: '14px 16px', display: 'flex', gap: 12, alignItems: 'flex-start' }}>
        <span style={{ fontSize: 18, lineHeight: 1.2 }}>📬</span>
        <p style={{ fontSize: 13, color: OP_MUTED, margin: 0, lineHeight: 1.6 }}>
          Po płatności otrzymasz email z <strong style={{ color: OP_INK }}>linkiem do panelu</strong> — tam wgrasz zdjęcia i opiszesz wszystkie szczegóły.
        </p>
      </div>
      <div style={{ display: 'flex', gap: 10, marginTop: 24 }}>
        <button className="ow-op-btn-secondary" onClick={onBack}
          style={{ flex: '0 0 auto', background: '#f0e8d8', color: OP_INK, border: 'none', padding: '16px 20px', borderRadius: 10, fontSize: 14, fontWeight: 600, cursor: 'pointer', fontFamily: OP_SANS }}>
          ←
        </button>
        <button className="ow-op-btn-primary" disabled={!valid || loading} onClick={onPay}
          style={{
            flex: 1, background: valid ? OP_ACCENT : OP_BORDER,
            color: '#fff', border: 'none', padding: '16px', borderRadius: 10,
            fontSize: 15, fontWeight: 700, cursor: valid ? 'pointer' : 'default', fontFamily: OP_SANS,
          }}>
          {loading ? '⏳ Przekierowuję…' : `Zapłać ${pkg?.price} zł →`}
        </button>
      </div>
      <p style={{ fontSize: 11, color: OP_MUTED, textAlign: 'center', marginTop: 14, lineHeight: 1.5 }}>
        🔒 Twoje dane są bezpieczne · nie wysyłamy spamu
      </p>
    </div>
  );
}


function OrderPanel() {
  const [open, setOpen]       = React.useState(false);
  const [step, setStep]       = React.useState(1);
  const [selected, setSelected] = React.useState(null);
  const [form, setForm]       = React.useState({ name: '', email: '' });
  const [loading, setLoading] = React.useState(false);

  React.useEffect(() => {
    window.OW_ORDER = (pkgName) => {
      if (pkgName) setSelected(pkgName);
      setStep(pkgName ? 2 : 1);
      setOpen(true);
    };
    return () => { delete window.OW_ORDER; };
  }, []);

  const close = () => { setOpen(false); };
  const pkg   = PACKAGES.find(p => p.name === selected);

  const handlePay = async () => {
    setLoading(true);
    try {
      const res = await fetch('https://portal-api.ozywspomnienia.pl/checkout', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ package: selected, name: form.name, email: form.email }),
      });
      const data = await res.json();
      if (data.url) {
        window.location.href = data.url;
      } else {
        alert('Coś poszło nie tak. Spróbuj ponownie lub napisz do nas.');
        setLoading(false);
      }
    } catch (e) {
      alert('Błąd połączenia. Spróbuj ponownie.');
      setLoading(false);
    }
  };

  return (
    <>
      <style>{OP_KEYFRAMES}</style>
      <div className="ow-op-overlay" onClick={close} style={{
        position: 'fixed', inset: 0, background: 'rgba(20,12,6,0.5)',
        zIndex: 900, opacity: open ? 1 : 0, pointerEvents: open ? 'auto' : 'none',
        backdropFilter: 'blur(2px)',
      }} />
      <div className="ow-op-drawer" style={{
        position: 'fixed', top: 0, right: 0, bottom: 0,
        width: '100%', maxWidth: 480,
        background: OP_BG, zIndex: 901,
        transform: open ? 'translateX(0)' : 'translateX(100%)',
        display: 'flex', flexDirection: 'column',
        boxShadow: '-20px 0 60px rgba(0,0,0,0.18)',
      }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '22px 28px', borderBottom: `1px solid ${OP_BORDER}`, flexShrink: 0 }}>
          <div style={{ fontFamily: OP_SERIF, fontSize: 18, color: OP_INK, display: 'flex', alignItems: 'center', gap: 8 }}>
            <span style={{ width: 8, height: 8, borderRadius: '50%', background: OP_ACCENT, display: 'inline-block' }} />
            Ożywione Wspomnienia
          </div>
          <button onClick={close} style={{ background: 'none', border: 'none', fontSize: 22, cursor: 'pointer', color: OP_MUTED, lineHeight: 1, padding: 4 }}>✕</button>
        </div>
        <div style={{ flex: 1, overflowY: 'auto', padding: '32px 28px' }}>
          {step === 1 && <Step1 selected={selected} onSelect={setSelected} onNext={() => setStep(2)} />}
          {step === 2 && <Step2 pkg={pkg} form={form} onChange={(k,v) => setForm(f => ({...f,[k]:v}))} onPay={handlePay} onBack={() => setStep(1)} loading={loading} />}
        </div>
      </div>
    </>
  );
}

window.OrderPanel = OrderPanel;
