/* ============================================================
   WorkStay — Booking Flow (multi-step)
   exports: BookingFlow
   ============================================================ */
const { useState: useStateBk } = React;

const STEPS = ['Dates', 'Work needs', 'Details', 'Confirm'];

function BookingFlow({ go, params = {} }) {
  const { PROPERTIES, OPERATORS } = window.WS_DATA;
  const p = PROPERTIES.find(x => x.id === params.id) || PROPERTIES[0];
  const op = OPERATORS[p.operator];
  const [step, setStep] = useStateBk(0);
  const [months, setMonths] = useStateBk(3);
  const [needs, setNeeds] = useStateBk(['Wired desk', 'Quiet after 8pm']);
  const [done, setDone] = useStateBk(false);

  const total = p.price * months + 240;
  const next = () => { if (step < 3) setStep(step + 1); else setDone(true); };
  const back = () => { if (step > 0) setStep(step - 1); else go('property', { id: p.id }); };
  const toggleNeed = n => setNeeds(prev => prev.includes(n) ? prev.filter(x => x !== n) : [...prev, n]);

  if (done) return <BookingConfirmed p={p} op={op} months={months} total={total} go={go} />;

  return (
    <main style={{ minHeight: '100vh', display: 'grid', gridTemplateColumns: '1.4fr 1fr' }} className="ws-hero-split">
      {/* left: form */}
      <div className="ws-book-form" style={{ display: 'flex', flexDirection: 'column', padding: 'clamp(28px,5vw,72px)', paddingTop: 110 }}>
        {/* mobile-only compact summary */}
        <div className="ws-book-mobile-summary" style={{ display: 'none', marginBottom: 24, padding: '14px 16px', borderRadius: 'var(--r-md)', background: 'var(--surface)', border: '1px solid var(--line)' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12 }}>
            <div style={{ minWidth: 0 }}>
              <div style={{ fontSize: 11, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--text-faint)' }}>{p.collection}</div>
              <div className="serif" style={{ fontSize: 18, marginTop: 2, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{p.name}</div>
              <div style={{ fontSize: 12, color: 'var(--text-dim)', marginTop: 2 }}>{p.city}</div>
            </div>
            <div style={{ textAlign: 'right', flexShrink: 0 }}>
              <div style={{ fontSize: 11, color: 'var(--text-faint)' }}>Total</div>
              <div style={{ fontFamily: 'var(--serif)', fontSize: 20 }}>${total.toLocaleString()}</div>
            </div>
          </div>
        </div>
        {/* progress */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 50 }}>
          {STEPS.map((s, i) => (
            <React.Fragment key={s}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 9, opacity: i <= step ? 1 : 0.4, transition: 'opacity .3s' }}>
                <span style={{ width: 26, height: 26, borderRadius: 999, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 12,
                  background: i < step ? 'var(--violet)' : (i === step ? 'rgba(124,108,240,0.18)' : 'var(--surface-2)'),
                  border: `1px solid ${i <= step ? 'var(--violet)' : 'var(--line)'}`, color: i < step ? '#fff' : (i === step ? 'var(--violet-soft)' : 'var(--text-faint)') }}>
                  {i < step ? <Icon name="check" size={13} /> : i + 1}
                </span>
                <span style={{ fontSize: 13, color: i === step ? 'var(--text)' : 'var(--text-faint)' }} className="ws-stepname ws-book-stepname">{s}</span>
              </div>
              {i < STEPS.length - 1 && <span style={{ flex: 1, height: 1, background: i < step ? 'var(--violet)' : 'var(--line)', transition: 'background .3s' }} />}
            </React.Fragment>
          ))}
        </div>

        <div key={step} className="rise" style={{ flex: 1 }}>
          {step === 0 && <StepDates p={p} months={months} setMonths={setMonths} />}
          {step === 1 && <StepNeeds needs={needs} toggleNeed={toggleNeed} />}
          {step === 2 && <StepDetails />}
          {step === 3 && <StepConfirm p={p} op={op} months={months} needs={needs} total={total} />}
        </div>

        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 40, paddingTop: 24, borderTop: '1px solid var(--line)' }}>
          <Btn variant="ghost" onClick={back}>{step === 0 ? 'Back to stay' : 'Back'}</Btn>
          <Btn size="lg" icon={step === 3 ? 'check' : 'arrow'} onClick={next}>{step === 3 ? 'Confirm & reserve' : 'Continue'}</Btn>
        </div>
      </div>

      {/* right: cinematic summary rail */}
      <aside className="ws-book-aside" style={{ position: 'relative', overflow: 'hidden' }}>
        <Scene variant={p.scene} style={{ position: 'absolute', inset: 0 }} />
        <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(180deg, rgba(10,10,12,0.55), rgba(10,10,12,0.85))' }} />
        <div style={{ position: 'relative', padding: 'clamp(28px,4vw,48px)', paddingTop: 130, height: '100%', display: 'flex', flexDirection: 'column' }}>
          <div className="glass" style={{ borderRadius: 'var(--r-xl)', padding: 26, boxShadow: 'var(--shadow-soft)' }}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <div>
                <div style={{ fontSize: 12.5, color: 'var(--text-faint)' }}>{p.collection}</div>
                <div className="serif" style={{ fontSize: 26, marginTop: 2 }}>{p.name}</div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 7, fontSize: 13.5, color: 'var(--text-dim)', marginTop: 6 }}><Icon name="pin" size={14} /> {p.city}, {p.country}</div>
              </div>
              <WorkScore value={p.workScore} size={78} stroke={5} label="Work" />
            </div>
            <div style={{ marginTop: 22, paddingTop: 18, borderTop: '1px solid var(--line)', display: 'flex', flexDirection: 'column', gap: 11 }}>
              {[['$' + p.price.toLocaleString() + ' × ' + months + ' mo', '$' + (p.price * months).toLocaleString()], ['Operator service', '$240'], ['Workspace setup', 'Included']].map(([l, v]) => (
                <div key={l} style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13.5, color: 'var(--text-dim)' }}><span>{l}</span><span>{v}</span></div>
              ))}
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', paddingTop: 11, borderTop: '1px solid var(--line)' }}>
                <span style={{ fontSize: 15 }}>Total</span><span style={{ fontFamily: 'var(--serif)', fontSize: 26 }}>${total.toLocaleString()}</span>
              </div>
            </div>
          </div>
          <div style={{ marginTop: 'auto', display: 'flex', alignItems: 'center', gap: 11, fontSize: 13, color: 'var(--text-dim)', paddingTop: 24 }}>
            <Icon name="shield" size={16} style={{ color: 'var(--violet-soft)' }} /> Free to hold · full refund within 48h
          </div>
        </div>
      </aside>
    </main>
  );
}

function StepHead({ eyebrow, title }) {
  return <div style={{ marginBottom: 34 }}>
    <div className="eyebrow" style={{ marginBottom: 14 }}>{eyebrow}</div>
    <h2 className="d3" style={{ margin: 0 }}>{title}</h2>
  </div>;
}

function StepDates({ p, months, setMonths }) {
  return (
    <div>
      <StepHead eyebrow="Step 1 — When" title="How long will you stay?" />
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14, marginBottom: 30 }}>
        {[['Move in', 'Apr 12, 2026'], ['Move out', `Jul 12, 2026`]].map(([l, v]) => (
          <div key={l} style={{ padding: '18px 20px', borderRadius: 'var(--r-md)', background: 'var(--surface)', border: '1px solid var(--line)' }}>
            <div style={{ fontSize: 11, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--text-faint)', marginBottom: 8 }}>{l}</div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, fontSize: 17 }}><Icon name="cal" size={17} style={{ color: 'var(--violet-soft)' }} /> {v}</div>
          </div>
        ))}
      </div>
      <div style={{ padding: '24px 22px', borderRadius: 'var(--r-lg)', background: 'var(--surface)', border: '1px solid var(--line)' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 18 }}>
          <span style={{ fontSize: 15 }}>Duration</span>
          <span><span style={{ fontFamily: 'var(--serif)', fontSize: 30 }}>{months}</span> <span style={{ color: 'var(--text-faint)' }}>months</span></span>
        </div>
        <input type="range" min="1" max="12" value={months} onChange={e => setMonths(+e.target.value)} className="ws-range" style={{ width: '100%' }} />
        <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, color: 'var(--text-faint)', marginTop: 6 }}><span>1 mo</span><span>Long-stay 12 mo</span></div>
        {months >= 3 && <div style={{ marginTop: 18, display: 'flex', alignItems: 'center', gap: 9, fontSize: 13.5, color: 'var(--good)' }}><Icon name="check" size={15} /> Long-stay rate applied — 12% off monthly</div>}
      </div>
    </div>
  );
}

function StepNeeds({ needs, toggleNeed }) {
  const opts = [
    { n: 'Wired desk', i: 'desk' }, { n: 'Quiet after 8pm', i: 'quiet' }, { n: 'Video-call room', i: 'video' },
    { n: '1 Gbps fiber', i: 'wifi' }, { n: 'Standing desk', i: 'ergo' }, { n: 'Power backup', i: 'power' },
    { n: 'Great light', i: 'light' }, { n: 'Espresso bar', i: 'coffee' },
  ];
  return (
    <div>
      <StepHead eyebrow="Step 2 — What you need" title="Tune the workspace." />
      <p style={{ fontSize: 15, color: 'var(--text-dim)', marginTop: -22, marginBottom: 26 }}>We’ll match the setup and flag anything the Operator should prep before you arrive.</p>
      <div className="ws-book-needs" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
        {opts.map(o => {
          const on = needs.includes(o.n);
          return (
            <button key={o.n} onClick={() => toggleNeed(o.n)} style={{ display: 'flex', alignItems: 'center', gap: 13, padding: '16px 18px', borderRadius: 'var(--r-md)',
              background: on ? 'rgba(124,108,240,0.12)' : 'var(--surface)', border: `1px solid ${on ? 'var(--violet)' : 'var(--line)'}`, transition: 'all .25s', textAlign: 'left' }}>
              <span style={{ width: 38, height: 38, borderRadius: 11, background: on ? 'var(--violet)' : 'var(--surface-2)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: on ? '#fff' : 'var(--violet-soft)', transition: 'all .25s' }}><Icon name={o.i} size={17} /></span>
              <span style={{ fontSize: 14.5, flex: 1 }}>{o.n}</span>
              <span style={{ width: 20, height: 20, borderRadius: 999, border: `1.5px solid ${on ? 'var(--violet)' : 'var(--line-2)'}`, background: on ? 'var(--violet)' : 'transparent', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff' }}>{on && <Icon name="check" size={12} />}</span>
            </button>
          );
        })}
      </div>
    </div>
  );
}

function Field({ label, placeholder, span }) {
  return (
    <label style={{ display: 'flex', flexDirection: 'column', gap: 9, gridColumn: span ? '1 / -1' : 'auto' }}>
      <span style={{ fontSize: 12.5, color: 'var(--text-dim)' }}>{label}</span>
      <input placeholder={placeholder} className="ws-input" />
    </label>
  );
}

function StepDetails() {
  return (
    <div>
      <StepHead eyebrow="Step 3 — Who" title="Your details." />
      <div className="ws-book-fields" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
        <Field label="First name" placeholder="Aarav" />
        <Field label="Last name" placeholder="Sharma" />
        <Field label="Email" placeholder="aarav@studio.com" span />
        <Field label="What are you working on?" placeholder="Building a design tool" span />
      </div>
      <div style={{ marginTop: 26 }}>
        <div style={{ fontSize: 12.5, color: 'var(--text-dim)', marginBottom: 12 }}>Payment</div>
        <div className="ws-book-payrow" style={{ padding: '18px 20px', borderRadius: 'var(--r-md)', background: 'var(--surface)', border: '1px solid var(--line)', display: 'flex', alignItems: 'center', gap: 14 }}>
          <span style={{ width: 42, height: 30, borderRadius: 6, background: 'linear-gradient(135deg, var(--violet), var(--violet-deep))', flexShrink: 0 }} />
          <input placeholder="Card number" className="ws-input" style={{ border: 'none', background: 'none', flex: 1, padding: 0 }} />
          <input placeholder="MM / YY" className="ws-input" style={{ border: 'none', background: 'none', width: 80, padding: 0 }} />
          <input placeholder="CVC" className="ws-input" style={{ border: 'none', background: 'none', width: 56, padding: 0 }} />
        </div>
        <div style={{ marginTop: 14, fontSize: 12.5, color: 'var(--text-faint)', display: 'flex', alignItems: 'center', gap: 8 }}><Icon name="shield" size={14} /> Encrypted · you won’t be charged until the Operator confirms.</div>
      </div>
    </div>
  );
}

function StepConfirm({ p, op, months, needs, total }) {
  return (
    <div>
      <StepHead eyebrow="Step 4 — Review" title="One last look." />
      <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        <SummaryRow label="Stay" value={`${p.name} · ${p.city}`} />
        <SummaryRow label="Operator" value={op.name} />
        <SummaryRow label="Duration" value={`${months} months · Apr 12 → ${months === 3 ? 'Jul 12' : 'long stay'}`} />
        <SummaryRow label="Workspace" value={needs.join(' · ') || 'Standard setup'} />
        <div style={{ padding: '20px 22px', borderRadius: 'var(--r-lg)', background: 'rgba(124,108,240,0.1)', border: '1px solid var(--violet)', display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
          <span style={{ fontSize: 15 }}>Total due at confirmation</span>
          <span style={{ fontFamily: 'var(--serif)', fontSize: 32 }}>${total.toLocaleString()}</span>
        </div>
      </div>
    </div>
  );
}

function SummaryRow({ label, value }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', gap: 20, padding: '16px 0', borderBottom: '1px solid var(--line)' }}>
      <span style={{ fontSize: 13.5, color: 'var(--text-faint)' }}>{label}</span>
      <span style={{ fontSize: 14.5, textAlign: 'right' }}>{value}</span>
    </div>
  );
}

function BookingConfirmed({ p, op, months, total, go }) {
  return (
    <main style={{ position: 'relative', minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center', overflow: 'hidden', textAlign: 'center', padding: 'var(--gutter)' }}>
      <Scene variant={p.scene} style={{ position: 'absolute', inset: 0 }} />
      <div style={{ position: 'absolute', inset: 0, background: 'radial-gradient(60% 70% at 50% 40%, rgba(10,10,12,0.5), rgba(10,10,12,0.92))' }} />
      <div className="rise" style={{ position: 'relative', maxWidth: 540 }}>
        <span style={{ width: 76, height: 76, borderRadius: 999, background: 'var(--violet)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', boxShadow: '0 0 50px -6px var(--violet-glow)', marginBottom: 30 }}><Icon name="check" size={36} style={{ color: '#fff' }} /></span>
        <h1 className="d2" style={{ margin: 0 }}>You’re in.</h1>
        <p style={{ fontSize: 18, lineHeight: 1.6, color: 'var(--text-dim)', marginTop: 20 }}>
          {op.name} is preparing <span style={{ color: 'var(--text)' }}>{p.name}</span> for your {months}-month stay. You’ll get a confirmation and workspace checklist by email.
        </p>
        <div className="glass" style={{ marginTop: 30, padding: 22, borderRadius: 'var(--r-lg)', display: 'flex', justifyContent: 'space-between', alignItems: 'center', textAlign: 'left' }}>
          <div><div style={{ fontSize: 12.5, color: 'var(--text-faint)' }}>Confirmation</div><div style={{ fontFamily: 'var(--serif)', fontSize: 22, marginTop: 2 }}>WS-{p.id.slice(0, 3).toUpperCase()}-2026</div></div>
          <div style={{ textAlign: 'right' }}><div style={{ fontSize: 12.5, color: 'var(--text-faint)' }}>Total</div><div style={{ fontFamily: 'var(--serif)', fontSize: 22, marginTop: 2 }}>${total.toLocaleString()}</div></div>
        </div>
        <div style={{ marginTop: 30, display: 'flex', gap: 12, justifyContent: 'center', flexWrap: 'wrap' }}>
          <Btn size="lg" onClick={() => go('home')}>Back to home</Btn>
          <Btn size="lg" variant="line" icon="arrow" onClick={() => go('explore')}>Explore more stays</Btn>
        </div>
      </div>
    </main>
  );
}

Object.assign(window, { BookingFlow });
