// sections-bot.jsx — OrderForm, Pickup+Map, Payment, Founder, FAQ, Footer

const { useState: useS2, useRef: useR2 } = React;

// ─────────────────────────────────────────────────────────────────────────────
function OrderForm({ presetTier, onClear }) {
  const tierMap = {
    single: { qty: 1,  price: 5  },
    five:   { qty: 5,  price: 22 },
    ten:    { qty: 10, price: 40 },
  };
  const [tier, setTier] = useS2(presetTier || 'five');
  const [name, setName] = useS2('');
  const [contact, setContact] = useS2('');
  const [carrier, setCarrier] = useS2('');
  const [pay, setPay] = useS2('Venmo');
  const [pickup, setPickup] = useS2('');
  const [notes, setNotes] = useS2('');
  const [submitted, setSubmitted] = useS2(false);
  const [done,      setDone]      = useS2(false);
  const [orderErr,  setOrderErr]  = useS2(false);

  React.useEffect(() => { if (presetTier) setTier(presetTier); }, [presetTier]);

  const total = tierMap[tier].price;
  const qty   = tierMap[tier].qty;

  // Detect if contact looks like a phone number vs email
  const contactIsPhone = contact.length > 0 && !contact.includes('@') && /\d{7,}/.test(contact.replace(/\D/g,''));

  const carriers = [
    { value: 'att',     label: 'AT&T'              },
    { value: 'tmobile', label: 'T-Mobile'           },
    { value: 'verizon', label: 'Verizon'            },
    { value: 'visible', label: 'Visible'            },
    { value: 'cricket', label: 'Cricket'            },
    { value: 'metro',   label: 'Metro by T-Mobile'  },
    { value: 'boost',   label: 'Boost Mobile'       },
    { value: 'fi',      label: 'Google Fi'          },
    { value: 'other',   label: 'Other / Skip text'  },
  ];

  const submit = (e) => {
    e.preventDefault();
    setSubmitted(true); setOrderErr(false);
    fetch('/order.php', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        name, contact, carrier,
        pack:    `${qty} ball${qty > 1 ? 's' : ''} (${tier})`,
        price:   String(total),
        payment: pay,
        pickup:  pickup || '—',
        notes:   notes  || '—',
      }),
    })
    .then(r => r.json())
    .then(d => { if (d.success) { setDone(true); } else { setOrderErr(true); setSubmitted(false); } })
    .catch(() => { setOrderErr(true); setSubmitted(false); });
  };

  const inputStyle = {
    width: '100%', padding: '14px 16px', borderRadius: 10,
    border: '1px solid var(--line-strong)', background: 'var(--paper)',
    fontFamily: 'var(--sans)', fontSize: 15, color: 'var(--ink)',
    outline: 'none',
  };
  const labelStyle = { fontFamily: 'var(--mono)', fontSize: 11, letterSpacing: '.14em', textTransform: 'uppercase', color: 'var(--ink-mute)', display: 'block', marginBottom: 8 };

  return (
    <section id="order">
      <div className="wrap">
        <div style={{ display: 'grid', gridTemplateColumns: '1.1fr 1fr', gap: 'clamp(32px, 5vw, 80px)' }}>
          <div>
            <span className="eyebrow">Order</span>
            <h2 style={{ marginTop: 16 }}>Reserve your date balls.</h2>
            <p style={{ marginTop: 20, fontSize: 17, color: 'var(--ink-soft)', maxWidth: 460 }}>
              Send your order through the form. Ela will confirm by text within a few hours and arrange pickup in Frisco.
            </p>

            <div style={{ marginTop: 36, padding: 24, borderRadius: 'var(--radius)', background: 'var(--bg-soft)', border: '1px solid var(--line)' }}>
              <div className="uppercase mono" style={{ color: 'var(--ink-mute)' }}>How it works</div>
              <ol style={{ paddingLeft: 0, listStyle: 'none', margin: '20px 0 0', display: 'flex', flexDirection: 'column', gap: 18 }}>
                {[
                  ['Send order', 'Fill the form. Pick your pack and payment method.'],
                  ['Get confirmed', 'Ela replies with pickup window and total.'],
                  ['Pickup + pay', 'Stop by the porch. Pay on arrival or in advance.'],
                ].map((s, i) => (
                  <li key={i} style={{ display: 'grid', gridTemplateColumns: '40px 1fr', alignItems: 'baseline', gap: 14 }}>
                    <span style={{ fontFamily: 'var(--display)', fontSize: 28, color: 'var(--accent)' }}>0{i+1}</span>
                    <div>
                      <div style={{ fontFamily: 'var(--display)', fontSize: 22 }}>{s[0]}</div>
                      <div style={{ color: 'var(--ink-soft)', fontSize: 14, marginTop: 2 }}>{s[1]}</div>
                    </div>
                  </li>
                ))}
              </ol>
            </div>
          </div>

          <form onSubmit={submit} style={{
            background: 'var(--paper)', border: '1px solid var(--line)', borderRadius: 'var(--radius-lg)',
            padding: 'clamp(24px, 3vw, 36px)', display: 'flex', flexDirection: 'column', gap: 18,
          }}>
            <div>
              <label style={labelStyle}>Pack</label>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 8 }}>
                {Object.entries(tierMap).map(([k, v]) => (
                  <button type="button" key={k} onClick={() => setTier(k)}
                    style={{
                      padding: '14px 8px', borderRadius: 10,
                      border: '1px solid ' + (tier === k ? 'var(--ink)' : 'var(--line-strong)'),
                      background: tier === k ? 'var(--ink)' : 'transparent',
                      color: tier === k ? 'var(--bg)' : 'var(--ink)',
                      textAlign: 'center',
                      transition: 'all .15s ease',
                    }}>
                    <div style={{ fontFamily: 'var(--display)', fontSize: 22 }}>{v.qty}</div>
                    <div style={{ fontFamily: 'var(--mono)', fontSize: 10, letterSpacing: '.1em' }}>${v.price}</div>
                  </button>
                ))}
              </div>
            </div>

            <div>
              <label style={labelStyle}>Your name</label>
              <input style={inputStyle} value={name} onChange={e => setName(e.target.value)} required placeholder="Jordan Reeves" />
            </div>
            <div>
              <label style={labelStyle}>Phone or email</label>
              <input style={inputStyle} value={contact} onChange={e => { setContact(e.target.value); setCarrier(''); }} required placeholder="(214) 555-0102" />
              <p style={{ margin: '8px 0 0', fontFamily: 'var(--mono)', fontSize: 11, color: 'var(--ink-mute)', letterSpacing: '.06em' }}>
                Enter a phone number to get a text confirmation, or an email address for an email confirmation.
              </p>
            </div>

            {contactIsPhone && (
              <div>
                <label style={labelStyle}>Your carrier</label>
                <select
                  value={carrier}
                  onChange={e => setCarrier(e.target.value)}
                  required
                  style={{ ...inputStyle, appearance: 'none', WebkitAppearance: 'none', backgroundImage: 'url("data:image/svg+xml,%3Csvg xmlns=\'http://www.w3.org/2000/svg\' width=\'12\' height=\'8\' viewBox=\'0 0 12 8\'%3E%3Cpath d=\'M1 1l5 5 5-5\' stroke=\'%238A745A\' stroke-width=\'1.5\' fill=\'none\' stroke-linecap=\'round\'/%3E%3C/svg%3E")', backgroundRepeat: 'no-repeat', backgroundPosition: 'right 16px center', paddingRight: 40, cursor: 'pointer' }}
                >
                  <option value="" disabled>Select your carrier…</option>
                  {carriers.map(c => (
                    <option key={c.value} value={c.value}>{c.label}</option>
                  ))}
                </select>
                <p style={{ margin: '8px 0 0', fontFamily: 'var(--mono)', fontSize: 11, color: 'var(--ink-mute)', letterSpacing: '.06em' }}>
                  Needed to send your text confirmation. "Other" skips the text.
                </p>
              </div>
            )}

            <div>
              <label style={labelStyle}>Payment method</label>
              <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                {['Venmo','Zelle','Apple Pay','PayPal','Cash'].map(p => (
                  <button type="button" key={p} onClick={() => setPay(p)}
                    style={{
                      padding: '10px 14px', borderRadius: 999,
                      border: '1px solid ' + (pay === p ? 'var(--ink)' : 'var(--line-strong)'),
                      background: pay === p ? 'var(--ink)' : 'transparent',
                      color: pay === p ? 'var(--bg)' : 'var(--ink)',
                      fontSize: 13, transition: 'all .15s',
                    }}>{p}</button>
                ))}
              </div>
            </div>

            <div>
              <label style={labelStyle}>Preferred pickup day</label>
              <input style={inputStyle} value={pickup} onChange={e => setPickup(e.target.value)} placeholder="Saturday afternoon, or anytime this week" />
            </div>
            <div>
              <label style={labelStyle}>Notes (optional)</label>
              <textarea style={{ ...inputStyle, minHeight: 80, fontFamily: 'var(--sans)' }} value={notes} onChange={e => setNotes(e.target.value)} placeholder="Team order, allergies to flag, etc." />
            </div>

            <div style={{ borderTop: '1px solid var(--line)', paddingTop: 18, marginTop: 6, display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
              <div>
                <div className="uppercase mono" style={{ color: 'var(--ink-mute)' }}>Total</div>
                <div style={{ fontFamily: 'var(--display)', fontSize: 40, lineHeight: 1 }}>${total}</div>
                <div style={{ fontFamily: 'var(--mono)', fontSize: 11, color: 'var(--ink-mute)', marginTop: 4 }}>{qty} ball{qty>1?'s':''} · pickup only</div>
              </div>
              {orderErr && (
                <p style={{ color: '#c0392b', fontFamily: 'var(--mono)', fontSize: 12, marginBottom: 8 }}>
                  Something went wrong — please email ela@realdateballs.com directly.
                </p>
              )}
              {done ? (
                <div style={{ textAlign: 'right' }}>
                  <div style={{ fontFamily: 'var(--display)', fontSize: 22, color: 'var(--accent)' }}>Order sent ✓</div>
                  <div style={{ fontFamily: 'var(--mono)', fontSize: 12, color: 'var(--ink-mute)', marginTop: 4 }}>
                    Check your {contact.includes('@') ? 'email' : 'phone'} for a confirmation. Ela will be in touch soon!
                  </div>
                </div>
              ) : (
                <button type="submit" className="btn" style={{ padding: '16px 28px' }} disabled={submitted}>
                  {submitted ? 'Sending…' : 'Send order'} {!submitted && <span className="arr">→</span>}
                </button>
              )}
            </div>
          </form>
        </div>
      </div>
    </section>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
function PickupMap() {
  // 13030 Dolomite Drive, Frisco, TX 75035 — Richwoods community
  const address = '13030 Dolomite Drive, Frisco, TX 75035';
  const src = `https://www.google.com/maps?q=${encodeURIComponent(address)}&z=16&output=embed`;
  const directions = `https://www.google.com/maps/dir/?api=1&destination=${encodeURIComponent(address)}`;

  return (
    <section id="pickup">
      <div className="wrap">
        <div style={{ display: 'flex', justifyContent: 'space-between', flexWrap: 'wrap', gap: 24, alignItems: 'end', marginBottom: 48 }}>
          <div style={{ maxWidth: 600 }}>
            <span className="eyebrow">Pickup</span>
            <h2 style={{ marginTop: 16 }}>Made local. <em>Picked up local.</em></h2>
          </div>
          <p style={{ maxWidth: 380, color: 'var(--ink-soft)' }}>
            Every ball is hand-rolled in a home kitchen in Frisco, Texas. Order ahead, swing by the porch, grab your date balls.
          </p>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 24 }}>
          <div style={{
            borderRadius: 'var(--radius-lg)', overflow: 'hidden',
            border: '1px solid var(--line-strong)', position: 'relative',
            minHeight: 460, background: 'var(--bg-soft)',
          }}>
            <iframe
              title="Pickup location — Frisco, TX"
              src={src}
              style={{ width: '100%', height: '100%', border: 0, minHeight: 460, filter: 'sepia(0.15) saturate(0.85)' }}
              loading="lazy"
            />
            <div style={{
              position: 'absolute', left: 18, top: 18,
              background: 'var(--bg)', border: '1px solid var(--line-strong)',
              padding: '8px 12px', borderRadius: 8,
              fontFamily: 'var(--mono)', fontSize: 11, letterSpacing: '.14em', textTransform: 'uppercase',
            }}>◆ Pickup HQ · Richwoods, Frisco</div>
          </div>

          <div style={{ background: 'var(--paper)', border: '1px solid var(--line)', borderRadius: 'var(--radius-lg)', padding: 'clamp(24px, 3vw, 40px)' }}>
            <div className="uppercase mono" style={{ color: 'var(--ink-mute)' }}>Address</div>
            <div style={{ fontFamily: 'var(--display)', fontSize: 'clamp(26px, 2.4vw, 34px)', marginTop: 10, lineHeight: 1.1 }}>
              13030 Dolomite Drive<br/>Frisco, TX 75035
            </div>
            <div className="mono uppercase" style={{ color: 'var(--ink-mute)', marginTop: 12 }}>◆ Richwoods community</div>
            <div style={{ color: 'var(--ink-soft)', marginTop: 12, maxWidth: 380 }}>
              Order ahead by text or through the form below. Ela will confirm a pickup window that works for your schedule.
            </div>

            <div className="rule" style={{ margin: '28px 0' }} />

            <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap' }}>
              <a href={directions} target="_blank" rel="noreferrer" className="btn">
                Get directions <span className="arr">→</span>
              </a>
              <a href="#order" className="btn ghost">Place an order</a>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
function PaymentBadge({ name }) {
  // tiny SVG marks per service, on a chip
  const marks = {
    'Venmo': (
      <svg viewBox="0 0 24 24" width="20" height="20"><rect width="24" height="24" rx="5" fill="#008CFF"/><path d="M16.5 6.5c.4.8.6 1.7.6 2.6 0 3-2.5 6.8-4.5 9.4H8.4L6 7.2l3.5-.4 1.4 9.1c1.2-2 2.8-5.3 2.8-7.4 0-1.1-.2-1.9-.5-2.6l3.3.6Z" fill="#fff"/></svg>
    ),
    'Zelle': (
      <svg viewBox="0 0 24 24" width="20" height="20"><rect width="24" height="24" rx="5" fill="#6D1ED4"/><path d="M9 6h6v2l-4.5 6H15v2H9v-2l4.5-6H9V6Z" fill="#fff"/><circle cx="12" cy="3.6" r="1.2" fill="#fff"/><circle cx="12" cy="20.4" r="1.2" fill="#fff"/></svg>
    ),
    'Apple Pay': (
      <svg viewBox="0 0 24 24" width="20" height="20"><rect width="24" height="24" rx="5" fill="#000"/><path d="M8.6 9.4c-.6 0-1.4-.4-1.4-1.5 0-1.1.9-1.7 1.4-1.7 0 .8-.4 1.3-.4 1.3s.4.2.4.4c0 .4-.3.6-.3.9.1.4.3.6.3.6Zm-1 .9c.7 0 1-.4 1.7-.4.7 0 1 .4 1.7.4 1 0 1.7-.9 2.2-1.8-.5-.3-1.2-.8-1.2-1.7 0-.9.7-1.4 1-1.6-.4-.7-1.1-1-1.6-1-.7-.1-1.3.4-1.7.4-.4 0-1-.4-1.6-.4-.8 0-1.6.4-2 1.2-.9 1.5-.2 3.7.6 4.9.5.6 1 1 1.4 1Z" fill="#fff"/><text x="13" y="16" fontFamily="Helvetica" fontSize="7" fontWeight="700" fill="#fff">Pay</text></svg>
    ),
    'PayPal': (
      <svg viewBox="0 0 24 24" width="20" height="20"><rect width="24" height="24" rx="5" fill="#003087"/><path d="M9 16.5h2.2l.5-3h1.4c2.4 0 4-1.3 4.4-3.6.2-1.1-.1-1.9-.7-2.4-.7-.6-1.7-.9-3-.9H10c-.3 0-.5.2-.6.5L8 16.2c0 .2.1.3.3.3H9Zm3.5-8c1.4 0 2.2.5 2 1.8-.2 1.4-1.1 2-2.5 2H11l.6-3.8h.9Z" fill="#fff"/></svg>
    ),
    'Cash': (
      <svg viewBox="0 0 24 24" width="20" height="20"><rect width="24" height="24" rx="5" fill="#1F8A5B"/><circle cx="12" cy="12" r="4" fill="#fff" opacity="0.18"/><text x="12" y="15.5" textAnchor="middle" fontFamily="Helvetica" fontSize="11" fontWeight="700" fill="#fff">$</text></svg>
    ),
  };
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 12,
      padding: '14px 18px', borderRadius: 12,
      border: '1px solid var(--line-strong)', background: 'var(--paper)',
    }}>
      {marks[name]}
      <span style={{ fontFamily: 'var(--display)', fontSize: 20 }}>{name}</span>
    </div>
  );
}

function Payment() {
  const methods = ['Venmo', 'Zelle', 'Apple Pay', 'PayPal', 'Cash'];
  return (
    <section id="payment" className="tight" style={{ background: 'var(--bg-soft)' }}>
      <div className="wrap">
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1.4fr', gap: 'clamp(32px, 5vw, 80px)', alignItems: 'center' }}>
          <div>
            <span className="eyebrow">Payment</span>
            <h2 style={{ marginTop: 16 }}>Pay however<br/><em>works for you.</em></h2>
            <p style={{ marginTop: 20, fontSize: 16, color: 'var(--ink-soft)', maxWidth: 380 }}>
              No card terminals, no app downloads. Pay on pickup or in advance — whichever's easier.
            </p>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(170px, 1fr))', gap: 12 }}>
            {methods.map(m => <PaymentBadge key={m} name={m} />)}
          </div>
        </div>
      </div>
    </section>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
function Founder() {
  return (
    <section id="founder">
      <div className="wrap">
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1.2fr', gap: 'clamp(32px, 5vw, 80px)', alignItems: 'start' }}>
          <div style={{
            aspectRatio: '4/5', minHeight: 460, position: 'sticky', top: 100,
            borderRadius: 'var(--radius-lg)', overflow: 'hidden',
            border: '1px solid var(--line)',
          }}>
            <img src="assets/founder.jpeg" alt="Ela Junnarkar — founder of Real Date Balls"
              style={{ width: '100%', height: '100%', objectFit: 'cover', objectPosition: 'center 28%', display: 'block' }} />
          </div>
          <div>
            <span className="eyebrow">The Founder</span>
            <h2 style={{ marginTop: 16 }}>
              Hi, I'm <em>Ela</em>.
            </h2>
            <p style={{ marginTop: 24, fontFamily: 'var(--display)', fontSize: 26, lineHeight: 1.3, color: 'var(--ink)' }}>
              "At swim meets, I watched my teammates rip open energy gel after energy gel and still feel hungry. It would lead to either overeating right before a race and feeling sick — or chugging more gels, which isn't good for you. I wanted something better."
            </p>
            <div style={{ marginTop: 28, color: 'var(--ink-soft)', fontSize: 17, lineHeight: 1.7, maxWidth: 560, display: 'flex', flexDirection: 'column', gap: 16 }}>
              <p>
                Real Date Balls started in my kitchen with two ingredients I knew I could trust — organic dates and organic cashews — and a goal: a snack that's real food, that travels well, and that actually keeps you full.
              </p>
              <p>
                I built it for swim, but it's for <em>any</em> sport — soccer practice, a track meet, a long hike, a tournament weekend. And honestly, you don't have to be an athlete at all. If you want a clean, filling snack between classes, before a long shift, or in your kid's lunchbox, this date ball is for you too.
              </p>
              <p>
                Every ball is hand-rolled and made in small batches in Frisco. I'm a competitive swimmer first, but Real Date Balls is for anyone who wants real food they can trust.
              </p>
            </div>

            <div style={{ marginTop: 36, display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 0, border: '1px solid var(--line-strong)', borderRadius: 'var(--radius)' }}>
              {[
                ['Hometown', 'Frisco, TX'],
                ['Made for', 'Every sport · every body'],
                ['Founded',  '2026'],
              ].map(([k, v], i) => (
                <div key={k} style={{ padding: 20, borderRight: i < 2 ? '1px solid var(--line)' : 'none' }}>
                  <div className="uppercase mono" style={{ color: 'var(--ink-mute)' }}>{k}</div>
                  <div style={{ fontFamily: 'var(--display)', fontSize: 22, marginTop: 6 }}>{v}</div>
                </div>
              ))}
            </div>

            <div style={{ marginTop: 28 }}>
              <a href="#order" className="btn">Try a date ball Ela made <span className="arr">→</span></a>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// Reviews — leave a review + see existing reviews. Stored in localStorage.
const SEED_REVIEWS = [
  { name: 'Mia R.', role: 'Varsity swimmer · 16', rating: 5, date: 'May 14, 2026',
    body: 'I used to eat three gels at finals and still feel shaky. One Real Date Ball before warm-ups and I\'m good through prelims. Tastes like real food, not goo.' },
  { name: 'Coach D.', role: 'Club coach, FAST', rating: 5, date: 'Apr 28, 2026',
    body: 'Bought a 10-pack for my distance group. The kids actually finished them — which never happens with the protein bars. Two ingredients, no parent complaints.' },
  { name: 'Priya S.', role: 'Swim parent', rating: 5, date: 'Apr 21, 2026',
    body: 'Got these for my daughter\'s meet. She said they kept her full between her 200 free and 100 back. I tried one too — chewy, not too sweet, and I trust the ingredient list.' },
  { name: 'Jordan T.', role: 'Cross country', rating: 4, date: 'Apr 06, 2026',
    body: 'Took one before a long run. Solid, sustained energy and no stomach drop. Wish it came in a slightly bigger size for longer efforts, but the regular is great.' },
];

function Stars({ value, onChange, size = 18, interactive = false }) {
  const [hover, setHover] = useS2(0);
  return (
    <div style={{ display: 'inline-flex', gap: 2 }}>
      {[1,2,3,4,5].map(i => {
        const active = (hover || value) >= i;
        return (
          <button key={i} type="button"
            disabled={!interactive}
            onMouseEnter={() => interactive && setHover(i)}
            onMouseLeave={() => interactive && setHover(0)}
            onClick={() => interactive && onChange && onChange(i)}
            aria-label={`${i} star${i>1?'s':''}`}
            style={{
              background: 'transparent', border: 0, padding: 0,
              cursor: interactive ? 'pointer' : 'default',
              lineHeight: 0,
            }}>
            <svg viewBox="0 0 24 24" width={size} height={size}>
              <path d="M12 2l2.95 6.6 7.05.7-5.3 4.8 1.6 7-6.3-3.7-6.3 3.7 1.6-7L2 9.3l7.05-.7L12 2z"
                fill={active ? 'var(--accent)' : 'transparent'}
                stroke={active ? 'var(--accent)' : 'var(--line-strong)'}
                strokeWidth="1.4"
                strokeLinejoin="round" />
            </svg>
          </button>
        );
      })}
    </div>
  );
}

function Reviews() {
  const STORAGE = 'rdb_reviews_v1';
  const [reviews, setReviews] = useS2(() => {
    try {
      const saved = JSON.parse(localStorage.getItem(STORAGE) || '[]');
      return [...saved, ...SEED_REVIEWS];
    } catch { return SEED_REVIEWS; }
  });
  const [open, setOpen] = useS2(false);
  const [name, setName] = useS2('');
  const [role, setRole] = useS2('');
  const [rating, setRating] = useS2(5);
  const [body, setBody] = useS2('');
  const [submitted, setSubmitted] = useS2(false);

  const userReviews = reviews.filter(r => !SEED_REVIEWS.includes(r));
  const avg = (reviews.reduce((s, r) => s + r.rating, 0) / reviews.length).toFixed(1);

  const submit = (e) => {
    e.preventDefault();
    const r = {
      name: name.trim() || 'Anonymous',
      role: role.trim(),
      rating,
      date: new Date().toLocaleDateString('en-US', { month: 'short', day: '2-digit', year: 'numeric' }),
      body: body.trim(),
    };
    const next = [r, ...userReviews];
    localStorage.setItem(STORAGE, JSON.stringify(next));
    setReviews([...next, ...SEED_REVIEWS]);
    setSubmitted(true);
    setTimeout(() => {
      setOpen(false);
      setSubmitted(false);
      setName(''); setRole(''); setBody(''); setRating(5);
    }, 1400);
  };

  const inputStyle = {
    width: '100%', padding: '14px 16px', borderRadius: 10,
    border: '1px solid var(--line-strong)', background: 'var(--paper)',
    fontFamily: 'var(--sans)', fontSize: 15, color: 'var(--ink)', outline: 'none',
  };
  const labelStyle = { fontFamily: 'var(--mono)', fontSize: 11, letterSpacing: '.14em', textTransform: 'uppercase', color: 'var(--ink-mute)', display: 'block', marginBottom: 8 };

  return (
    <section id="reviews" style={{ background: 'var(--bg-soft)' }}>
      <div className="wrap">
        <div style={{ display: 'flex', justifyContent: 'space-between', flexWrap: 'wrap', gap: 24, alignItems: 'end', marginBottom: 48 }}>
          <div style={{ maxWidth: 640 }}>
            <span className="eyebrow">Reviews</span>
            <h2 style={{ marginTop: 16 }}>What people are <em>saying.</em></h2>
            <div style={{ display: 'flex', alignItems: 'center', gap: 16, marginTop: 20, flexWrap: 'wrap' }}>
              <Stars value={Math.round(avg)} size={22} />
              <span style={{ fontFamily: 'var(--display)', fontSize: 28 }}>{avg}</span>
              <span className="mono uppercase" style={{ color: 'var(--ink-mute)' }}>{reviews.length} review{reviews.length>1?'s':''}</span>
            </div>
          </div>
          <button className="btn" onClick={() => setOpen(true)}>
            Leave a review <span className="arr">→</span>
          </button>
        </div>

        <div className="grid cols-2">
          {reviews.slice(0, 6).map((r, i) => (
            <article key={i} style={{
              background: 'var(--paper)', border: '1px solid var(--line)',
              borderRadius: 'var(--radius-lg)', padding: 'clamp(24px, 3vw, 32px)',
              display: 'flex', flexDirection: 'column', gap: 16,
            }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 12 }}>
                <Stars value={r.rating} />
                <span className="mono" style={{ fontSize: 11, letterSpacing: '.1em', color: 'var(--ink-mute)' }}>{r.date}</span>
              </div>
              <p style={{ fontFamily: 'var(--display)', fontSize: 'clamp(18px, 1.8vw, 22px)', lineHeight: 1.4, color: 'var(--ink)' }}>
                "{r.body}"
              </p>
              <div style={{ borderTop: '1px solid var(--line)', paddingTop: 14, display: 'flex', alignItems: 'center', gap: 12, marginTop: 'auto' }}>
                <div style={{
                  width: 38, height: 38, borderRadius: 999,
                  background: 'var(--tan)', color: 'var(--ink)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  fontFamily: 'var(--display)', fontSize: 18,
                }}>{r.name.charAt(0)}</div>
                <div>
                  <div style={{ fontFamily: 'var(--display)', fontSize: 18, lineHeight: 1 }}>{r.name}</div>
                  {r.role && <div className="mono" style={{ fontSize: 11, letterSpacing: '.08em', color: 'var(--ink-mute)', marginTop: 4 }}>{r.role}</div>}
                </div>
              </div>
            </article>
          ))}
        </div>

        {reviews.length > 6 && (
          <div style={{ textAlign: 'center', marginTop: 28 }}>
            <span className="mono uppercase" style={{ color: 'var(--ink-mute)' }}>Showing 6 of {reviews.length}</span>
          </div>
        )}

        {/* Modal */}
        {open && (
          <div onClick={() => setOpen(false)} style={{
            position: 'fixed', inset: 0, background: 'rgba(20,12,4,0.55)',
            backdropFilter: 'blur(6px)', WebkitBackdropFilter: 'blur(6px)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            padding: 20, zIndex: 100,
          }}>
            <form onClick={e => e.stopPropagation()} onSubmit={submit} style={{
              background: 'var(--bg)', border: '1px solid var(--line-strong)',
              borderRadius: 'var(--radius-lg)', padding: 'clamp(24px, 3vw, 36px)',
              width: 'min(560px, 100%)', maxHeight: '90vh', overflowY: 'auto',
              display: 'flex', flexDirection: 'column', gap: 18,
            }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
                <div>
                  <span className="eyebrow">Leave a review</span>
                  <h3 style={{ marginTop: 12 }}>Tell us how it went.</h3>
                </div>
                <button type="button" onClick={() => setOpen(false)} style={{
                  background: 'transparent', border: '1px solid var(--line-strong)',
                  width: 36, height: 36, borderRadius: 999, fontSize: 18, color: 'var(--ink)',
                }}>×</button>
              </div>

              <div>
                <label style={labelStyle}>Rating</label>
                <Stars value={rating} onChange={setRating} interactive size={28} />
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                <div>
                  <label style={labelStyle}>Your name</label>
                  <input style={inputStyle} value={name} onChange={e => setName(e.target.value)} placeholder="Jordan R." />
                </div>
                <div>
                  <label style={labelStyle}>Role (optional)</label>
                  <input style={inputStyle} value={role} onChange={e => setRole(e.target.value)} placeholder="Swimmer, Parent, Coach…" />
                </div>
              </div>
              <div>
                <label style={labelStyle}>Your review</label>
                <textarea required style={{ ...inputStyle, minHeight: 120, fontFamily: 'var(--sans)' }}
                  value={body} onChange={e => setBody(e.target.value)}
                  placeholder="What did you eat it for? How did it taste? Did it keep you full?" />
              </div>
              <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 10, marginTop: 4 }}>
                <button type="button" onClick={() => setOpen(false)} className="btn ghost">Cancel</button>
                <button type="submit" className="btn">
                  {submitted ? 'Posted ✓' : 'Post review'} {!submitted && <span className="arr">→</span>}
                </button>
              </div>
            </form>
          </div>
        )}
      </div>
    </section>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
function FAQ() {
  const qs = [
    ['Are these gluten-free?', 'Yes. The only two ingredients are organic dates and organic cashews — naturally gluten-free, dairy-free, soy-free, and vegan.'],
    ['How long do they keep?', 'A long time — dates and cashews are both naturally shelf-stable. Several months at room temperature, even longer refrigerated. Slightly shorter than a typical store-bought energy bar (no preservatives), but you have plenty of time.'],
    ['Do you deliver?', 'Not yet — pickup only in Frisco, TX. Bulk team orders can sometimes be arranged for nearby drop-offs; ask.'],
    ['Cashew allergies?', 'These date balls are made in a kitchen with cashews. Please don\'t order if you have a tree-nut allergy.'],
  ];
  const [open, setOpen] = useS2(0);
  return (
    <section id="faq" className="tight">
      <div className="wrap">
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 2fr', gap: 'clamp(32px, 5vw, 80px)' }}>
          <div>
            <span className="eyebrow">FAQ</span>
            <h2 style={{ marginTop: 16 }}>Questions, <em>honestly.</em></h2>
          </div>
          <div>
            {qs.map(([q, a], i) => (
              <div key={i} style={{ borderTop: i === 0 ? '1px solid var(--line-strong)' : 'none', borderBottom: '1px solid var(--line-strong)' }}>
                <button onClick={() => setOpen(open === i ? -1 : i)}
                  style={{ width: '100%', display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 16,
                    padding: '24px 0', background: 'transparent', border: 0, textAlign: 'left',
                    fontFamily: 'var(--display)', fontSize: 'clamp(20px, 2vw, 28px)', color: 'var(--ink)' }}>
                  <span>{q}</span>
                  <span style={{ fontFamily: 'var(--mono)', fontSize: 18, color: 'var(--ink-mute)', transform: open === i ? 'rotate(45deg)' : 'none', transition: 'transform .2s' }}>+</span>
                </button>
                <div style={{
                  maxHeight: open === i ? 200 : 0, overflow: 'hidden',
                  transition: 'max-height .35s ease, opacity .25s',
                  opacity: open === i ? 1 : 0,
                }}>
                  <p style={{ paddingBottom: 24, color: 'var(--ink-soft)', fontSize: 16, maxWidth: 640 }}>{a}</p>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
function Footer() {
  return (
    <footer style={{ background: 'var(--ink)', color: 'var(--bg)', paddingTop: 80, paddingBottom: 40 }}>
      <div className="wrap">
        <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr 1fr 1fr', gap: 32 }}>
          <div>
            <LogoMark size={44} />
            <p style={{ marginTop: 18, color: 'color-mix(in oklab, var(--bg) 70%, transparent)', maxWidth: 280 }}>
              Two ingredients. Made by a swimmer. For everyone who needs to actually stay full.
            </p>
          </div>
          <div>
            <div className="uppercase mono" style={{ color: 'var(--tan)' }}>Shop</div>
            <ul style={{ listStyle: 'none', padding: 0, margin: '14px 0 0', display: 'flex', flexDirection: 'column', gap: 8 }}>
              <li><a href="#pricing">Pricing</a></li>
              <li><a href="#order">Order</a></li>
              <li><a href="#pickup">Pickup</a></li>
              <li><a href="#nutrition">Nutrition</a></li>
            </ul>
          </div>
          <div>
            <div className="uppercase mono" style={{ color: 'var(--tan)' }}>Story</div>
            <ul style={{ listStyle: 'none', padding: 0, margin: '14px 0 0', display: 'flex', flexDirection: 'column', gap: 8 }}>
              <li><a href="#founder">Founder</a></li>
              <li><a href="#reviews">Reviews</a></li>
              <li><a href="#why">Why date balls?</a></li>
              <li><a href="#faq">FAQ</a></li>
            </ul>
          </div>
          <div>
            <div className="uppercase mono" style={{ color: 'var(--tan)' }}>Contact</div>
            <ul style={{ listStyle: 'none', padding: 0, margin: '14px 0 0', display: 'flex', flexDirection: 'column', gap: 8 }}>
              <li>ela@realdateballs.com</li>
              <li>Frisco, TX 75034</li>
              <li>@realdateballs</li>
            </ul>
          </div>
        </div>
        <div className="rule" style={{ background: 'color-mix(in oklab, var(--bg) 18%, transparent)', margin: '48px 0 24px' }} />
        <div style={{ display: 'flex', justifyContent: 'space-between', fontFamily: 'var(--mono)', fontSize: 11, letterSpacing: '.14em', textTransform: 'uppercase', color: 'color-mix(in oklab, var(--bg) 55%, transparent)', flexWrap: 'wrap', gap: 12 }}>
          <span>© 2026 Real Date Balls</span>
          <span>Hand-formed in Frisco, TX ◆</span>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, { OrderForm, PickupMap, Payment, Founder, FAQ, Footer, Reviews });
