/* check-in-flow.jsx — Typeform-style arrival check-in with Miami luxury concierge tone */

const FLOW_STEPS = [
  {
    id: 'reservation',
    kind: 'reservation',
    eyebrow: 'Welcome to Novus',
    label: <>Let's find your <em style={{ fontStyle: 'italic' }}>reservation.</em></>,
    help: 'Type your confirmation code or the email you booked with. We\u2019ll pull everything else.',
    placeholder: 'NVR-2026-4F2A · or your booking email',
  },
  {
    id: 'name',
    kind: 'text',
    eyebrow: 'Your details',
    label: <>And your <em style={{ fontStyle: 'italic' }}>full name?</em></>,
    help: 'Exactly as it appears on your government ID — passport or driver\u2019s license.',
    placeholder: 'Marina Acosta',
  },
  {
    id: 'email',
    kind: 'email',
    eyebrow: 'Your details',
    label: <>Where should we send your <em style={{ fontStyle: 'italic' }}>door code?</em></>,
    help: 'Activates at 4 PM on your arrival day. We\u2019ll also send the Wi-Fi password and Miguel\u2019s WhatsApp.',
    placeholder: 'you@email.com',
  },
  {
    id: 'phone',
    kind: 'tel',
    eyebrow: 'Your details',
    label: <>WhatsApp for your <em style={{ fontStyle: 'italic' }}>concierge.</em></>,
    help: 'Miguel replies in under an hour, in English or Spanish. Real human — not a bot.',
    placeholder: '+1 305-848-3113',
  },
  {
    id: 'doc',
    kind: 'file',
    eyebrow: 'Identity',
    label: <>Let's verify your <em style={{ fontStyle: 'italic' }}>identity.</em></>,
    help: 'Florida law requires this for any stay under 30 days. Encrypted at rest. Deleted within 30 days of check-out.',
  },
  {
    id: 'selfie',
    kind: 'selfie',
    eyebrow: 'Identity',
    label: <>One quick <em style={{ fontStyle: 'italic' }}>selfie.</em></>,
    help: 'Just to match the photo on your ID. We don\u2019t store it or use it for anything else.',
  },
  {
    id: 'guests',
    kind: 'guests',
    eyebrow: 'Your party',
    label: <>Who's joining you in <em style={{ fontStyle: 'italic' }}>Miami?</em></>,
    help: 'First names of any other adult guests staying overnight. We have welcome bottles ready for everyone.',
  },
  {
    id: 'arrival',
    kind: 'choice',
    eyebrow: 'Arrival',
    label: <>What time will you be <em style={{ fontStyle: 'italic' }}>landing?</em></>,
    help: 'Tap whichever is closest. We\u2019ll have the villa exactly the way you like it.',
    options: [
      { value: 'morning', label: 'Morning · before 12 PM', sub: 'Early check-in available' },
      { value: 'afternoon', label: 'Afternoon · 12 – 4 PM', sub: 'Lounge by the pool while we finish' },
      { value: 'evening', label: 'Standard · 4 PM onward', sub: 'Door code is live' },
      { value: 'late', label: 'Late night · after 10 PM', sub: 'We\u2019ll leave the porch on' },
    ],
  },
  {
    id: 'transport',
    kind: 'choice',
    eyebrow: 'Arrival',
    label: <>How are you getting <em style={{ fontStyle: 'italic' }}>here?</em></>,
    help: 'So we can prep parking, the gate code, or a private pickup if you\u2019d like one.',
    options: [
      { value: 'uber', label: 'Uber / Lyft from MIA or FLL', sub: 'Driver gets the address + gate code' },
      { value: 'rental', label: 'Rental car', sub: 'Driveway + garage code ready' },
      { value: 'private', label: 'Private driver / black car', sub: 'Add to itinerary in concierge' },
      { value: 'novus', label: 'Novus chauffeur pickup', sub: 'Mercedes V-Class · from $180' },
    ],
  },
  {
    id: 'reason',
    kind: 'choice',
    eyebrow: 'The trip',
    label: <>What brings you to <em style={{ fontStyle: 'italic' }}>Miami?</em></>,
    help: 'No wrong answer — it just helps us set the tone. (Honeymoon \u2260 bachelor party.)',
    options: [
      { value: 'vacation', label: 'Vacation · relax mode' },
      { value: 'work', label: 'Work trip · need fast Wi-Fi' },
      { value: 'anniversary', label: 'Anniversary · low-key romantic' },
      { value: 'birthday', label: 'Birthday · let\u2019s celebrate' },
      { value: 'family', label: 'Family trip · with kids' },
      { value: 'group', label: 'Group / friends getaway' },
      { value: 'wedding', label: 'Wedding party' },
      { value: 'other', label: 'Something else' },
    ],
  },
  {
    id: 'concierge',
    kind: 'multichoice',
    eyebrow: 'Concierge',
    label: <>Anything we should have <em style={{ fontStyle: 'italic' }}>ready?</em></>,
    help: 'Pick as many as you like. None of it costs anything to ask. Concierge will follow up on the priced items.',
    options: [
      { value: 'champagne', label: 'Welcome bottle of champagne', sub: 'Complimentary' },
      { value: 'groceries', label: 'Pre-stocked kitchen', sub: 'Send list · billed at receipt' },
      { value: 'chef', label: 'Private chef for one night', sub: 'From $220/person' },
      { value: 'yacht', label: 'Yacht charter · Galeon 500', sub: 'Half-day · from $4,800' },
      { value: 'spa', label: 'In-villa spa / massage', sub: 'From $180/hr' },
      { value: 'restaurants', label: 'Restaurant reservations', sub: 'Carbone, Cote, Joe\u2019s, etc.' },
      { value: 'nightlife', label: 'Club / lounge table service', sub: 'LIV, E11even, Mr. Jones' },
      { value: 'flowers', label: 'Fresh flowers on arrival', sub: 'From $90' },
    ],
  },
  {
    id: 'allergies',
    kind: 'textarea',
    eyebrow: 'Concierge',
    label: <>Any allergies, requests, or <em style={{ fontStyle: 'italic' }}>preferences?</em></>,
    help: 'Dietary stuff, surprises for a partner, "no peanuts," "extra towels," "she\u2019s scared of the dark" — anything.',
    placeholder: 'Optional. Skip if nothing comes to mind.',
    optional: true,
  },
  {
    id: 'rules',
    kind: 'rules',
    eyebrow: 'The fine print',
    label: <>Our house, our <em style={{ fontStyle: 'italic' }}>rules.</em></>,
    help: 'Short and reasonable. Tap to confirm and continue.',
  },
  {
    id: 'sign',
    kind: 'sign',
    eyebrow: 'Final step',
    label: <>Sign the <em style={{ fontStyle: 'italic' }}>agreement.</em></>,
    help: 'Your signature finalizes the rental agreement and activates your door code on arrival day.',
  },
];

const HOUSE_RULES = [
  ['Quiet hours', '8 PM – 8 AM. Outdoor music down after 10 PM.'],
  ['No parties or events', 'Daytime gatherings up to 12 guests are fine — events require approval.'],
  ['Max occupancy', 'As stated on your booking. Additional overnight guests must be registered.'],
  ['Smoking', 'No smoking indoors. Designated outdoor areas only.'],
  ['Pets', 'Pet-friendly residences only. Please confirm with concierge.'],
  ['Damage policy', 'Accidental damages covered up to $500. Anything above billed to card on file.'],
];

function CheckInFlow() {
  const [idx, setIdx] = React.useState(0);
  const [data, setData] = React.useState({});
  const [done, setDone] = React.useState(false);
  const [transitioning, setTransitioning] = React.useState(false);

  const step = FLOW_STEPS[idx];
  const set = (v) => setData(d => ({ ...d, [step.id]: v }));

  const valid = () => {
    if (step.optional) return true;
    const v = data[step.id];
    if (step.kind === 'rules') return v === true;
    if (step.kind === 'sign') return !!v;
    if (step.kind === 'multichoice') return true;
    if (step.kind === 'guests') return data.skipGuests || (Array.isArray(v) ? v.some(g => typeof g === 'string' && g.trim()) : false);
    return !!v && (typeof v === 'string' ? v.trim().length > 0 : true);
  };

  const advance = (forward) => {
    setTransitioning(true);
    setTimeout(() => {
      if (forward) {
        if (idx === FLOW_STEPS.length - 1) setDone(true);
        else setIdx(i => i + 1);
      } else {
        setIdx(i => Math.max(0, i - 1));
      }
      setTransitioning(false);
    }, 220);
  };

  // Enter key advances
  React.useEffect(() => {
    const onKey = (e) => {
      if (e.key === 'Enter' && !e.shiftKey && valid()) {
        e.preventDefault();
        advance(true);
      }
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [idx, data]);

  if (done) return <SuccessScreen data={data} />;

  return (
    <div style={{
      minHeight: '100vh', background: 'var(--bg-page)',
      display: 'flex', flexDirection: 'column',
    }}>
      <style>{`
        .ci-grid { flex: 1; display: grid; grid-template-columns: 1fr; min-height: calc(100vh - 64px); }
        .ci-question { padding: 40px 22px 120px; }
        .ci-side { display: none; }
        @media (min-width: 900px) {
          .ci-grid { grid-template-columns: 1fr 1fr; }
          .ci-question { padding: 64px 80px 80px; }
          .ci-side { display: block; }
        }
        /* On mobile the primary action sticks to the bottom — thumb-reachable. */
        .ci-actions { display: flex; align-items: center; gap: 14px; margin-top: 32px; }
        @media (max-width: 899px) {
          .ci-actions {
            position: fixed; left: 0; right: 0; bottom: 0; z-index: 50; margin: 0;
            padding: 14px 18px calc(14px + env(safe-area-inset-bottom));
            background: rgba(250,247,242,0.96);
            backdrop-filter: blur(16px); -webkit-backdrop-filter: blur(16px);
            border-top: 1px solid var(--line);
          }
          .ci-continue { flex: 1; justify-content: center; }
          .ci-enter-hint { display: none; }
        }
      `}</style>
      <FlowHeader idx={idx} total={FLOW_STEPS.length} />

      <div className="ci-grid">
        {/* LEFT: Question */}
        <div className="ci-question" style={{
          display: 'flex', flexDirection: 'column', justifyContent: 'center',
          maxWidth: 720, width: '100%',
          opacity: transitioning ? 0 : 1, transform: transitioning ? 'translateY(8px)' : 'translateY(0)',
          transition: 'all 220ms var(--ease-novus)',
        }}>
          <div className="overline" style={{ color: 'var(--sun-coral)', marginBottom: 14 }}>
            {step.eyebrow} · {idx + 1} / {FLOW_STEPS.length}
          </div>
          <h1 style={{
            fontFamily: 'var(--font-display)', fontWeight: 400,
            fontSize: 'clamp(36px, 4vw, 56px)', color: 'var(--navy-900)',
            margin: '0 0 14px', letterSpacing: '-0.015em', lineHeight: 1.08,
            textWrap: 'balance',
          }}>{step.label}</h1>
          {step.help && (
            <p style={{
              color: 'var(--ink-700)', fontSize: 16, lineHeight: 1.65,
              margin: '0 0 36px', maxWidth: 540, textWrap: 'pretty',
            }}>{step.help}</p>
          )}

          <StepInput step={step} value={data[step.id]} set={set} onAdvance={() => advance(true)} skipGuests={() => setData(d => ({ ...d, skipGuests: true }))} />

          <div className="ci-actions">
            {idx > 0 && (
              <button onClick={() => advance(false)} className="ci-back" style={{
                background: 'transparent', border: 0, order: 0,
                color: 'var(--ink-500)', fontSize: 14, cursor: 'pointer', padding: '8px 4px',
              }}>← Back</button>
            )}
            <button onClick={() => advance(true)} disabled={!valid()} className="ci-continue"
              style={{
                padding: '15px 28px', borderRadius: 999, border: 0, minHeight: 52,
                background: valid()
                  ? 'linear-gradient(135deg, var(--sun-coral), var(--sun-amber))'
                  : 'var(--sand-200)',
                color: valid() ? '#fff' : 'var(--ink-500)',
                fontSize: 15, fontWeight: 600, cursor: valid() ? 'pointer' : 'not-allowed',
                boxShadow: valid() ? '0 6px 18px rgba(252,172,100,0.36)' : 'none',
                transition: 'all 200ms var(--ease-novus)',
                display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 10,
              }}>
              {idx === FLOW_STEPS.length - 1 ? 'Complete check-in' : 'Continue'} →
            </button>
            <span className="ci-enter-hint" style={{ fontSize: 12, color: 'var(--ink-500)' }}>
              press <kbd style={{
                background: 'var(--sand-100)', border: '1px solid var(--line)',
                borderRadius: 4, padding: '2px 6px', fontFamily: 'var(--font-text)', fontSize: 11,
              }}>Enter ↵</kbd>
            </span>
          </div>
        </div>

        {/* RIGHT: Imagery (desktop only) */}
        <div className="ci-side"><FlowSidePanel idx={idx} step={step} data={data} /></div>
      </div>
    </div>
  );
}

function FlowHeader({ idx, total }) {
  const pct = ((idx + 1) / total) * 100;
  return (
    <header className="ci-header" style={{
      borderBottom: '1px solid var(--line)',
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      background: 'rgba(250,247,242,0.86)', backdropFilter: 'blur(18px)',
      position: 'sticky', top: 0, zIndex: 10,
    }}>
      <style>{`
        .ci-header { padding: 16px 18px; }
        .ci-header .ci-progress { margin: 0 14px; }
        @media (min-width: 900px) {
          .ci-header { padding: 20px 40px; }
          .ci-header .ci-progress { margin: 0 32px; }
        }
      `}</style>
      <a href="index.html" style={{ display: 'flex', alignItems: 'center', gap: 10, flexShrink: 0 }}>
        <img src="../../assets/novus-logo-mark.jpg" style={{ height: 30, borderRadius: 4 }} alt="Novus" />
        <div style={{ display: 'flex', flexDirection: 'column', lineHeight: 1.1 }}>
          <span style={{ fontWeight: 700, letterSpacing: '0.18em', fontSize: 11, color: 'var(--navy-900)' }}>NOVUS</span>
          <span style={{ fontWeight: 500, letterSpacing: '0.12em', fontSize: 8, color: 'var(--ink-600)' }}>RESIDENTIALS</span>
        </div>
      </a>

      <div className="ci-progress" style={{ flex: 1, maxWidth: 420, position: 'relative' }}>
        <div style={{ height: 4, background: 'var(--sand-200)', borderRadius: 999, overflow: 'hidden' }}>
          <div style={{
            width: `${pct}%`, height: '100%',
            background: 'linear-gradient(90deg, var(--sun-coral), var(--sun-amber))',
            transition: 'width 380ms var(--ease-novus)',
          }} />
        </div>
        <div style={{
          marginTop: 6, fontSize: 11, color: 'var(--ink-500)',
          letterSpacing: '0.14em', textTransform: 'uppercase', fontWeight: 600,
        }}>{Math.round(pct)}% complete · {total - idx - 1} questions left</div>
      </div>

      <a href="contact.html" style={{
        fontSize: 13, color: 'var(--ink-700)',
        display: 'inline-flex', alignItems: 'center', gap: 6,
      }}>Need help? <strong style={{ color: 'var(--navy-900)' }}>WhatsApp Miguel</strong></a>
    </header>
  );
}

function FlowSidePanel({ idx, step, data }) {
  // rotate imagery / quotes per question group
  const panels = {
    'Welcome to Novus': {
      img: '../../assets/properties/aria-on-the-bay-living-room.png',
      quote: 'In luxury, the welcome begins before you arrive.',
      attr: 'Miguel Cárdenas · Founder, Novus Residentials',
    },
    'Your details': {
      img: '../../assets/properties/villa-gaia-pool.png',
      quote: 'We keep a private file on every guest — so a return visit feels like coming home.',
      attr: 'Marina Acosta · Head Concierge',
    },
    'Identity': {
      img: '../../assets/properties/aston-martin-balcony.png',
      quote: 'Verification takes 60 seconds. Then your door becomes your phone, and your phone becomes a key.',
      attr: 'Trust & Safety · Novus',
    },
    'Your party': {
      img: '../../assets/properties/villa-helios-dining.png',
      quote: 'Tell us names. We\u2019ll set the table.',
      attr: '',
    },
    'Arrival': {
      img: '../../assets/properties/villa-olimpo-view.png',
      quote: 'When you cross the threshold, everything is already in place — the lights, the cool air, the music low.',
      attr: '',
    },
    'The trip': {
      img: '../../assets/properties/villa-eros-bedroom.png',
      quote: 'Every Miami trip is its own kind of story. Ours is to help you live it.',
      attr: '',
    },
    'Concierge': {
      img: '../../assets/properties/villa-artemis-kitchen.png',
      quote: 'The chef, the captain, the florist — we know them all by first name.',
      attr: 'Concierge desk · 24/7',
    },
    'The fine print': {
      img: '../../assets/properties/villa-gaia-living-room.png',
      quote: 'A clear agreement is the foundation of a good stay.',
      attr: '',
    },
    'Final step': {
      img: '../../assets/properties/aria-on-the-bay-bedroom.png',
      quote: 'Nos vemos pronto.',
      attr: 'See you soon — your Miami arrival, designed.',
    },
  };

  const panel = panels[step.eyebrow] || panels['Welcome to Novus'];

  return (
    <div style={{
      position: 'relative', overflow: 'hidden',
      background: 'var(--navy-900)',
    }}>
      <img src={panel.img}
        onError={(e) => { e.target.style.display = 'none'; }}
        style={{
          position: 'absolute', inset: 0, width: '100%', height: '100%',
          objectFit: 'cover', opacity: 0.78,
          transition: 'opacity 600ms var(--ease-novus)',
        }} alt="" />
      <div style={{
        position: 'absolute', inset: 0,
        background: 'linear-gradient(180deg, rgba(15,42,66,0.32) 0%, rgba(15,42,66,0.78) 100%)',
      }} />

      <div style={{
        position: 'relative', height: '100%',
        display: 'flex', flexDirection: 'column', justifyContent: 'flex-end',
        padding: '80px 64px', color: '#fff',
      }}>
        <div style={{
          width: 32, height: 1, background: 'var(--sun-amber)', marginBottom: 24,
        }} />
        <blockquote style={{
          margin: 0, fontFamily: 'var(--font-display)', fontWeight: 400,
          fontSize: 'clamp(22px, 1.8vw, 28px)', lineHeight: 1.35,
          fontStyle: 'italic', textWrap: 'balance',
        }}>"{panel.quote}"</blockquote>
        {panel.attr && (
          <div style={{
            marginTop: 18, fontSize: 12, letterSpacing: '0.14em',
            textTransform: 'uppercase', fontWeight: 600,
            color: 'var(--sun-amber)',
          }}>{panel.attr}</div>
        )}

        {/* Concierge contact card */}
        <div style={{
          marginTop: 40, padding: '16px 18px',
          background: 'rgba(255,255,255,0.08)',
          backdropFilter: 'blur(18px)',
          borderRadius: 14, border: '1px solid rgba(255,255,255,0.18)',
          display: 'flex', alignItems: 'center', gap: 14,
        }}>
          <div style={{
            width: 44, height: 44, borderRadius: 999,
            background: 'linear-gradient(135deg, var(--sun-coral), var(--sun-amber))',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontFamily: 'var(--font-display)', fontSize: 18, fontWeight: 500,
          }}>S</div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 13, fontWeight: 500 }}>Miguel is online</div>
            <div style={{ fontSize: 11, color: 'rgba(255,255,255,0.7)' }}>
              Avg. reply: 4 min · English / Español
            </div>
          </div>
          <button style={{
            padding: '8px 14px', borderRadius: 999, border: '1px solid rgba(255,255,255,0.32)',
            background: 'transparent', color: '#fff', fontSize: 12, cursor: 'pointer',
            letterSpacing: '0.06em',
          }}>WhatsApp →</button>
        </div>
      </div>
    </div>
  );
}

function StepInput({ step, value, set, onAdvance, skipGuests }) {
  if (step.kind === 'reservation' || step.kind === 'text' || step.kind === 'email' || step.kind === 'tel') {
    return (
      <input type={step.kind === 'reservation' ? 'text' : step.kind}
        value={value || ''}
        onChange={e => set(e.target.value)}
        placeholder={step.placeholder}
        autoFocus
        style={{
          width: '100%', padding: '14px 0', border: 0,
          borderBottom: '2px solid var(--sun-coral)',
          background: 'transparent', fontSize: 28,
          color: 'var(--navy-900)', outline: 'none',
          fontFamily: 'var(--font-text)', fontWeight: 400,
        }} />
    );
  }

  if (step.kind === 'textarea') {
    return (
      <textarea value={value || ''} onChange={e => set(e.target.value)}
        placeholder={step.placeholder} rows={4} autoFocus
        style={{
          width: '100%', padding: '14px 16px',
          border: '1.5px solid var(--line)', borderRadius: 12,
          background: '#fff', fontSize: 16, color: 'var(--navy-900)',
          outline: 'none', resize: 'vertical',
          fontFamily: 'var(--font-text)', lineHeight: 1.5,
        }} />
    );
  }

  if (step.kind === 'file') {
    const onPickId = (e) => {
      const f = e.target.files && e.target.files[0];
      if (f) set(f.name || 'id.jpg');
    };
    return (
      <label style={{
        display: 'block', padding: 36, border: `1.5px dashed ${value ? 'var(--sun-coral)' : 'var(--line)'}`,
        borderRadius: 16, background: value ? 'rgba(252,172,100,0.08)' : 'rgba(255,255,255,0.4)',
        cursor: 'pointer', textAlign: 'center',
        transition: 'all 200ms var(--ease-novus)',
      }}>
        <input type="file" accept="image/*,application/pdf" capture="environment" onChange={onPickId} style={{ display: 'none' }} />
        <div style={{
          width: 56, height: 56, borderRadius: 999, margin: '0 auto 16px',
          background: value ? 'var(--sun-coral)' : 'var(--sand-200)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          color: value ? '#fff' : 'var(--ink-500)',
        }}>
          {value ? (
            <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12l5 5L20 7" /></svg>
          ) : (
            <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M17 8l-5-5-5 5M12 3v12" /></svg>
          )}
        </div>
        <div style={{ fontSize: 16, fontWeight: 500, color: 'var(--navy-900)' }}>
          {value ? 'Government ID uploaded' : 'Tap to photograph or upload your ID'}
        </div>
        <div style={{ fontSize: 13, color: 'var(--ink-500)', marginTop: 6 }}>
          {value ? 'Looks good. Tap continue to verify.' : 'Passport, driver\u2019s license, or national ID · JPG, PNG, PDF'}
        </div>
      </label>
    );
  }

  if (step.kind === 'selfie') {
    // Real capture: opens the front camera on mobile (capture="user"); shows a
    // live preview of the chosen photo. Falls back to gallery on desktop.
    const preview = value && typeof value === 'object' ? value.url : null;
    const onPick = (e) => {
      const f = e.target.files && e.target.files[0];
      if (f) set({ name: f.name, url: URL.createObjectURL(f) });
    };
    return (
      <div style={{ display: 'flex', justifyContent: 'center', padding: '20px 0' }}>
        <label style={{
          width: 220, height: 220, borderRadius: '50%', cursor: 'pointer',
          background: preview ? `center/cover url('${preview}')`
            : (value ? 'linear-gradient(135deg, var(--sun-coral), var(--sun-amber))' : 'var(--sand-100)'),
          border: `2px dashed ${value ? 'transparent' : 'var(--sun-coral)'}`,
          display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 10,
          color: value ? '#fff' : 'var(--ink-700)', position: 'relative', overflow: 'hidden',
          transition: 'all 200ms var(--ease-novus)',
          boxShadow: value ? '0 12px 28px rgba(252,172,100,0.42)' : 'none',
        }}>
          <input type="file" accept="image/*" capture="user" onChange={onPick} style={{ display: 'none' }} />
          {preview ? (
            <div style={{ position: 'absolute', inset: 0, background: 'rgba(15,42,66,0.28)', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 8, color: '#fff' }}>
              <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12l5 5L20 7" /></svg>
              <div style={{ fontSize: 12, fontWeight: 600 }}>Retake</div>
            </div>
          ) : (
            <>
              <svg width="36" height="36" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="3" /><path d="M22 12s-3.5-7-10-7-10 7-10 7 3.5 7 10 7 10-7 10-7z" /></svg>
              <div style={{ fontSize: 13, fontWeight: 500 }}>Tap to take selfie</div>
              <div style={{ fontSize: 11, color: 'var(--ink-500)' }}>Uses your front camera</div>
            </>
          )}
        </label>
      </div>
    );
  }

  if (step.kind === 'guests') {
    const guests = value || [''];
    return (
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        {guests.map((g, i) => (
          <div key={i} style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
            <div style={{
              width: 32, height: 32, borderRadius: 999, background: 'var(--sand-100)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontSize: 13, color: 'var(--ink-700)', fontWeight: 500,
            }}>{i + 1}</div>
            <input value={g} onChange={e => { const copy=[...guests]; copy[i]=e.target.value; set(copy); }}
              placeholder={`Guest ${i + 1} first name`}
              style={{
                flex: 1, padding: '12px 16px',
                border: '1.5px solid var(--line)', borderRadius: 10,
                background: '#fff', fontSize: 15, outline: 'none',
                fontFamily: 'var(--font-text)',
              }} />
            {guests.length > 1 && (
              <button onClick={() => set(guests.filter((_, j) => j !== i))} style={{
                background: 'transparent', border: 0, color: 'var(--ink-500)',
                cursor: 'pointer', fontSize: 18, padding: '0 8px',
              }}>×</button>
            )}
          </div>
        ))}
        <div style={{ display: 'flex', gap: 10, marginTop: 8 }}>
          <button onClick={() => set([...guests, ''])} style={{
            background: 'transparent', border: '1.5px dashed var(--line)',
            color: 'var(--ink-700)', padding: '10px 16px', borderRadius: 10,
            fontSize: 13, cursor: 'pointer',
          }}>+ Add another guest</button>
          <button onClick={() => { skipGuests(); set([{ skip: true }]); }} style={{
            background: 'transparent', border: 0,
            color: 'var(--ink-500)', padding: '10px 8px',
            fontSize: 13, cursor: 'pointer',
          }}>I'm traveling solo</button>
        </div>
      </div>
    );
  }

  if (step.kind === 'choice') {
    return (
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 10 }}>
        {step.options.map((o, i) => {
          const v = typeof o === 'string' ? o : o.value;
          const lbl = typeof o === 'string' ? o : o.label;
          const sub = typeof o === 'string' ? null : o.sub;
          const selected = value === v;
          return (
            <button key={v} onClick={() => { set(v); setTimeout(onAdvance, 180); }} style={{
              padding: '18px 20px', textAlign: 'left',
              borderRadius: 14,
              border: `1.5px solid ${selected ? 'var(--sun-coral)' : 'var(--line)'}`,
              background: selected ? 'rgba(252,172,100,0.10)' : '#fff',
              color: 'var(--navy-900)', cursor: 'pointer',
              display: 'flex', alignItems: 'center', gap: 14,
              transition: 'all 160ms var(--ease-novus)',
            }}>
              <div style={{
                width: 28, height: 28, borderRadius: 8,
                border: `1.5px solid ${selected ? 'var(--sun-coral)' : 'var(--line)'}`,
                background: selected ? 'var(--sun-coral)' : '#fff',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                color: selected ? '#fff' : 'var(--ink-500)',
                fontSize: 12, fontWeight: 600, flexShrink: 0,
              }}>{selected ? '✓' : String.fromCharCode(65 + i)}</div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 15, fontWeight: 500 }}>{lbl}</div>
                {sub && <div style={{ fontSize: 12, color: 'var(--ink-500)', marginTop: 2 }}>{sub}</div>}
              </div>
            </button>
          );
        })}
      </div>
    );
  }

  if (step.kind === 'multichoice') {
    const selected = value || [];
    const toggle = (v) => {
      if (selected.includes(v)) set(selected.filter(x => x !== v));
      else set([...selected, v]);
    };
    return (
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 10 }}>
        {step.options.map((o, i) => {
          const isOn = selected.includes(o.value);
          return (
            <button key={o.value} onClick={() => toggle(o.value)} style={{
              padding: '16px 18px', textAlign: 'left',
              borderRadius: 14,
              border: `1.5px solid ${isOn ? 'var(--sun-coral)' : 'var(--line)'}`,
              background: isOn ? 'rgba(252,172,100,0.10)' : '#fff',
              cursor: 'pointer',
              display: 'flex', alignItems: 'center', gap: 12,
              transition: 'all 160ms var(--ease-novus)',
            }}>
              <div style={{
                width: 24, height: 24, borderRadius: 6,
                border: `1.5px solid ${isOn ? 'var(--sun-coral)' : 'var(--line)'}`,
                background: isOn ? 'var(--sun-coral)' : '#fff',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                color: '#fff', flexShrink: 0,
              }}>{isOn && '✓'}</div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 14, fontWeight: 500, color: 'var(--navy-900)' }}>{o.label}</div>
                {o.sub && <div style={{ fontSize: 11, color: 'var(--ink-500)', marginTop: 2 }}>{o.sub}</div>}
              </div>
            </button>
          );
        })}
      </div>
    );
  }

  if (step.kind === 'rules') {
    return (
      <div>
        <div style={{
          background: '#fff', border: '1px solid var(--line)',
          borderRadius: 14, padding: '8px 22px', marginBottom: 18,
        }}>
          {HOUSE_RULES.map(([k, v], i) => (
            <div key={k} style={{
              padding: '14px 0',
              borderBottom: i < HOUSE_RULES.length - 1 ? '1px solid var(--line)' : 'none',
            }}>
              <div style={{ fontWeight: 500, fontSize: 14, color: 'var(--navy-900)' }}>{k}</div>
              <div style={{ fontSize: 13, color: 'var(--ink-700)', marginTop: 2, lineHeight: 1.5 }}>{v}</div>
            </div>
          ))}
        </div>
        <label style={{
          display: 'flex', gap: 12, cursor: 'pointer',
          alignItems: 'flex-start', padding: 14,
          background: value ? 'rgba(252,172,100,0.10)' : '#fff',
          border: `1.5px solid ${value ? 'var(--sun-coral)' : 'var(--line)'}`,
          borderRadius: 12,
          transition: 'all 160ms var(--ease-novus)',
        }}>
          <input type="checkbox" checked={!!value} onChange={e => set(e.target.checked)}
            style={{ marginTop: 3, accentColor: 'var(--sun-coral)', width: 18, height: 18 }} />
          <span style={{ fontSize: 14, color: 'var(--navy-900)', lineHeight: 1.55 }}>
            I have read and accept the house rules, the rental agreement, and the cancellation policy.
          </span>
        </label>
      </div>
    );
  }

  if (step.kind === 'sign') {
    return (
      <div>
        <div onClick={() => set('signed')} style={{
          background: '#fff', border: `1.5px dashed ${value ? 'var(--sun-coral)' : 'var(--line)'}`,
          borderRadius: 16, padding: '40px 24px', textAlign: 'center',
          cursor: 'pointer', minHeight: 160,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          transition: 'all 200ms var(--ease-novus)',
          background: value ? 'rgba(252,172,100,0.06)' : '#fff',
        }}>
          {value ? (
            <div style={{
              fontFamily: 'var(--font-display)', fontStyle: 'italic',
              fontSize: 56, color: 'var(--navy-900)', lineHeight: 1,
            }}>{(typeof value === 'string' && value !== 'signed') ? value : (window._checkInData?.name || 'Your Name')}</div>
          ) : (
            <div>
              <div style={{
                color: 'var(--ink-500)', fontSize: 12,
                letterSpacing: '0.18em', textTransform: 'uppercase',
                fontWeight: 600, marginBottom: 8,
              }}>Sign here</div>
              <div style={{ fontSize: 14, color: 'var(--ink-700)' }}>
                Tap to sign with your full name
              </div>
            </div>
          )}
        </div>
        <div style={{
          marginTop: 12, fontSize: 11, color: 'var(--ink-500)',
          display: 'flex', gap: 18, flexWrap: 'wrap',
        }}>
          <span>· Legally binding electronic signature</span>
          <span>· Audit log timestamped at submission</span>
          <span>· PDF emailed to you on completion</span>
        </div>
      </div>
    );
  }

  return null;
}

function SuccessScreen({ data }) {
  React.useEffect(() => { window.scrollTo(0, 0); }, []);
  const name = (data.name || '').split(' ')[0] || 'there';
  return (
    <div style={{
      minHeight: '100vh', background: 'var(--bg-page)',
      display: 'flex', flexDirection: 'column',
    }}>
      <header style={{
        padding: '20px 40px', borderBottom: '1px solid var(--line)',
        background: 'rgba(250,247,242,0.86)', backdropFilter: 'blur(18px)',
      }}>
        <a href="index.html" style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <img src="../../assets/novus-logo-mark.jpg" style={{ height: 32, borderRadius: 4 }} alt="Novus" />
          <div style={{ display: 'flex', flexDirection: 'column', lineHeight: 1.1 }}>
            <span style={{ fontWeight: 700, letterSpacing: '0.18em', fontSize: 11, color: 'var(--navy-900)' }}>NOVUS</span>
            <span style={{ fontWeight: 500, letterSpacing: '0.12em', fontSize: 8, color: 'var(--ink-600)' }}>RESIDENTIALS</span>
          </div>
        </a>
      </header>

      <div style={{ flex: 1, display: 'grid', gridTemplateColumns: '1fr 1fr' }}>
        <div style={{
          display: 'flex', flexDirection: 'column', justifyContent: 'center',
          padding: '64px 80px', maxWidth: 720,
        }}>
          <div style={{
            width: 64, height: 64, borderRadius: 999,
            background: 'linear-gradient(135deg, var(--sun-coral), var(--sun-amber))',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            marginBottom: 28, boxShadow: '0 10px 28px rgba(252,172,100,0.4)',
          }}>
            <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12l5 5L20 7" /></svg>
          </div>
          <div className="overline" style={{ color: 'var(--sun-coral)', marginBottom: 12 }}>Check-in complete</div>
          <h1 style={{
            fontFamily: 'var(--font-display)', fontWeight: 400,
            fontSize: 'clamp(40px, 5vw, 64px)', color: 'var(--navy-900)',
            margin: '0 0 16px', letterSpacing: '-0.02em', lineHeight: 1.05,
          }}>
            You're all set, <em style={{ fontStyle: 'italic' }}>{name}.</em>
          </h1>
          <p style={{
            color: 'var(--ink-700)', fontSize: 17, lineHeight: 1.65,
            margin: '0 0 32px', maxWidth: 540, textWrap: 'pretty',
          }}>
            Your door code activates at <strong style={{ color: 'var(--navy-900)' }}>4 PM on your arrival day</strong>.
            We've sent the welcome packet to your email — Wi-Fi password, gate code, the works.
            Miguel will WhatsApp you 24 hours before you land.
          </p>

          <div style={{
            padding: 22, background: '#fff',
            border: '1px solid var(--line)', borderRadius: 16,
            marginBottom: 28,
          }}>
            <div className="overline" style={{ marginBottom: 14 }}>What happens next</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
              {[
                ['Now', 'Confirmation email + signed rental PDF sent to your inbox.'],
                ['T - 48 h', 'Miguel sends a personal note with arrival tips.'],
                ['T - 24 h', 'Final reminder + your door code (active at 4 PM).'],
                ['Arrival', 'Walk in. The lights, A/C, and music are already set.'],
              ].map(([when, what]) => (
                <div key={when} style={{ display: 'flex', gap: 16 }}>
                  <div style={{
                    minWidth: 72, fontSize: 11, fontWeight: 600,
                    letterSpacing: '0.14em', textTransform: 'uppercase',
                    color: 'var(--sun-coral)', paddingTop: 2,
                  }}>{when}</div>
                  <div style={{ fontSize: 14, color: 'var(--ink-700)', lineHeight: 1.55 }}>{what}</div>
                </div>
              ))}
            </div>
          </div>

          <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
            <a href="../guest-portal/index.html" className="btn btn-primary" style={{ padding: '13px 22px', fontSize: 14 }}>
              Open the guest portal →
            </a>
            <a href="index.html" className="btn" style={{
              padding: '13px 22px', fontSize: 14,
              background: 'transparent', color: 'var(--navy-900)',
              border: '1px solid var(--line)',
            }}>Back to home</a>
          </div>
        </div>

        <div style={{
          position: 'relative', overflow: 'hidden',
          background: 'var(--navy-900)',
        }}>
          <img src="../../assets/properties/villa-gaia-pool.png"
            style={{
              position: 'absolute', inset: 0, width: '100%', height: '100%',
              objectFit: 'cover', opacity: 0.85,
            }} alt="" />
          <div style={{
            position: 'absolute', inset: 0,
            background: 'linear-gradient(180deg, rgba(15,42,66,0.2) 0%, rgba(15,42,66,0.78) 100%)',
          }} />
          <div style={{
            position: 'relative', height: '100%',
            display: 'flex', flexDirection: 'column', justifyContent: 'flex-end',
            padding: '80px 64px', color: '#fff',
          }}>
            <div style={{ width: 32, height: 1, background: 'var(--sun-amber)', marginBottom: 24 }} />
            <div style={{
              fontFamily: 'var(--font-display)', fontStyle: 'italic',
              fontSize: 'clamp(40px, 4vw, 56px)', lineHeight: 1.1,
              textWrap: 'balance', margin: 0,
            }}>Nos vemos pronto.</div>
            <div style={{
              marginTop: 16, fontSize: 13, letterSpacing: '0.14em',
              textTransform: 'uppercase', fontWeight: 600,
              color: 'var(--sun-amber)',
            }}>See you in Miami — your villa is ready.</div>
          </div>
        </div>
      </div>
    </div>
  );
}

window.CheckInFlow = CheckInFlow;
