/* Mega-Sweets website — Build-a-Box -> details (quote request) -> confirmation */
const { useState, useEffect, useRef } = React;

function BuildABox({ initialPkg, onContinue, onBack, content }) {
  const packages = content.packages;
  const defaultPkg = initialPkg || (packages.find(p => p.name === 'Medium') ? 'Medium' : packages[0].name);
  const [pkg, setPkg] = useState(defaultPkg);
  const [flavors, setFlavors] = useState(() => content.flavors.slice(0, 2).map(f => f.name));
  const [sticks, setSticks] = useState(false);
  const [theme, setTheme] = useState('');

  const selected = packages.find(p => p.name === pkg) || packages[0];
  const base = selected.price;
  const total = base + (sticks ? 12 : 0);
  const maxFlavors = 5;

  const toggleFlavor = (name) => setFlavors(f =>
    f.includes(name) ? f.filter(x => x !== name) : (f.length < maxFlavors ? [...f, name] : f));

  return (
    <div className="build">
      <button className="ms-btn ms-btn--ghost build-back" onClick={onBack}>← Back</button>
      <div className="build-grid">
        <div className="build-main">
          <span className="section-label">Build a Box</span>
          <h1 style={{ marginTop: 4 }}>Design your treat box</h1>

          <h3 className="build-step">1 · Choose a package</h3>
          <div className="opt-row">
            {packages.map(p => (
              <button key={p.name} className={`opt ${pkg === p.name ? 'opt--on' : ''}`} onClick={() => setPkg(p.name)}>
                <span className="opt-name">{p.name}</span>
                <span className="small">{p.treats} treats</span>
                <span className="opt-price">${p.price}</span>
              </button>
            ))}
          </div>

          <h3 className="build-step">2 · Pick flavors <span className="small">({flavors.length}/{maxFlavors})</span></h3>
          <div className="chip-wrap">
            {content.flavors.map((f, i) => (
              <button key={f.name + i} className={`flavor-chip ${flavors.includes(f.name) ? 'flavor-chip--on' : ''}`} onClick={() => toggleFlavor(f.name)}>
                <img src={f.image} alt="" />{f.name}
              </button>
            ))}
          </div>

          <h3 className="build-step">3 · Make it yours</h3>
          <label className="upgrade">
            <input type="checkbox" checked={sticks} onChange={e => setSticks(e.target.checked)} />
            <span><strong>Acrylic popsicle sticks</strong> <span className="small">+$12 upgrade</span></span>
          </label>
          <div className="ms-field" style={{ marginTop: 14 }}>
            <label>Theme / colors / occasion</label>
            <input className="ms-input" placeholder="e.g. Mia's beach 8th birthday — teal & pink" value={theme} onChange={e => setTheme(e.target.value)} />
          </div>
        </div>

        <aside className="summary">
          <h3 style={{ marginTop: 0 }}>Your box</h3>
          <div className="sum-row"><span>{pkg} package</span><span>${base}</span></div>
          <div className="sum-sub">{selected.items.join(' · ')}</div>
          <div className="sum-flavors">
            {flavors.length ? flavors.map(f => <span key={f} className="ms-chip ms-chip--lavender">{f}</span>) : <span className="small">No flavors yet</span>}
          </div>
          {sticks && <div className="sum-row"><span>Acrylic sticks</span><span>$12</span></div>}
          <hr className="ms-divider-rainbow" style={{ margin: '14px 0' }} />
          <div className="sum-total"><span>Est. total</span><span className="price price--magenta">${total}</span></div>
          <button className="ms-btn ms-btn--primary sum-cta" disabled={!flavors.length}
            onClick={() => onContinue({ pkg, flavors, sticks, theme, total })}>Continue →</button>
          <p className="small sum-note">Custom colors included · Wrapped &amp; boxed</p>
        </aside>
      </div>
    </div>
  );
}

const MS_EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

function OrderDetails({ order, onBack, onDone }) {
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [phone, setPhone] = useState('');
  const [eventDate, setEventDate] = useState('');
  const [notes, setNotes] = useState('');
  const [token, setToken] = useState('');
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState('');
  const widgetRef = useRef(null);
  const rendered = useRef(false);

  // Explicitly render Turnstile once its script is ready (auto-render misses
  // elements mounted after initial page scan in this SPA).
  useEffect(() => {
    const id = setInterval(() => {
      if (window.turnstile && widgetRef.current && !rendered.current) {
        rendered.current = true;
        try {
          window.turnstile.render(widgetRef.current, {
            sitekey: (window.MS_CONFIG && window.MS_CONFIG.turnstileSiteKey) || '',
            callback: (t) => setToken(t),
            'error-callback': () => setToken(''),
            'expired-callback': () => setToken(''),
          });
        } catch (e) { /* already rendered */ }
        clearInterval(id);
      }
    }, 200);
    return () => clearInterval(id);
  }, []);

  const emailOk = MS_EMAIL_RE.test(email);
  const canSubmit = name.trim() && emailOk && phone.trim() && eventDate && token && !submitting;

  const submit = async () => {
    setError('');
    if (!name.trim() || !emailOk || !phone.trim() || !eventDate) {
      setError('Please fill in all required fields with a valid email.');
      return;
    }
    if (!token) {
      setError('Please wait a moment for the spam check to finish, then try again.');
      return;
    }
    setSubmitting(true);
    try {
      const res = await fetch('/api/order', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name: name.trim(), email: email.trim(), phone: phone.trim(), eventDate, notes: notes.trim(),
          pkg: order.pkg, flavors: order.flavors, sticks: order.sticks, theme: order.theme, total: order.total,
          turnstileToken: token,
        }),
      });
      const data = await res.json();
      if (data.ok) {
        onDone();
      } else {
        setError(data.error || 'Something went wrong. Please try again.');
        if (window.turnstile) window.turnstile.reset();
        setToken('');
      }
    } catch (e) {
      setError('Network error. Please check your connection and try again.');
    } finally {
      setSubmitting(false);
    }
  };

  const base = order.total - (order.sticks ? 12 : 0);
  return (
    <div className="build">
      <button className="ms-btn ms-btn--ghost build-back" onClick={onBack}>← Back to box</button>
      <div className="build-grid">
        <div className="build-main">
          <span className="section-label" style={{ color: 'var(--ms-magenta)' }}>Almost there</span>
          <h1 style={{ marginTop: 4 }}>Your details</h1>
          <p className="body-muted" style={{ maxWidth: 520 }}>Every order is custom, so this is a <strong>quote request</strong> — no payment now. We'll review your box and email you a quote.</p>

          <div className="ms-field" style={{ marginTop: 18 }}>
            <label>Name <span className="od-req">*</span></label>
            <input className="ms-input" value={name} onChange={e => setName(e.target.value)} />
          </div>
          <div className="od-row">
            <div className="ms-field">
              <label>Email <span className="od-req">*</span></label>
              <input className="ms-input" type="email" value={email} onChange={e => setEmail(e.target.value)} />
            </div>
            <div className="ms-field">
              <label>Phone <span className="od-req">*</span></label>
              <input className="ms-input" type="tel" value={phone} onChange={e => setPhone(e.target.value)} />
            </div>
          </div>
          <div className="ms-field">
            <label>Event / pickup date <span className="od-req">*</span></label>
            <input className="ms-input" type="date" value={eventDate} onChange={e => setEventDate(e.target.value)} />
          </div>
          <div className="ms-field">
            <label>Anything else?</label>
            <input className="ms-input" placeholder="Pickup vs delivery, allergies, inspo links…" value={notes} onChange={e => setNotes(e.target.value)} />
          </div>

          <div ref={widgetRef} style={{ marginTop: 16 }}></div>
          {error && <p className="od-error">{error}</p>}
        </div>

        <aside className="summary">
          <h3 style={{ marginTop: 0 }}>Your box</h3>
          <div className="sum-row"><span>{order.pkg} package</span><span>${base}</span></div>
          <div className="sum-flavors">{order.flavors.map(f => <span key={f} className="ms-chip ms-chip--lavender">{f}</span>)}</div>
          {order.sticks && <div className="sum-row"><span>Acrylic sticks</span><span>$12</span></div>}
          {order.theme && <p className="small" style={{ margin: '8px 0 0' }}>Theme: <strong>{order.theme}</strong></p>}
          <hr className="ms-divider-rainbow" style={{ margin: '14px 0' }} />
          <div className="sum-total"><span>Est. total</span><span className="price price--magenta">${order.total}</span></div>
          <button className="ms-btn ms-btn--primary sum-cta" disabled={!canSubmit} onClick={submit}>
            {submitting ? 'Sending…' : 'Request My Quote'}
          </button>
          <p className="small sum-note">Final price confirmed by email · No payment now</p>
        </aside>
      </div>
    </div>
  );
}

function Confirmation({ order, onHome }) {
  return (
    <div className="confirm">
      <img className="confirm-flourish" src="assets/flourish-divider.png" alt="" />
      <span className="section-label" style={{ color: 'var(--ms-magenta)' }}>Quote Request Received</span>
      <h1>Thanks — your request is in!</h1>
      <p className="tagline">— Perfect for celebrations —</p>
      <div className="ms-card confirm-card">
        <div className="sum-row"><span>{order.pkg} package</span><span>${order.total - (order.sticks ? 12 : 0)}</span></div>
        <div className="sum-flavors">{order.flavors.map(f => <span key={f} className="ms-chip ms-chip--mint">{f}</span>)}</div>
        {order.sticks && <div className="sum-row"><span>Acrylic sticks</span><span>$12</span></div>}
        {order.theme && <p className="small" style={{ margin: '10px 0 0' }}>Theme: <strong>{order.theme}</strong></p>}
        <hr className="ms-divider-dotted" />
        <div className="sum-total"><span>Est. total</span><span className="price price--magenta">${order.total}</span></div>
      </div>
      <p className="small" style={{ maxWidth: 420, margin: '4px auto 18px', textAlign: 'center' }}>
        We'll review your box and email you a confirmed quote soon. Keep an eye on your inbox!
      </p>
      <button className="ms-btn ms-btn--teal" onClick={onHome}>Back to Home</button>
    </div>
  );
}

Object.assign(window, { BuildABox, OrderDetails, Confirmation });
