/* HelpMe — Booking flow: Date → Tickets → Payment → Confirm */

function Stepper({ step }) {
  const steps = ['Date', 'Tickets', 'Payment', 'Confirm'];
  return (
    <div style={{ display: 'flex', alignItems: 'center', padding: '0 4px' }}>
      {steps.map((s, i) => {
        const n = i + 1, done = n < step, active = n === step;
        return (
          <React.Fragment key={s}>
            <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 5 }}>
              <div style={{
                width: 34, height: 34, borderRadius: 999, display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontFamily: SANS, fontWeight: 800, fontSize: 14,
                background: done ? T.teal : active ? T.navy : '#e7ded0',
                color: done || active ? '#fff' : T.muted,
              }}>{done ? <Icon name="check" size={17} color="#fff" /> : n}</div>
              <span style={{ fontFamily: SANS, fontSize: 11.5, fontWeight: active ? 700 : 500, color: active ? T.navy : done ? T.teal : T.muted }}>{s}</span>
            </div>
            {i < 3 && <div style={{ flex: 1, height: 2, background: n < step ? T.teal : '#e7ded0', margin: '0 6px', marginBottom: 18 }} />}
          </React.Fragment>
        );
      })}
    </div>
  );
}

function Counter({ value, set, min = 0 }) {
  const btn = (dis) => ({ width: 32, height: 32, borderRadius: 9, border: `1px solid ${T.line}`, background: T.white, cursor: dis ? 'default' : 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', opacity: dis ? 0.4 : 1 });
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
      <button style={btn(value <= min)} onClick={() => value > min && set(value - 1)}><Icon name="minus" size={16} color={T.ink} /></button>
      <span style={{ fontFamily: SANS, fontWeight: 800, fontSize: 18, color: T.ink, minWidth: 16, textAlign: 'center' }}>{value}</span>
      <button style={btn(false)} onClick={() => set(value + 1)}><Icon name="plus" size={16} color={T.ink} /></button>
    </div>
  );
}

function Radio({ on }) {
  return <div style={{ width: 22, height: 22, borderRadius: 999, border: `2px solid ${on ? T.navy : T.line}`, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
    {on && <div style={{ width: 11, height: 11, borderRadius: 999, background: T.navy }} />}
  </div>;
}

function QR({ size = 150 }) {
  const cells = 21;
  const pat = React.useMemo(() => Array.from({ length: cells * cells }, (_, i) => {
    const x = i % cells, y = Math.floor(i / cells);
    const finder = (cx, cy) => x >= cx && x < cx + 7 && y >= cy && y < cy + 7;
    if (finder(0, 0) || finder(cells - 7, 0) || finder(0, cells - 7)) {
      const lx = x % (cells - 7 || 1);
      // draw finder rings
      const inRing = (cx, cy) => {
        const rx = x - cx, ry = y - cy;
        const edge = rx === 0 || rx === 6 || ry === 0 || ry === 6;
        const core = rx >= 2 && rx <= 4 && ry >= 2 && ry <= 4;
        return edge || core;
      };
      if (finder(0, 0)) return inRing(0, 0);
      if (finder(cells - 7, 0)) return inRing(cells - 7, 0);
      if (finder(0, cells - 7)) return inRing(0, cells - 7);
    }
    return (Math.sin(i * 12.9898) * 43758.5453 % 1) > 0.45;
  }), []);
  return (
    <div style={{ width: size, height: size, display: 'grid', gridTemplateColumns: `repeat(${cells},1fr)`, background: '#fff', padding: 6, borderRadius: 10, boxSizing: 'content-box' }}>
      {pat.map((on, i) => <div key={i} style={{ background: on ? T.navy : 'transparent' }} />)}
    </div>
  );
}

function BookingFlow({ place, onBack, onDone, lang }) {
  const p = place || HM.PLACES[0];
  const [step, setStep] = React.useState(1);
  const [dateIdx, setDateIdx] = React.useState(2);
  const [pass, setPass] = React.useState('1-day');
  const [adults, setAdults] = React.useState(2);
  const [kids, setKids] = React.useState(1);
  const [pay, setPay] = React.useState('card');

  const dates = ['Jun 10', 'Jun 11', 'Jun 12', 'Jun 13', 'Jun 14', 'Jun 15', 'Jun 16'];
  const days = ['Wed', 'Thu', 'Fri', 'Sat', 'Sun', 'Mon', 'Tue'];
  const unit = pass === '1-day' ? p.price : 62;
  const sub = adults * unit;
  const fee = 2.5;
  const total = sub + fee;

  const next = () => step < 4 ? setStep(step + 1) : onDone({
    id: 'b' + Date.now(), place: p.name, sub: `${pass === '1-day' ? '1-Day Pass' : '3-Day Pass'} · ${adults} Adult${adults > 1 ? 's' : ''}${kids ? `, ${kids} Child` : ''}`,
    date: dates[dateIdx] + ', 2026', code: 'HM-' + p.name.slice(0, 2).toUpperCase() + '-' + Math.floor(1000 + Math.random() * 9000), status: 'upcoming', total, img: p.img, grad: p.grad,
  });

  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: T.cream }}>
      {/* header */}
      <div style={{ background: `linear-gradient(120deg,${T.navy2},${T.tealDk})`, paddingBottom: 18, borderBottomLeftRadius: 26, borderBottomRightRadius: 26, flexShrink: 0 }}>
        <StatusBar light />
        <div style={{ padding: '4px 22px 0' }}>
          <button onClick={step > 1 ? () => setStep(step - 1) : onBack} style={{ ...iconBtn, marginBottom: 12 }}><Icon name="arrow-left" size={22} color="#fff" /></button>
          <h1 style={{ fontFamily: DISP, fontWeight: 800, fontSize: 30, color: '#fff', margin: 0 }}>{step === 4 ? 'Confirmed!' : 'Book Tickets'}</h1>
          <div style={{ fontFamily: SANS, fontSize: 14.5, color: 'rgba(255,255,255,0.7)', marginTop: 2 }}>{p.name} · {p.location}</div>
        </div>
      </div>

      <div style={{ flex: 1, overflowY: 'auto' }}>
        <div style={{ padding: '20px 22px 130px' }}>
          {step < 4 && <div style={{ marginBottom: 22 }}><Stepper step={step} /></div>}

          {step === 1 && <>
            <h3 style={hd}>Choose your visit date</h3>
            <div style={{ display: 'flex', gap: 9, overflowX: 'auto', margin: '0 -22px', padding: '4px 22px 8px' }}>
              {dates.map((d, i) => (
                <button key={d} onClick={() => setDateIdx(i)} style={{
                  flexShrink: 0, width: 60, padding: '12px 0', borderRadius: 14, cursor: 'pointer',
                  border: `1px solid ${dateIdx === i ? T.navy : T.line}`, background: dateIdx === i ? T.navy : T.white,
                  display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 3,
                }}>
                  <span style={{ fontFamily: SANS, fontSize: 12, fontWeight: 600, color: dateIdx === i ? 'rgba(255,255,255,0.7)' : T.muted }}>{days[i]}</span>
                  <span style={{ fontFamily: SANS, fontSize: 15, fontWeight: 800, color: dateIdx === i ? '#fff' : T.ink }}>{d.split(' ')[1]}</span>
                </button>
              ))}
            </div>
            <h3 style={hd}>Entry window</h3>
            {[['Sunrise', '5:00 – 7:00 AM', 'Best light & reflections'], ['Morning', '7:00 – 11:00 AM', 'Cooler, fewer crowds'], ['Afternoon', '2:00 – 6:00 PM', 'Golden hour & sunset']].map((w, i) => (
              <div key={w[0]} onClick={() => setDateIdx(dateIdx)} style={{ display: 'flex', alignItems: 'center', gap: 13, background: T.white, border: `1px solid ${i === 0 ? T.navy : T.line}`, borderRadius: 14, padding: 14, marginBottom: 10 }}>
                <Radio on={i === 0} />
                <div style={{ flex: 1 }}>
                  <div style={{ fontFamily: SANS, fontWeight: 700, fontSize: 15.5, color: T.ink }}>{w[0]} <span style={{ color: T.muted, fontWeight: 600, fontSize: 13.5 }}>· {w[1]}</span></div>
                  <div style={{ fontFamily: SANS, fontSize: 13, color: T.muted }}>{w[2]}</div>
                </div>
              </div>
            ))}
          </>}

          {step === 2 && <>
            <div style={{ display: 'flex', gap: 11, marginBottom: 8 }}>
              <SummaryCard label="Visit Date" icon="calendar" value={dates[dateIdx]} />
              <SummaryCard label="Duration" icon="clock" value={pass === '1-day' ? '1-day pass' : '3-day pass'} />
            </div>
            <h3 style={hd}>Select ticket type</h3>
            {[['1-day', '1-Day Pass', 'Angkor Wat + Ta Prohm + Bayon', 37], ['3-day', '3-Day Pass', 'Full complex access · valid 10 days', 62]].map(o => (
              <div key={o[0]} onClick={() => setPass(o[0])} style={{ display: 'flex', alignItems: 'center', gap: 13, background: pass === o[0] ? '#eef2f6' : T.white, border: `1.5px solid ${pass === o[0] ? T.navy : T.line}`, borderRadius: 14, padding: 15, marginBottom: 11, cursor: 'pointer' }}>
                <Radio on={pass === o[0]} />
                <div style={{ flex: 1 }}>
                  <div style={{ fontFamily: SANS, fontWeight: 700, fontSize: 16, color: T.ink }}>{o[1]}</div>
                  <div style={{ fontFamily: SANS, fontSize: 13, color: T.muted }}>{o[2]}</div>
                </div>
                <div style={{ fontFamily: SANS, fontWeight: 800, fontSize: 19, color: T.ink }}>${o[3]}</div>
              </div>
            ))}
            <h3 style={hd}>Number of visitors</h3>
            <div style={{ background: T.white, border: `1px solid ${T.line}`, borderRadius: 14, padding: '6px 16px' }}>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '12px 0' }}>
                <div><div style={{ fontFamily: SANS, fontWeight: 700, fontSize: 15.5, color: T.ink }}>Adult</div><div style={{ fontFamily: SANS, fontSize: 12.5, color: T.muted }}>Age 12+</div></div>
                <Counter value={adults} set={setAdults} min={1} />
              </div>
              <div style={{ height: 1, background: T.line }} />
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '12px 0' }}>
                <div><div style={{ fontFamily: SANS, fontWeight: 700, fontSize: 15.5, color: T.ink }}>Child</div><div style={{ fontFamily: SANS, fontSize: 12.5, color: T.muted }}>Age 4–11 · Free</div></div>
                <Counter value={kids} set={setKids} />
              </div>
            </div>
            <VerifiedNote />
            <PriceSummary rows={[[`${adults}× Adult (${pass})`, `$${sub.toFixed(2)}`], kids ? [`${kids}× Child`, 'Free'] : null, ['Service fee', `$${fee.toFixed(2)}`]]} total={total} />
          </>}

          {step === 3 && <>
            <h3 style={hd}>Payment method</h3>
            {[['card', 'Credit / Debit card', '•••• 4242', 'mail'], ['applepay', 'Apple Pay', 'Fast & secure', 'phone'], ['paypal', 'PayPal', 'lymeng.pen@dojology.com', 'globe']].map(m => (
              <div key={m[0]} onClick={() => setPay(m[0])} style={{ display: 'flex', alignItems: 'center', gap: 13, background: pay === m[0] ? '#eef2f6' : T.white, border: `1.5px solid ${pay === m[0] ? T.navy : T.line}`, borderRadius: 14, padding: 15, marginBottom: 11, cursor: 'pointer' }}>
                <div style={{ width: 40, height: 40, borderRadius: 11, background: T.cream, display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name={m[3]} size={20} color={T.navy} /></div>
                <div style={{ flex: 1 }}><div style={{ fontFamily: SANS, fontWeight: 700, fontSize: 15.5, color: T.ink }}>{m[1]}</div><div style={{ fontFamily: SANS, fontSize: 13, color: T.muted }}>{m[2]}</div></div>
                <Radio on={pay === m[0]} />
              </div>
            ))}
            {pay === 'card' && (
              <div style={{ background: T.white, border: `1px solid ${T.line}`, borderRadius: 14, padding: 16, marginTop: 4 }}>
                <MiniField label="Card number" value="4242 4242 4242 4242" />
                <div style={{ display: 'flex', gap: 12 }}>
                  <div style={{ flex: 1 }}><MiniField label="Expiry" value="08 / 28" /></div>
                  <div style={{ flex: 1 }}><MiniField label="CVC" value="•••" /></div>
                </div>
              </div>
            )}
            <VerifiedNote />
            <PriceSummary rows={[['Subtotal', `$${sub.toFixed(2)}`], ['Service fee', `$${fee.toFixed(2)}`]]} total={total} />
          </>}

          {step === 4 && (
            <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', textAlign: 'center', paddingTop: 8 }}>
              <div style={{ width: 70, height: 70, borderRadius: 999, background: T.tealBg, display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: 16 }}>
                <div style={{ width: 50, height: 50, borderRadius: 999, background: T.teal, display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name="check" size={28} color="#fff" /></div>
              </div>
              <h2 style={{ fontFamily: DISP, fontWeight: 800, fontSize: 26, color: T.ink, margin: 0, whiteSpace: 'nowrap' }}>You're all set!</h2>
              <p style={{ fontFamily: SANS, fontSize: 14.5, color: T.body, marginTop: 6, maxWidth: 280 }}>Show this QR at the gate. We've added it to your Bookings and sent a copy to your email.</p>
              <div style={{ background: T.white, border: `1px solid ${T.line}`, borderRadius: 20, padding: 22, marginTop: 18, width: '100%', boxSizing: 'border-box', display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
                <QR />
                <div style={{ fontFamily: MONO, fontSize: 14, color: T.ink, marginTop: 14, letterSpacing: 1, whiteSpace: 'nowrap' }}>HM-{p.name.slice(0, 2).toUpperCase()}-8842</div>
                <div style={{ width: '100%', height: 1, background: T.line, margin: '16px 0' }} />
                <div style={{ width: '100%', display: 'flex', justifyContent: 'space-between', fontFamily: SANS, fontSize: 14, whiteSpace: 'nowrap', gap: 12 }}>
                  <span style={{ color: T.muted }}>{p.name}</span><span style={{ color: T.ink, fontWeight: 700 }}>{dates[dateIdx]}, 2026</span>
                </div>
                <div style={{ width: '100%', display: 'flex', justifyContent: 'space-between', fontFamily: SANS, fontSize: 14, marginTop: 8, whiteSpace: 'nowrap', gap: 12 }}>
                  <span style={{ color: T.muted }}>{adults} Adult{adults > 1 ? 's' : ''}{kids ? `, ${kids} Child` : ''}</span><span style={{ color: T.ink, fontWeight: 700 }}>${total.toFixed(2)}</span>
                </div>
              </div>
              <div style={{ display: 'flex', gap: 10, alignItems: 'center', marginTop: 16, color: T.teal }}>
                <Icon name="shield-check" size={17} color={T.teal} />
                <span style={{ fontFamily: SANS, fontSize: 13, fontWeight: 600 }}>Verified APSARA Authority seller · Protected by Scam Shield</span>
              </div>
            </div>
          )}
        </div>
      </div>

      <div style={{ flexShrink: 0, padding: '14px 22px 20px', background: T.cream, borderTop: `1px solid ${T.line}` }}>
        <PrimaryBtn onClick={next} icon={step < 4 ? 'arrow-right' : undefined}>
          {step === 1 ? 'Continue' : step === 2 ? 'Continue to payment' : step === 3 ? `Pay $${total.toFixed(2)}` : 'View my bookings'}
        </PrimaryBtn>
      </div>
    </div>
  );
}

const hd = { fontFamily: SANS, fontWeight: 800, fontSize: 17, color: T.ink, margin: '18px 0 12px' };
function SummaryCard({ label, icon, value }) {
  return <div style={{ flex: 1, background: T.white, border: `1px solid ${T.line}`, borderRadius: 14, padding: '11px 14px' }}>
    <div style={{ fontFamily: SANS, fontSize: 12, color: T.muted, fontWeight: 600 }}>{label}</div>
    <div style={{ display: 'flex', alignItems: 'center', gap: 7, marginTop: 4 }}><Icon name={icon} size={17} color={T.teal} /><span style={{ fontFamily: SANS, fontWeight: 700, fontSize: 15, color: T.ink, whiteSpace: 'nowrap' }}>{value}</span></div>
  </div>;
}
function MiniField({ label, value }) {
  return <div style={{ marginBottom: 12 }}>
    <div style={{ fontFamily: SANS, fontSize: 12.5, color: T.muted, fontWeight: 600, marginBottom: 5 }}>{label}</div>
    <div style={{ border: `1px solid ${T.line}`, borderRadius: 10, padding: '11px 13px', fontFamily: MONO, fontSize: 14.5, color: T.ink, background: T.cream }}>{value}</div>
  </div>;
}
function VerifiedNote() {
  return <div style={{ display: 'flex', gap: 11, alignItems: 'flex-start', background: T.warnBg, border: `1px solid ${T.warn}55`, borderRadius: 14, padding: 14, marginTop: 16 }}>
    <Icon name="shield-check" size={20} color={T.goldDk} style={{ flexShrink: 0, marginTop: 1 }} />
    <span style={{ fontFamily: SANS, fontSize: 13.5, lineHeight: 1.45, color: '#6b531a' }}><strong>Verified ticket seller.</strong> GoWithMe uses only certified APSARA Authority partners — you're protected against ticket scams.</span>
  </div>;
}
function PriceSummary({ rows, total }) {
  return <div style={{ background: T.white, border: `1px solid ${T.line}`, borderRadius: 16, padding: 16, marginTop: 16 }}>
    {rows.filter(Boolean).map((r, i) => (
      <div key={i} style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 10, fontFamily: SANS, fontSize: 14.5, color: T.body }}>
        <span>{r[0]}</span><span style={{ fontWeight: r[1] === 'Free' ? 800 : 600, color: r[1] === 'Free' ? T.teal : T.ink }}>{r[1]}</span>
      </div>
    ))}
    <div style={{ height: 1, background: T.line, margin: '4px 0 12px' }} />
    <div style={{ display: 'flex', justifyContent: 'space-between', fontFamily: SANS }}>
      <span style={{ fontWeight: 800, fontSize: 16, color: T.ink }}>Total</span>
      <span style={{ fontWeight: 800, fontSize: 20, color: T.ink }}>${total.toFixed(2)}</span>
    </div>
  </div>;
}

Object.assign(window, { BookingFlow });
