// ═══════════════════════════════════════════════
// JAGTAR STUDIO — Checkout Page
// ═══════════════════════════════════════════════

const JagtarCheckout = ({ onNavigate }) => {
  const { c, H2, H3, Body, Label, CTA, Field, Section, Img } = JAGTAR;
  const [step, setStep] = React.useState(0); // 0=details, 1=payment, 2=confirm
  const [submitting, setSubmitting] = React.useState(false);
  const [error, setError] = React.useState(null);
  const [orderResult, setOrderResult] = React.useState(null);
  const [form, setForm] = React.useState({
    first_name: '', last_name: '', email: '',
    street: '', city: '', postcode: '', country: '',
  });
  const update = (k) => (e) => setForm(s => ({ ...s, [k]: e.target.value }));

  const detailsValid = (
    form.first_name.trim() &&
    form.last_name.trim() &&
    /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email) &&
    form.street.trim() && form.city.trim() &&
    form.postcode.trim() && form.country.trim()
  );

  const submitOrder = async () => {
    if (submitting) return;
    setSubmitting(true);
    setError(null);
    try {
      const res = await window.api('/api/orders', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          customer_name: `${form.first_name} ${form.last_name}`.trim(),
          customer_email: form.email.trim(),
          shipping_address: {
            street: form.street.trim(),
            city: form.city.trim(),
            postcode: form.postcode.trim(),
            country: form.country.trim(),
          },
          total_amount: 49,
          currency: 'USD',
        }),
      });
      const data = await res.json().catch(() => null);
      if (!res.ok) throw new Error((data && data.error) || `Order failed (${res.status})`);
      setOrderResult(data);
      setStep(2);
    } catch (e) {
      setError(e.message || 'Could not place your order. Please try again.');
    } finally {
      setSubmitting(false);
    }
  };

  const ProgressBar = () => (
    <div style={{
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      gap: 0, marginBottom: 48,
    }}>
      {['Details', 'Payment', 'Confirmation'].map((label, i) => (
        <React.Fragment key={i}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <div style={{
              width: 28, height: 28, borderRadius: '50%',
              background: i <= step ? c.charcoal : 'transparent',
              border: `1.5px solid ${i <= step ? c.charcoal : c.border}`,
              color: i <= step ? c.bg : c.gray,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontFamily: "'Manrope', sans-serif", fontSize: 11, fontWeight: 500,
              transition: 'all 0.4s ease',
            }}>{i < step ? '✓' : i + 1}</div>
            <span style={{
              fontFamily: "'Manrope', sans-serif", fontSize: 13,
              fontWeight: i === step ? 600 : 400,
              color: i <= step ? c.charcoal : c.gray,
              letterSpacing: '0.04em',
              display: 'inline',
            }}>{label}</span>
          </div>
          {i < 2 && <div style={{
            width: 'clamp(24px, 4vw, 60px)', height: 1,
            background: i < step ? c.charcoal : c.border,
            margin: '0 12px',
            transition: 'background 0.4s ease',
          }} />}
        </React.Fragment>
      ))}
    </div>
  );

  const ErrorBanner = () => error ? (
    <div style={{
      padding: '12px 16px', marginBottom: 16,
      background: '#faecec', borderLeft: `3px solid ${c.error}`,
      color: '#6a2222', fontSize: 14,
    }}>{error}</div>
  ) : null;

  // ─── Step 0: Shipping Details ───
  const DetailsStep = () => (
    <div>
      <div style={{ textAlign: 'center', marginBottom: 40 }}>
        <H3>Where should we send it?</H3>
        <Body small style={{ color: c.gray, marginTop: 8 }}>Free worldwide delivery. Arrives in approximately 15 days.</Body>
      </div>

      <ErrorBanner />

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(240px, 1fr))', gap: '0 20px' }}>
        <Field label="First name" placeholder="Jane"
          name="first_name" value={form.first_name} onChange={update('first_name')}
          autoComplete="given-name" required />
        <Field label="Last name" placeholder="Smith"
          name="last_name" value={form.last_name} onChange={update('last_name')}
          autoComplete="family-name" required />
      </div>
      <Field label="Email address" placeholder="jane@example.com" type="email"
        name="email" value={form.email} onChange={update('email')}
        autoComplete="email" required />
      <Field label="Street address" placeholder="123 Main Street, Apt 4"
        name="street" value={form.street} onChange={update('street')}
        autoComplete="street-address" required />
      <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: '0 20px' }}>
        <Field label="City" placeholder="London"
          name="city" value={form.city} onChange={update('city')}
          autoComplete="address-level2" required />
        <Field label="Postcode" placeholder="SW1A 1AA"
          name="postcode" value={form.postcode} onChange={update('postcode')}
          autoComplete="postal-code" required />
      </div>
      <Field label="Country" placeholder="United Kingdom"
        name="country" value={form.country} onChange={update('country')}
        autoComplete="country-name" required />

      <div style={{
        display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        marginTop: 20, flexWrap: 'wrap', gap: 12,
      }}>
        <button onClick={() => onNavigate('product')} style={{
          fontFamily: "'Manrope', sans-serif", fontSize: 13,
          background: 'none', border: 'none', cursor: 'pointer',
          color: c.gray, padding: 0,
        }}>{'←'} Back to product</button>
        <CTA onClick={() => detailsValid && setStep(1)}
          style={detailsValid ? {} : { opacity: 0.5, cursor: 'not-allowed' }}>
          Continue to Payment
        </CTA>
      </div>
    </div>
  );

  // ─── Step 1: Payment ───
  const PaymentStep = () => (
    <div>
      <div style={{ textAlign: 'center', marginBottom: 40 }}>
        <H3>Payment</H3>
        <Body small style={{ color: c.gray, marginTop: 8 }}>Secure checkout. Your card is never stored.</Body>
      </div>

      <ErrorBanner />

      <Field label="Name on card" placeholder="Jane Smith" autoComplete="cc-name" />
      <Field label="Card number" placeholder="4242 4242 4242 4242" autoComplete="cc-number" />
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '0 20px' }}>
        <Field label="Expiry date" placeholder="MM / YY" autoComplete="cc-exp" />
        <Field label="Security code" placeholder="CVC" autoComplete="cc-csc" />
      </div>

      {/* Order summary inline */}
      <div style={{
        background: c.cream, padding: 24, marginTop: 16, marginBottom: 24,
      }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}>
          <Body small>Personalized Bust</Body>
          <Body small style={{ fontWeight: 500 }}>$49</Body>
        </div>
        <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}>
          <Body small style={{ color: c.gray }}>Shipping</Body>
          <Body small style={{ color: c.success }}>Free</Body>
        </div>
        <div style={{
          display: 'flex', justifyContent: 'space-between',
          paddingTop: 12, borderTop: `1px solid ${c.border}`,
        }}>
          <Body small style={{ fontWeight: 600 }}>Total</Body>
          <span style={{
            fontFamily: "'Cormorant Garamond', Georgia, serif",
            fontSize: 24, color: c.charcoal,
          }}>$49</span>
        </div>
      </div>

      <div style={{
        display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        flexWrap: 'wrap', gap: 12,
      }}>
        <button onClick={() => setStep(0)} disabled={submitting} style={{
          fontFamily: "'Manrope', sans-serif", fontSize: 13,
          background: 'none', border: 'none',
          cursor: submitting ? 'not-allowed' : 'pointer',
          opacity: submitting ? 0.5 : 1,
          color: c.gray, padding: 0,
        }}>{'←'} Back to details</button>
        <CTA onClick={submitOrder}
          style={submitting ? { opacity: 0.6, cursor: 'wait' } : {}}>
          {submitting ? 'Placing order…' : `Place Order — $49`}
        </CTA>
      </div>

      <Body small style={{ color: c.gray, marginTop: 16, textAlign: 'center' }}>
        Card processing is not yet live — your order is recorded and we’ll reach out for payment.
      </Body>
    </div>
  );

  // ─── Step 2: Confirmation ───
  const ConfirmStep = () => {
    const orderNumber = (orderResult && orderResult.order_number) || '#JS-2847';
    const days = (orderResult && orderResult.estimated_delivery_days) || 15;
    const eta = new Date(Date.now() + days * 24 * 60 * 60 * 1000)
      .toLocaleDateString(undefined, { month: 'long', day: 'numeric', year: 'numeric' });

    return (
      <div style={{ textAlign: 'center' }}>
        {/* Checkmark */}
        <div style={{
          width: 64, height: 64, borderRadius: '50%',
          background: c.success, display: 'flex',
          alignItems: 'center', justifyContent: 'center',
          margin: '0 auto 24px',
        }}>
          <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2.5">
            <polyline points="20 6 9 17 4 12" strokeLinecap="round" strokeLinejoin="round" />
          </svg>
        </div>

        <H3 style={{ marginBottom: 8 }}>Your commission has begun.</H3>
        <Body style={{ color: c.gray, maxWidth: 420, margin: '0 auto', marginBottom: 32 }}>
          We have received your order. You’ll receive a confirmation email at{' '}
          <strong style={{ color: c.charcoal }}>{form.email}</strong> with photo upload instructions.
        </Body>

        <div style={{
          background: c.cream, padding: 32, textAlign: 'left',
          maxWidth: 400, margin: '0 auto 32px',
        }}>
          <Label style={{ display: 'block', marginBottom: 16 }}>Order Summary</Label>
          {[
            ['Order', orderNumber],
            ['Item', 'Personalized Bust'],
            ['Total', '$49'],
            ['Estimated delivery', eta],
          ].map(([k, v]) => (
            <div key={k} style={{
              display: 'flex', justifyContent: 'space-between',
              padding: '8px 0', borderBottom: `1px solid ${c.border}`,
            }}>
              <Body small style={{ color: c.gray }}>{k}</Body>
              <Body small style={{ fontWeight: 500 }}>{v}</Body>
            </div>
          ))}
        </div>

        <Body small style={{ color: c.gray, marginBottom: 32 }}>
          Questions? Email us at hello@jagtarstudio.com
        </Body>

        <CTA secondary onClick={() => onNavigate('home')}>Return Home</CTA>
      </div>
    );
  };

  return (
    <div style={{ paddingTop: 72 }}>
      <Section style={{ minHeight: 'calc(100vh - 72px)', display: 'flex', alignItems: 'flex-start' }}>
        <div style={{ width: '100%' }}>
          {/* Two-column layout on desktop for steps 0 & 1 */}
          {step < 2 ? (
            <div style={{
              display: 'grid',
              gridTemplateColumns: 'repeat(auto-fit, minmax(340px, 1fr))',
              gap: 'clamp(32px, 5vw, 60px)',
              alignItems: 'start',
            }}>
              {/* Form column */}
              <div>
                <ProgressBar />
                {step === 0 ? <DetailsStep /> : <PaymentStep />}
              </div>

              {/* Sticky order card */}
              <div style={{
                position: 'sticky', top: 100,
                background: c.cream, padding: 'clamp(24px, 3vw, 40px)',
              }}>
                <Label style={{ display: 'block', marginBottom: 20 }}>Your Commission</Label>
                <Img label="bust preview" ratio="4/3" style={{ marginBottom: 20 }} />
                <H3 style={{ fontSize: 20, marginBottom: 8 }}>Personalized Bust</H3>
                <Body small style={{ color: c.gray, marginBottom: 4 }}>Hand-finished resin {'·'} ~15cm</Body>
                <Body small style={{ color: c.gray, marginBottom: 4 }}>2 photographs {'·'} 15 days</Body>

                <div style={{
                  marginTop: 20, paddingTop: 16,
                  borderTop: `1px solid ${c.border}`,
                  display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
                }}>
                  <Body small style={{ fontWeight: 500 }}>Total</Body>
                  <span style={{
                    fontFamily: "'Cormorant Garamond', Georgia, serif",
                    fontSize: 28, color: c.charcoal,
                  }}>$49</span>
                </div>
                <Body small style={{ color: c.success, marginTop: 6 }}>Free worldwide shipping</Body>

                {/* Subtle trust signals */}
                <div style={{ marginTop: 24, paddingTop: 16, borderTop: `1px solid ${c.border}` }}>
                  {['Secure payment', 'Free shipping worldwide', '15-day delivery guarantee'].map((t, i) => (
                    <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
                      <div style={{ width: 4, height: 4, borderRadius: '50%', background: c.gray }} />
                      <Body small style={{ color: c.gray, fontSize: 12 }}>{t}</Body>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          ) : (
            <div style={{ maxWidth: 500, margin: '0 auto' }}>
              <ProgressBar />
              <ConfirmStep />
            </div>
          )}
        </div>
      </Section>
    </div>
  );
};

Object.assign(window, { JagtarCheckout });
