/* ============================================================
   Tectus — Book Now: multi-step booking wizard (Details → Team →
   Intel → Review). Replaces the single-page form for #/book-now.
   Uses Tectus DS primitives; dark, gold-accent, no external deps.
   ============================================================ */
const { Button: BwButton, Field: BwField, Input: BwInput, Select: BwSelect, Textarea: BwTextarea, SegmentedControl: BwSeg, Eyebrow: BwEyebrow, ProgressSteps: BwProgress } = window.TectusDesignSystem_c42b34;

const BW_SERVICES = [
  'Executive & VIP protection', 'Event security', 'Mobile patrol', 'Retail security',
  'Alarm response', 'Corporate security', 'Fire watch',
];
const BW_STEPS = ['Details', 'Team', 'Intel', 'Review'];

function BwStepCard({ children }) {
  return (
    <div style={{ background: 'var(--color-surface)', border: '1px solid var(--color-border)', borderRadius: 'var(--radius-xl)', padding: 32 }}>
      {children}
    </div>
  );
}
function BwSectionTitle({ children, sub }) {
  return (
    <div style={{ marginBottom: 22 }}>
      <h2 style={{ fontFamily: 'var(--font-display)', fontSize: 20, fontWeight: 600, margin: '0 0 6px' }}>{children}</h2>
      {sub && <p style={{ fontSize: 13.5, color: 'var(--color-text-faint)', margin: 0, lineHeight: 1.5 }}>{sub}</p>}
    </div>
  );
}
function BwStepper({ value, onChange, min = 1, max = 20 }) {
  return (
    <div style={{ display: 'inline-flex', alignItems: 'center', gap: 14, background: 'var(--color-bg)', border: '1px solid var(--color-border)', borderRadius: 'var(--radius-md)', padding: '6px 10px' }}>
      <button type="button" onClick={() => onChange(Math.max(min, value - 1))} style={{ width: 30, height: 30, borderRadius: 'var(--radius-sm)', border: '1px solid var(--color-border)', background: 'var(--color-surface-2)', color: 'var(--color-text)', cursor: 'pointer', fontSize: 16, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>–</button>
      <span style={{ fontFamily: 'var(--font-mono)', fontSize: 17, fontWeight: 700, minWidth: 24, textAlign: 'center' }}>{value}</span>
      <button type="button" onClick={() => onChange(Math.min(max, value + 1))} style={{ width: 30, height: 30, borderRadius: 'var(--radius-sm)', border: '1px solid var(--color-border)', background: 'var(--color-surface-2)', color: 'var(--color-text)', cursor: 'pointer', fontSize: 16, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>+</button>
    </div>
  );
}
function BwReviewRow({ label, value }) {
  if (!value) return null;
  return (
    <div>
      <div style={{ fontSize: 10.5, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--color-text-faint)', fontWeight: 700, marginBottom: 4 }}>{label}</div>
      <div style={{ fontSize: 14, color: 'var(--color-text)', lineHeight: 1.5, whiteSpace: 'pre-line' }}>{value}</div>
    </div>
  );
}

function BookingWizard() {
  const [step, setStep] = useState(0);
  const [sent, setSent] = useState(false);
  const [f, setF] = useState({
    assignmentName: '', service: BW_SERVICES[1], location: '', date: '', time: '',
    armed: 'Unarmed', urgency: 'Scheduled',
    teamSize: 2, appearance: 'Suit',
    situation: '', concerns: '', notes: '',
    fullName: '', email: '', phone: '', company: '',
  });
  const set = (patch) => setF((p) => ({ ...p, ...patch }));

  const canNext = () => {
    if (step === 0) return f.service && f.location && f.date;
    if (step === 3) return f.fullName && f.email;
    return true;
  };
  const next = () => setStep((s) => Math.min(BW_STEPS.length - 1, s + 1));
  const back = () => setStep((s) => Math.max(0, s - 1));
  const submit = (e) => { e.preventDefault(); setSent(true); };

  if (sent) {
    return (
      <BwStepCard>
        <div style={{ textAlign: 'center', padding: '20px 10px' }}>
          <span style={{ width: 64, height: 64, borderRadius: '50%', background: 'var(--color-success-soft)', color: 'var(--color-success)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', marginBottom: 20 }}><Icon name="check" size={30} /></span>
          <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 24, fontWeight: 700, margin: '0 0 10px' }}>Request submitted</h3>
          <p style={{ fontSize: 15.5, color: 'var(--color-text-muted)', lineHeight: 1.6, maxWidth: 420, margin: '0 auto 22px' }}>Your request is in the queue. A Tectus coordinator will match you with vetted vendors and confirm details shortly.</p>
          <button onClick={() => { setSent(false); setStep(0); }} style={{ background: 'transparent', border: 'none', color: 'var(--color-primary-light)', font: 'inherit', fontSize: 14, fontWeight: 600, cursor: 'pointer', display: 'inline-flex', alignItems: 'center', gap: 7 }}><Icon name="rotate-ccw" size={14} />Book another</button>
        </div>
      </BwStepCard>
    );
  }

  return (
    <form onSubmit={step === BW_STEPS.length - 1 ? submit : (e) => e.preventDefault()}>
      <div style={{ marginBottom: 32 }}>
        <BwProgress steps={BW_STEPS} current={step} />
      </div>

      {step === 0 && (
        <BwStepCard>
          <BwSectionTitle sub="Define the name, service, location, and schedule for this request.">Assignment details</BwSectionTitle>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
            <BwField label="Assignment name" helper="Optional — e.g. “Miami waterfront arrival detail”">
              <BwInput value={f.assignmentName} onChange={(e) => set({ assignmentName: e.target.value })} placeholder="Assignment name" />
            </BwField>
            <BwField label="Service type" required>
              <BwSelect value={f.service} onChange={(e) => set({ service: e.target.value })}>
                {BW_SERVICES.map((o) => <option key={o}>{o}</option>)}
              </BwSelect>
            </BwField>
            <BwField label="Location" required helper="Address or venue name">
              <BwInput value={f.location} onChange={(e) => set({ location: e.target.value })} placeholder="Search for location" required />
            </BwField>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
              <BwField label="Start date" required><BwInput type="date" value={f.date} onChange={(e) => set({ date: e.target.value })} required /></BwField>
              <BwField label="Start time"><BwInput type="time" value={f.time} onChange={(e) => set({ time: e.target.value })} /></BwField>
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
              <BwField label="Requirement"><BwSeg options={['Unarmed', 'Armed']} value={f.armed} onChange={(v) => set({ armed: v })} /></BwField>
              <BwField label="Timing"><BwSeg options={['Scheduled', 'Urgent']} value={f.urgency} onChange={(v) => set({ urgency: v })} /></BwField>
            </div>
          </div>
        </BwStepCard>
      )}

      {step === 1 && (
        <BwStepCard>
          <BwSectionTitle sub="Set the size and presentation of your security team.">Your team</BwSectionTitle>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 22 }}>
            <div>
              <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--color-text)', marginBottom: 10 }}>Personnel required</div>
              <BwStepper value={f.teamSize} onChange={(v) => set({ teamSize: v })} />
            </div>
            <BwField label="Appearance">
              <BwSeg options={['Suit', 'Casual', 'Tactical']} value={f.appearance} onChange={(v) => set({ appearance: v })} />
            </BwField>
          </div>
        </BwStepCard>
      )}

      {step === 2 && (
        <BwStepCard>
          <BwSectionTitle sub="Share context to help the assigned team prepare. All fields are optional.">Additional intel</BwSectionTitle>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
            <BwField label="What's the situation?" helper="Describe the environment, event, or scenario.">
              <BwTextarea rows={3} value={f.situation} onChange={(e) => set({ situation: e.target.value })} placeholder="e.g. Corporate dinner at a private venue…" />
            </BwField>
            <BwField label="Any known concerns?">
              <BwTextarea rows={3} value={f.concerns} onChange={(e) => set({ concerns: e.target.value })} placeholder="e.g. Media presence, crowd control near entry…" />
            </BwField>
            <BwField label="Anything else we should know?">
              <BwTextarea rows={3} value={f.notes} onChange={(e) => set({ notes: e.target.value })} placeholder="e.g. Check in with the on-site coordinator upon arrival." />
            </BwField>
          </div>
        </BwStepCard>
      )}

      {step === 3 && (
        <BwStepCard>
          <BwSectionTitle sub="Confirm your contact details and review the request before submitting.">Review &amp; confirm</BwSectionTitle>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginBottom: 22 }}>
            <BwField label="Full name" required><BwInput value={f.fullName} onChange={(e) => set({ fullName: e.target.value })} placeholder="Jordan Avery" required /></BwField>
            <BwField label="Work email" required><BwInput type="email" value={f.email} onChange={(e) => set({ email: e.target.value })} placeholder="you@company.com" required /></BwField>
            <BwField label="Phone"><BwInput type="tel" value={f.phone} onChange={(e) => set({ phone: e.target.value })} placeholder="(555) 000-0000" /></BwField>
            <BwField label="Company"><BwInput value={f.company} onChange={(e) => set({ company: e.target.value })} placeholder="Company or organization" /></BwField>
          </div>
          <div style={{ borderTop: '1px solid var(--color-divider)', paddingTop: 20, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
            <BwReviewRow label="Service" value={f.service} />
            <BwReviewRow label="Location" value={f.location} />
            <BwReviewRow label="Schedule" value={[f.date, f.time].filter(Boolean).join(' · ') || '—'} />
            <BwReviewRow label="Requirement" value={`${f.armed} · ${f.urgency}`} />
            <BwReviewRow label="Team" value={`${f.teamSize} personnel · ${f.appearance}`} />
            {f.assignmentName && <div style={{ gridColumn: 'span 2' }}><BwReviewRow label="Assignment name" value={f.assignmentName} /></div>}
            {f.situation && <div style={{ gridColumn: 'span 2' }}><BwReviewRow label="Situation" value={f.situation} /></div>}
            {f.concerns && <div style={{ gridColumn: 'span 2' }}><BwReviewRow label="Concerns" value={f.concerns} /></div>}
            {f.notes && <div style={{ gridColumn: 'span 2' }}><BwReviewRow label="Instructions" value={f.notes} /></div>}
          </div>
        </BwStepCard>
      )}

      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16, marginTop: 24, flexWrap: 'wrap' }}>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8, fontSize: 12.5, color: 'var(--color-text-faint)' }}><Icon name="lock" size={14} color="var(--color-primary)" />Your details stay private.</span>
        <div style={{ display: 'flex', gap: 10 }}>
          {step > 0 && <BwButton type="button" variant="secondary" onClick={back}>Back</BwButton>}
          {step < BW_STEPS.length - 1
            ? <BwButton type="button" variant="primary" disabled={!canNext()} iconRight={<Icon name="arrow-right" size={16} />} onClick={next}>Continue</BwButton>
            : <BwButton type="submit" variant="primary" disabled={!canNext()} iconRight={<Icon name="arrow-right" size={16} />}>Submit request</BwButton>}
        </div>
      </div>
    </form>
  );
}

function BookNowPage({ data }) {
  return (
    <div>
      <PageHero
        group={data.group} groupHref={data.groupHref} title={data.title}
        eyebrow={data.eyebrow} h1={data.h1} sub={data.sub}
      />
      <section className="wrap" style={{ padding: '8px 40px 96px', maxWidth: 780 }}>
        <Reveal><BookingWizard /></Reveal>
      </section>
    </div>
  );
}

window.CUSTOM_PAGES = window.CUSTOM_PAGES || {};
window.CUSTOM_PAGES['book-now'] = BookNowPage;
