/* Rust Truck — Book the truck. A 3-step enquiry wizard (Your event ·
   The venue · Get in touch) on an oxblood ground, with a clickable
   progress bar, soft step transitions and an enquiry-summary success
   state. Only phone + email are required (on the last step). */
(function () {
  const { Button, Eyebrow, Badge } = window.RustTruckDesignSystem_a832c6;

  /* ---- small building blocks ---------------------------------- */

  // Wraps step content with a one-shot enter animation. The animation
  // lives on a class that is REMOVED once it finishes, so if the frame
  // clock is ever paused the content still resolves to its visible
  // end-state rather than staying hidden.
  function StepFade({ dx, style, children }) {
    const ref = React.useRef(null);
    React.useEffect(() => {
      const el = ref.current;
      if (!el) return;
      el.classList.add('rt-anim');
      const t = setTimeout(() => { if (ref.current) ref.current.classList.remove('rt-anim'); }, 460);
      return () => clearTimeout(t);
    }, []);
    return <div ref={ref} style={{ '--rt-dx': dx, ...style }}>{children}</div>;
  }

  // Label that sits above a field (typewriter, all-caps)
  function FieldLabel({ children, optional, el }) {
    return (
      <div style={{
        fontFamily: 'var(--font-label)', fontSize: 'var(--text-2xs)',
        letterSpacing: 'var(--tracking-label)', textTransform: 'uppercase',
        color: 'var(--ink-500)', marginBottom: 8,
      }}>
        {children}
        {optional && <span style={{ color: 'var(--ink-400)', marginLeft: 8, textTransform: 'lowercase', letterSpacing: '0.06em' }}>· {el ? 'προαιρετικό' : 'optional'}</span>}
      </div>
    );
  }

  // Native select styled like the DS Select, but layout-free for grids
  function PlainSelect({ value, onChange, options, ariaLabel }) {
    const [focus, setFocus] = React.useState(false);
    return (
      <div style={{ position: 'relative' }}>
        <select aria-label={ariaLabel} value={value} onChange={onChange}
          onFocus={() => setFocus(true)} onBlur={() => setFocus(false)}
          style={{
            width: '100%', appearance: 'none', WebkitAppearance: 'none',
            fontFamily: 'var(--font-body)', fontSize: 'var(--text-md)',
            color: value ? 'var(--ink-900)' : 'var(--ink-400)',
            padding: '11px 38px 11px 13px',
            border: `1px solid ${focus ? 'var(--brick-500)' : 'var(--paper-400)'}`,
            borderRadius: 'var(--radius-sm)', background: 'var(--surface-card)',
            outline: 'none', boxShadow: focus ? 'var(--focus-ring)' : 'none', cursor: 'pointer',
            transition: 'border-color var(--dur-fast) var(--ease-out), box-shadow var(--dur-fast) var(--ease-out)',
          }}>
          {options.map((o) => <option key={o.value} value={o.value} disabled={o.value === ''}>{o.label}</option>)}
        </select>
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="var(--ink-500)"
          strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"
          style={{ position: 'absolute', right: 12, top: '50%', transform: 'translateY(-50%)', pointerEvents: 'none' }}>
          <polyline points="6 9 12 15 18 9" />
        </svg>
      </div>
    );
  }

  function PlainInput({ value, onChange, placeholder, type = 'text', invalid, ariaLabel }) {
    const [focus, setFocus] = React.useState(false);
    const border = invalid ? 'var(--error-500)' : focus ? 'var(--brick-500)' : 'var(--paper-400)';
    return (
      <input type={type} value={value} onChange={onChange} placeholder={placeholder} aria-label={ariaLabel}
        onFocus={() => setFocus(true)} onBlur={() => setFocus(false)}
        style={{
          width: '100%', boxSizing: 'border-box', fontFamily: 'var(--font-body)', fontSize: 'var(--text-md)',
          color: 'var(--ink-900)', padding: '11px 13px', border: `1px solid ${border}`,
          borderRadius: 'var(--radius-sm)', background: 'var(--surface-card)', outline: 'none',
          boxShadow: focus && !invalid ? 'var(--focus-ring)' : 'none',
          transition: 'border-color var(--dur-fast) var(--ease-out), box-shadow var(--dur-fast) var(--ease-out)',
        }} />
    );
  }

  function Segmented({ options, value, onChange }) {
    return (
      <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap' }}>
        {options.map((o) => (
          <button key={o.value} type="button" className={'rt-seg' + (value === o.value ? ' is-on' : '')}
            aria-pressed={value === o.value} onClick={() => onChange(value === o.value ? '' : o.value)}>
            {o.label}
          </button>
        ))}
      </div>
    );
  }

  /* ---- progress bar ------------------------------------------- */

  function Progress({ steps, current, maxReached, onJump, compact }) {
    return (
      <div style={{ display: 'flex', alignItems: 'center', marginBottom: compact ? 30 : 40 }}>
        {steps.map((s, idx) => {
          const done = idx < current;
          const active = idx === current;
          const clickable = idx <= maxReached;
          return (
            <React.Fragment key={s.key}>
              <button type="button" className="rt-stepbtn" data-clickable={clickable ? '1' : '0'}
                onClick={() => clickable && onJump(idx)}>
                <span style={{
                  width: 34, height: 34, flex: 'none', borderRadius: '50%',
                  display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                  fontFamily: 'var(--font-signage)', fontSize: 16,
                  background: done ? 'var(--brick-500)' : 'transparent',
                  border: `2px solid ${done || active ? 'var(--brick-500)' : 'var(--paper-400)'}`,
                  color: done ? 'var(--paper-50)' : active ? 'var(--brick-500)' : 'var(--ink-400)',
                  transition: 'all var(--dur-fast) var(--ease-out)',
                }}>
                  {done ? (
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor"
                      strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12" /></svg>
                  ) : s.n}
                </span>
                {!compact && <span style={{
                  fontFamily: 'var(--font-label)', fontSize: 'var(--text-2xs)', letterSpacing: '0.12em',
                  textTransform: 'uppercase', whiteSpace: 'nowrap',
                  color: active ? 'var(--ink-900)' : done ? 'var(--ink-700)' : 'var(--ink-400)',
                }}>{s.label}</span>}
              </button>
              {idx < steps.length - 1 && (
                <span style={{
                  flex: 1, height: 0, margin: '0 14px',
                  borderTop: `2px ${done ? 'solid var(--brick-500)' : 'solid var(--paper-300)'}`,
                  minWidth: 16,
                }} />
              )}
            </React.Fragment>
          );
        })}
      </div>
    );
  }

  /* ---- main --------------------------------------------------- */

  function BookScreen({ lang }) {
    const I = window.RTIcons;
    const el = lang === 'EL';
    const bp = window.useViewport();
    const [step, setStep] = React.useState(0);
    const [maxReached, setMaxReached] = React.useState(0);
    const [dir, setDir] = React.useState(1);
    const [sent, setSent] = React.useState(false);
    const [touched, setTouched] = React.useState(false);

    const [f, setF] = React.useState({
      eventType: '', guests: '', day: '', month: '', year: '',
      town: '', setting: '', power: '', phone: '', email: '', notes: '',
    });
    const set = (k) => (e) => setF((p) => ({ ...p, [k]: e.target.value }));
    const setRaw = (k, v) => setF((p) => ({ ...p, [k]: v }));

    const steps = [
      { key: 'event', n: 1, label: el ? 'Η εκδήλωση' : 'Your event' },
      { key: 'venue', n: 2, label: el ? 'Ο χώρος' : 'The venue' },
      { key: 'touch', n: 3, label: el ? 'Επικοινωνία' : 'Get in touch' },
    ];

    const go = (next) => {
      setDir(next > step ? 1 : -1);
      setStep(next);
      setMaxReached((m) => Math.max(m, next));
    };
    const jump = (idx) => { if (idx <= maxReached) go(idx); };

    const emailOk = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(f.email.trim());
    const phoneOk = f.phone.trim().length >= 6;
    const submit = () => {
      setTouched(true);
      if (emailOk && phoneOk) setSent(true);
    };

    const reset = () => {
      setF({ eventType: '', guests: '', day: '', month: '', year: '', town: '', setting: '', power: '', phone: '', email: '', notes: '' });
      setStep(0); setMaxReached(0); setSent(false); setTouched(false); setDir(1);
    };

    /* option lists */
    const eventOpts = [
      { value: '', label: el ? 'Διάλεξε…' : 'Choose…' },
      ...(el ? ['Γάμος', 'Γενέθλια', 'Εταιρικό', 'Φεστιβάλ', 'Άλλο'] : ['Wedding', 'Birthday', 'Corporate', 'Festival', 'Other']).map((v) => ({ value: v, label: v })),
    ];
    const days = [{ value: '', label: el ? 'Μέρα' : 'Day' }, ...Array.from({ length: 31 }, (_, i) => ({ value: String(i + 1), label: String(i + 1) }))];
    const monthNames = el
      ? ['Ιαν', 'Φεβ', 'Μάρ', 'Απρ', 'Μάι', 'Ιούν', 'Ιούλ', 'Αύγ', 'Σεπ', 'Οκτ', 'Νοέ', 'Δεκ']
      : ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
    const months = [{ value: '', label: el ? 'Μήνας' : 'Month' }, ...monthNames.map((m, i) => ({ value: String(i + 1), label: m }))];
    const years = [{ value: '', label: el ? 'Έτος' : 'Year' }, ...[2026, 2027, 2028, 2029].map((y) => ({ value: String(y), label: String(y) }))];

    const settingOpts = (el ? [['indoor', 'Εσωτερικός'], ['outdoor', 'Εξωτερικός'], ['both', 'Και τα δύο']] : [['indoor', 'Indoor'], ['outdoor', 'Outdoor'], ['both', 'Both']]).map(([value, label]) => ({ value, label }));
    const powerOpts = (el ? [['yes', 'Ναι'], ['no', 'Όχι'], ['unsure', 'Δεν είμαι σίγουρος/η']] : [['yes', 'Yes'], ['no', 'No'], ['unsure', 'Not sure']]).map(([value, label]) => ({ value, label }));

    const labelFor = (opts, v) => (opts.find((o) => o.value === v) || {}).label || '';
    const prettyDate = (f.day && f.month && f.year)
      ? `${String(f.day).padStart(2, '0')}/${String(f.month).padStart(2, '0')}/${f.year}` : '';

    const wrap = { maxWidth: 760, margin: '0 auto', padding: bp.mobile ? '0 18px' : '0 32px' };
    const cardPad = bp.mobile ? '28px 22px' : '44px 56px';
    const duoCols = bp.mobile ? '1fr' : '1fr 1fr';

    /* ---- success ---- */
    if (sent) {
      const rows = [
        [el ? 'Εκδήλωση' : 'Event', f.eventType],
        [el ? 'Ημερομηνία' : 'Date', prettyDate],
        [el ? 'Άτομα' : 'Guests', f.guests],
        [el ? 'Χώρος' : 'Where', f.town],
        [el ? 'Είδος χώρου' : 'Setting', labelFor(settingOpts, f.setting)],
        [el ? 'Ρεύμα / Νερό' : 'Power / Water', labelFor(powerOpts, f.power)],
        [el ? 'Τηλέφωνο' : 'Phone', f.phone],
        ['Email', f.email],
        [el ? 'Σημειώσεις' : 'Notes', f.notes],
      ];
      return (
        <div style={{ background: 'var(--brick-700)', backgroundImage: 'var(--grain)', backgroundSize: 'var(--grain-size)' }}>
          <div style={{ ...wrap, padding: bp.mobile ? '40px 18px 52px' : '72px 32px 64px' }}>
            <StepFade key="success" dx="24px" style={{ background: 'var(--paper-100)', backgroundImage: 'var(--grain)', backgroundSize: 'var(--grain-size)', borderRadius: 'var(--radius-md)', border: '3px solid var(--ink-900)', boxShadow: 'var(--shadow-lg)', padding: bp.mobile ? '36px 22px' : '52px 56px' }}>
              <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', textAlign: 'center' }}>
                <span style={{ width: 84, height: 84, borderRadius: '50%', background: 'var(--leaf-100)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}>
                  <svg width="38" height="38" viewBox="0 0 24 24" fill="none" stroke="var(--leaf-500)" strokeWidth="2.6" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12" /></svg>
                </span>
                <p style={{ fontFamily: 'var(--font-script)', fontSize: 38, color: 'var(--brick-500)', margin: '22px 0 0', lineHeight: 1, whiteSpace: 'nowrap' }}>{el ? 'στην υγειά μας!' : 'cheers!'}</p>
                <h1 style={{ fontFamily: 'var(--font-display)', textTransform: 'uppercase', fontSize: 'clamp(32px,4.4vw,46px)', color: 'var(--ink-900)', margin: '8px 0 0', lineHeight: 0.95 }}>
                  {el ? 'Το αίτημα στάλθηκε' : 'Enquiry sent'}
                </h1>
                <p style={{ fontFamily: 'var(--font-body)', fontSize: 17, lineHeight: 1.55, color: 'var(--ink-700)', margin: '16px 0 0', maxWidth: '46ch' }}>
                  {el
                    ? 'Ευχαριστούμε — έχουμε τα στοιχεία παρακάτω. Θα επικοινωνήσουμε σε μία-δύο μέρες με διαθεσιμότητα και μια πρόταση λίστας.'
                    : 'Thanks — we’ve got the details below. We’ll be in touch within a day or two with availability and a menu sketch.'}
                </p>
              </div>

              <div style={{ marginTop: 40 }}>
                <div style={{ fontFamily: 'var(--font-label)', fontSize: 'var(--text-2xs)', letterSpacing: '0.16em', textTransform: 'uppercase', color: 'var(--brick-600)', borderBottom: '2px solid var(--ink-900)', paddingBottom: 10 }}>
                  {el ? 'Το αίτημά σου' : 'Your enquiry'}
                </div>
                {rows.map(([k, v]) => (
                  <div key={k} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 20, padding: '15px 0', borderBottom: '1px dashed var(--paper-400)' }}>
                    <span style={{ fontFamily: 'var(--font-label)', fontSize: 11, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--ink-500)' }}>{k}</span>
                    <span style={{ fontFamily: 'var(--font-body)', fontSize: 16, color: v ? 'var(--ink-900)' : 'var(--ink-400)', textAlign: 'right' }}>{v || '—'}</span>
                  </div>
                ))}
              </div>

              <div style={{ display: 'flex', justifyContent: 'center', marginTop: 36 }}>
                <Button variant="ghost" onClick={reset}>{el ? 'Ξεκίνα από την αρχή' : 'Start over'}</Button>
              </div>
            </StepFade>
            <p style={{ textAlign: 'center', fontFamily: 'var(--font-body)', fontStyle: 'italic', fontSize: 15, color: 'var(--paper-300)', margin: '32px 0 0' }}>
              {el ? 'Χωρίς προκαταβολή για αίτημα · επιβεβαιώνουμε πρώτα τη διαθεσιμότητα.' : 'No deposit to enquire · we’ll confirm availability first.'}
            </p>
          </div>
        </div>
      );
    }

    /* ---- step content ---- */
    const StepHead = ({ n, title }) => (
      <div style={{ marginBottom: 28 }}>
        <div style={{ fontFamily: 'var(--font-label)', fontSize: 'var(--text-2xs)', letterSpacing: '0.16em', textTransform: 'uppercase', color: 'var(--brick-600)' }}>{el ? 'Βήμα' : 'Step'} {String(n).padStart(2, '0')}</div>
        <h2 style={{ fontFamily: 'var(--font-display)', textTransform: 'uppercase', fontSize: 'clamp(28px,3.6vw,40px)', color: 'var(--ink-900)', margin: '8px 0 0', lineHeight: 0.98 }}>{title}</h2>
      </div>
    );

    let body;
    if (step === 0) {
      body = (
        <div>
          <StepHead n={1} title={el ? 'Πες μας για την εκδήλωση' : 'Tell us about your event'} />
          <div style={{ display: 'grid', gridTemplateColumns: duoCols, gap: 22 }}>
            <div>
              <FieldLabel>{el ? 'Τύπος εκδήλωσης' : 'Event type'}</FieldLabel>
              <PlainSelect value={f.eventType} onChange={set('eventType')} options={eventOpts} ariaLabel={el ? 'Τύπος εκδήλωσης' : 'Event type'} />
            </div>
            <div>
              <FieldLabel>{el ? 'Αριθμός ατόμων' : 'Guest count'}</FieldLabel>
              <PlainInput type="number" value={f.guests} onChange={set('guests')} placeholder="120" ariaLabel={el ? 'Αριθμός ατόμων' : 'Guest count'} />
              <div style={{ fontFamily: 'var(--font-body)', fontSize: 'var(--text-xs)', color: 'var(--text-muted)', marginTop: 8 }}>{el ? 'Ένας κατά προσέγγιση αριθμός αρκεί' : 'A rough number is fine'}</div>
            </div>
          </div>
          <div style={{ marginTop: 22 }}>
            <FieldLabel>{el ? 'Επιθυμητή ημερομηνία' : 'Preferred date'}</FieldLabel>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1.4fr 1fr', gap: 12 }}>
              <PlainSelect value={f.day} onChange={set('day')} options={days} ariaLabel={el ? 'Μέρα' : 'Day'} />
              <PlainSelect value={f.month} onChange={set('month')} options={months} ariaLabel={el ? 'Μήνας' : 'Month'} />
              <PlainSelect value={f.year} onChange={set('year')} options={years} ariaLabel={el ? 'Έτος' : 'Year'} />
            </div>
          </div>
        </div>
      );
    } else if (step === 1) {
      body = (
        <div>
          <StepHead n={2} title={el ? 'Πού γίνεται;' : 'Where is it happening?'} />
          <div>
            <FieldLabel>{el ? 'Πόλη ή χώρος' : 'Town or venue'}</FieldLabel>
            <PlainInput value={f.town} onChange={set('town')} placeholder={el ? 'π.χ. Μπρίστολ, ή όνομα χώρου' : 'e.g. Bristol, or a venue name'} ariaLabel={el ? 'Πόλη ή χώρος' : 'Town or venue'} />
          </div>
          <div style={{ marginTop: 26 }}>
            <FieldLabel optional el={el}>{el ? 'Εσωτερικός ή εξωτερικός;' : 'Indoor or outdoor?'}</FieldLabel>
            <Segmented options={settingOpts} value={f.setting} onChange={(v) => setRaw('setting', v)} />
          </div>
          <div style={{ marginTop: 26 }}>
            <FieldLabel optional el={el}>{el ? 'Ρεύμα & νερό στον χώρο;' : 'Power & water on site?'}</FieldLabel>
            <Segmented options={powerOpts} value={f.power} onChange={(v) => setRaw('power', v)} />
          </div>
        </div>
      );
    } else {
      body = (
        <div>
          <StepHead n={3} title={el ? 'Πώς θα σε βρούμε;' : 'How do we reach you?'} />
          <div style={{ display: 'grid', gridTemplateColumns: duoCols, gap: 22 }}>
            <div>
              <FieldLabel>{el ? 'Τηλέφωνο' : 'Phone'}</FieldLabel>
              <PlainInput type="tel" value={f.phone} onChange={set('phone')} placeholder="07000 000000" invalid={touched && !phoneOk} ariaLabel={el ? 'Τηλέφωνο' : 'Phone'} />
              {touched && !phoneOk && <div style={{ fontFamily: 'var(--font-body)', fontSize: 'var(--text-xs)', color: 'var(--error-500)', marginTop: 8 }}>{el ? 'Δώσε ένα τηλέφωνο επικοινωνίας' : 'Add a contact number'}</div>}
            </div>
            <div>
              <FieldLabel>Email</FieldLabel>
              <PlainInput type="email" value={f.email} onChange={set('email')} placeholder="jane@email.com" invalid={touched && !emailOk} ariaLabel="Email" />
              {touched && !emailOk && <div style={{ fontFamily: 'var(--font-body)', fontSize: 'var(--text-xs)', color: 'var(--error-500)', marginTop: 8 }}>{el ? 'Δώσε ένα έγκυρο email' : 'Enter a valid email'}</div>}
            </div>
          </div>
          <div style={{ marginTop: 22 }}>
            <FieldLabel>{el ? 'Κάτι άλλο;' : 'Anything else?'}</FieldLabel>
            <textarea value={f.notes} onChange={set('notes')} rows={4}
              placeholder={el ? 'Το ύφος που θες, αγαπημένα ποτά, ώρες…' : 'The vibe you’re after, favourite drinks, timings…'}
              style={{ width: '100%', boxSizing: 'border-box', fontFamily: 'var(--font-body)', fontSize: 'var(--text-md)', color: 'var(--ink-900)', padding: '11px 13px', border: '1px solid var(--paper-400)', borderRadius: 'var(--radius-sm)', background: 'var(--surface-card)', outline: 'none', resize: 'vertical' }} />
          </div>
        </div>
      );
    }

    return (
      <div style={{ background: 'var(--brick-700)', backgroundImage: 'var(--grain)', backgroundSize: 'var(--grain-size)' }}>
        <div style={{ ...wrap, padding: bp.mobile ? '44px 18px 24px' : '64px 32px 28px', textAlign: 'center' }}>
          <Eyebrow align="center" color="var(--amber-400)">{el ? 'Κλείσε το φορτηγό · σε 48 ώρες' : 'Book the truck · within 48 hours'}</Eyebrow>
        </div>
        <div style={{ ...wrap, paddingBottom: 8 }}>
          <div style={{ background: 'var(--paper-100)', backgroundImage: 'var(--grain)', backgroundSize: 'var(--grain-size)', borderRadius: 'var(--radius-md)', border: '3px solid var(--ink-900)', boxShadow: 'var(--shadow-lg)', padding: cardPad }}>
            <Progress steps={steps} current={step} maxReached={maxReached} onJump={jump} compact={bp.mobile} />

            <StepFade key={step} dx={(dir >= 0 ? 24 : -24) + 'px'}>
              {body}
            </StepFade>

            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16, marginTop: 36, paddingTop: 26, borderTop: '1px solid var(--paper-300)' }}>
              {step > 0 ? (
                <button type="button" onClick={() => go(step - 1)} style={{ display: 'inline-flex', alignItems: 'center', gap: 10, background: 'none', border: 'none', cursor: 'pointer', fontFamily: 'var(--font-label)', fontSize: 'var(--text-2xs)', letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--ink-700)', padding: '8px 4px' }}>
                  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><line x1="19" y1="12" x2="5" y2="12" /><polyline points="12 19 5 12 12 5" /></svg>
                  {el ? 'Πίσω' : 'Back'}
                </button>
              ) : <span />}
              {step < 2
                ? <Button variant="primary" withArrow onClick={() => go(step + 1)}>{el ? 'Συνέχεια' : 'Continue'}</Button>
                : <Button variant="primary" size="lg" withArrow onClick={submit}>{el ? 'Στείλε το αίτημα' : 'Send enquiry'}</Button>}
            </div>
          </div>
          <p style={{ textAlign: 'center', fontFamily: 'var(--font-body)', fontStyle: 'italic', fontSize: 15, color: 'var(--paper-300)', margin: '28px 0 0' }}>
            {el ? 'Χωρίς προκαταβολή για αίτημα · επιβεβαιώνουμε πρώτα τη διαθεσιμότητα.' : 'No deposit to enquire · we’ll confirm availability first.'}
          </p>
        </div>
      </div>
    );
  }

  window.RTBookScreen = BookScreen;
})();
