// Screens 2a/b/c — Onboarding

function OnboardingStep1({ user, setUser, onNext, onSkip }) {
  const roles = ['MOH', 'Bridesmaid', 'Bride', 'Close friend', 'Someone else'];
  const regions = Object.entries(REGIONS).map(([k, r]) => ({ k, flag: r.flag, cur: r.currency }));
  const upd = (k, v) => setUser({ ...user, [k]: v });

  const canContinue = !!(user.name && user.name.trim() && user.brideName && user.brideName.trim() && user.role && user.region);

  return (
    <OnboardingShell step={1} title={<>Tell us about <i>the bach.</i></>} onNext={onNext} onSkip={onSkip} canContinue={canContinue}>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginBottom: 24 }}>
        <InputField label="Your name" value={user.name} onChange={(v) => upd('name', v)} placeholder="Alex"/>
        <InputField label="Bride's name" value={user.brideName} onChange={(v) => upd('brideName', v)} placeholder="Jules"/>
      </div>
      <SubLabel>Your role</SubLabel>
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginBottom: 24 }}>
        {roles.map(r => (
          <button key={r} onClick={() => upd('role', r)} style={{
            background: user.role === r ? TBL.jam : '#fff',
            color: user.role === r ? TBL.cream : TBL.ink,
            border: `1.5px solid ${user.role === r ? TBL.jam : TBL.line}`,
            padding: '11px 16px', borderRadius: 999,
            fontFamily: SANS, fontSize: 14, fontWeight: 500, cursor: 'pointer',
            letterSpacing: -0.1, whiteSpace: 'nowrap',
          }}>{r}</button>
        ))}
      </div>
      <SubLabel>Where's the hen?</SubLabel>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
        {regions.map(r => {
          const active = user.region === r.k;
          return (
            <button key={r.k} onClick={() => upd('region', r.k)} style={{
              background: active ? 'rgba(224,90,61,0.06)' : '#fff',
              border: active ? `1.5px solid ${TBL.jam}` : `1px solid ${TBL.line}`,
              borderRadius: 14, padding: '14px 12px', cursor: 'pointer', textAlign: 'left',
              display: 'flex', alignItems: 'center', gap: 10, position: 'relative',
            }}>
              <div style={{ fontSize: 22 }}>{r.flag}</div>
              <div style={{ flex: 1 }}>
                <div style={{ fontFamily: SANS, fontSize: 14, color: TBL.ink, fontWeight: 500 }}>{r.k}</div>
                <div style={{ fontFamily: MONO, fontSize: 10, color: TBL.mute, letterSpacing: 1 }}>{r.cur}</div>
              </div>
              {active && (
                <div style={{ position: 'absolute', top: 8, right: 8, width: 18, height: 18, borderRadius: 999, background: TBL.jam, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                  <svg width="10" height="10" viewBox="0 0 12 12"><path d="M2 6 L5 9 L10 3" stroke="#fff" strokeWidth="2" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>
                </div>
              )}
            </button>
          );
        })}
      </div>
    </OnboardingShell>
  );
}

function OnboardingStep2({ dates, setDates, onNext, onSkip }) {
  const upd = (k, v) => setDates({ ...dates, [k]: v });
  const canContinue = !!(dates.start && dates.end);

  // Derived: suggested theme count = nights between start and end + 1 (i.e. # of days inclusive)
  const suggested = React.useMemo(() => {
    if (!dates.start || !dates.end) return 3;
    const d1 = new Date(dates.start);
    const d2 = new Date(dates.end);
    if (isNaN(d1.getTime()) || isNaN(d2.getTime()) || d2 < d1) return 3;
    const days = Math.round((d2 - d1) / (1000 * 60 * 60 * 24)) + 1;
    return Math.max(1, Math.min(12, days));
  }, [dates.start, dates.end]);

  // When the date range changes and the user hasn't manually touched the stepper, align count with suggestion
  React.useEffect(() => {
    if (!dates.countTouched) setDates(d => ({ ...d, count: suggested }));
  }, [suggested]); // eslint-disable-line

  const changeCount = (v) => setDates({ ...dates, count: v, countTouched: true });

  return (
    <OnboardingShell step={2} title={<>When's <i>the hen?</i></>} onNext={onNext} onSkip={onSkip} canContinue={canContinue}>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginBottom: 24 }}>
        <DateInput label="Start" value={dates.start} onChange={(v) => upd('start', v)}/>
        <DateInput label="End"   value={dates.end}   onChange={(v) => upd('end', v)}/>
      </div>
      <div style={{ background: 'rgba(139,168,146,0.14)', border: `1px solid rgba(139,168,146,0.4)`, borderRadius: 16, padding: 18, marginBottom: 28 }}>
        <Eyebrow color={TBL.sage} style={{ marginBottom: 10 }}>Your weekend</Eyebrow>
        <div style={{ fontFamily: SERIF, fontSize: 22, fontStyle: 'italic', color: TBL.ink, marginBottom: 14, letterSpacing: -0.5 }}>
          We suggest <b style={{ color: TBL.jam, fontStyle: 'normal' }}>{suggested} theme{suggested === 1 ? '' : 's'}</b>{suggested === 1 ? '' : ' — one per day'}.
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 10 }}>
          <Stepper val={dates.count} min={1} max={12} onChange={changeCount}/>
          <div style={{ fontSize: 13, color: TBL.ink }}>
            {dates.count === suggested ? 'themes' : (
              <span>themes · <span style={{ color: TBL.subtle }}>you've picked {dates.count}</span></span>
            )}
          </div>
        </div>
        <div style={{ fontSize: 12, color: TBL.subtle, lineHeight: 1.4 }}>
          One theme per day is default — but doubling up (brunch theme + evening theme) is common.
        </div>
      </div>
      <div style={{ marginTop: 8 }}>
        <SubLabel>Guests (approx.)</SubLabel>
        <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
          <Stepper val={dates.guests} min={2} max={30} onChange={(v) => upd('guests', v)}/>
          <div style={{ fontSize: 13, color: TBL.subtle }}>Helps us size quantities and split per-guest costs</div>
        </div>
      </div>
    </OnboardingShell>
  );
}

const VIBE_TILES = [
  { key: 'coastal', n: 'Coastal pool party', em: '🐚', grad: THEME_GRADIENTS.coastal, palette: ['#2d5d8a','#fbeee0','#e8d4c5','#f3b94a'] },
  { key: 'disco', n: 'Disco & sparkles', em: '✨', grad: THEME_GRADIENTS.disco, palette: ['#e8a3c4','#c56d98','#7a4e8e','#f3b94a'] },
  { key: 'nashville', n: 'Nashville western', em: '🤠', grad: THEME_GRADIENTS.nashville, palette: ['#f3b94a','#e05a3d','#2a1a1f'] },
  { key: 'tropical', n: 'Tropical luxe brunch', em: '🌴', grad: THEME_GRADIENTS.tropical, palette: ['#f5e3cf','#e8c99a','#c88fa4'] },
  { key: 'ski', n: 'Ski chalet', em: '❄️', grad: THEME_GRADIENTS.ski, palette: ['#dce4ea','#c88fa4','#2a1a1f'] },
  { key: 'vegas', n: 'Vegas neon', em: '🎰', grad: THEME_GRADIENTS.vegas, palette: ['#7a4e8e','#e05a3d','#f3b94a'] },
  { key: 'garden', n: 'English garden', em: '🌹', grad: THEME_GRADIENTS.garden, palette: ['#c6d4b8','#f0d4c0','#c88fa4'] },
  { key: 'parisian', n: 'Parisian affair', em: '🥂', grad: THEME_GRADIENTS.parisian, palette: ['#e8d8c4','#b8939a','#fbeee0'] },
];

function OnboardingStep3({ pendingVibe, setPendingVibe, customTiles, overrides, onNext, onCustom, onSkip, onBrowseAll }) {
  const canContinue = !!pendingVibe;
  // Apply name/emoji overrides to built-in tiles
  const builtInMerged = VIBE_TILES.map(t => {
    const o = overrides && overrides[t.key];
    if (!o) return t;
    return {
      ...t,
      n: o.n || t.n,
      em: o.em || t.em,
      description: o.description || t.description,
      palette: o.palette || t.palette,
      grad: o.grad || t.grad,
    };
  });
  const allTiles = [...builtInMerged, ...((customTiles || []).map(t => ({
    key: t.key, n: t.n || t.name, em: t.em, grad: t.grad, palette: t.palette, description: t.description,
  })))];
  return (
    <OnboardingShell step={3} title={<>Pick a <i>vibe</i> to start.</>} onNext={onNext} onSkip={onSkip} canContinue={canContinue}>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, marginBottom: 14 }}>
        {allTiles.map(t => {
          const active = pendingVibe && pendingVibe.key === t.key;
          return (
            <button key={t.key} onClick={() => setPendingVibe(t)} style={{
              background: t.grad, border: active ? `2px solid ${TBL.jam}` : `1px solid ${TBL.line}`,
              borderRadius: 14, padding: 14, aspectRatio: '1/0.95', cursor: 'pointer', textAlign: 'left',
              display: 'flex', flexDirection: 'column', justifyContent: 'space-between', position: 'relative',
              boxShadow: active ? '0 4px 16px rgba(224,90,61,0.25)' : 'none',
            }}>
              <div style={{ fontSize: 26 }}>{t.em}</div>
              <div style={{ fontFamily: SERIF, fontSize: 15, fontStyle: 'italic', color: TBL.ink, lineHeight: 1.1, letterSpacing: -0.3 }}>{t.n}</div>
              {active && (
                <div style={{ position: 'absolute', top: 8, right: 8, width: 18, height: 18, borderRadius: 999, background: TBL.jam, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                  <svg width="10" height="10" viewBox="0 0 12 12"><path d="M2 6 L5 9 L10 3" stroke="#fff" strokeWidth="2" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>
                </div>
              )}
            </button>
          );
        })}
      </div>
      <button onClick={onBrowseAll} style={{
        background: 'none', border: 'none', width: '100%', padding: '4px 0 14px',
        fontFamily: SANS, fontSize: 13, color: TBL.jam, cursor: 'pointer',
        textAlign: 'center', textDecoration: 'underline', textUnderlineOffset: 3,
      }}>See the full theme library →</button>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, margin: '4px 0 14px' }}>
        <div style={{ flex: 1, height: 1, background: TBL.line }}/>
        <div style={{ fontFamily: MONO, fontSize: 10, color: TBL.mute, letterSpacing: 2 }}>OR</div>
        <div style={{ flex: 1, height: 1, background: TBL.line }}/>
      </div>
      <button onClick={onCustom} style={{
        width: '100%', background: `linear-gradient(120deg, ${TBL.citrus} 0%, ${TBL.jam} 50%, ${TBL.sky} 100%)`,
        color: TBL.cream, border: 'none', borderRadius: 14, padding: '16px 18px',
        textAlign: 'left', cursor: 'pointer', position: 'relative', overflow: 'hidden',
      }}>
        {Array.from({length: 8}).map((_, i) => (
          <div key={i} style={{ position: 'absolute', width: 3, height: 3, borderRadius: 999, background: '#fff', left: `${(i*43)%95}%`, top: `${(i*29)%95}%`, opacity: 0.5 }}/>
        ))}
        <div style={{ position: 'relative' }}>
          <div style={{ fontSize: 22, marginBottom: 4 }}>✨</div>
          <div style={{ fontFamily: SERIF, fontSize: 18, fontStyle: 'italic', lineHeight: 1.1, marginBottom: 2 }}>Something else in mind?</div>
          <div style={{ fontSize: 12, opacity: 0.9 }}>Describe your own vibe — we'll build from scratch.</div>
        </div>
      </button>
    </OnboardingShell>
  );
}

// ── Shared shell ──
function OnboardingShell({ step, title, children, onNext, onSkip, canContinue }) {
  const disabled = canContinue === false;
  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: TBL.cream }}>
      {/* Top: progress + skip */}
      <div style={{ padding: '22px 22px 0' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10 }}>
          <div style={{ fontFamily: MONO, fontSize: 10, letterSpacing: 2, color: TBL.mute, whiteSpace: 'nowrap' }}>STEP {step} / 3</div>
          <button onClick={onSkip} style={{ background: 'none', border: 'none', fontFamily: SANS, fontSize: 13, color: TBL.mute, cursor: 'pointer' }}>Skip</button>
        </div>
        <div style={{ display: 'flex', gap: 4 }}>
          {[1,2,3].map(n => (
            <div key={n} style={{ flex: 1, height: 3, borderRadius: 999, background: n <= step ? TBL.jam : TBL.line }}/>
          ))}
        </div>
      </div>

      {/* Title */}
      <div style={{ padding: '32px 22px 20px' }}>
        <div style={{ fontFamily: SERIF, fontSize: 38, lineHeight: 0.98, color: TBL.ink, letterSpacing: -1.2 }}>
          {title}
        </div>
      </div>

      {/* Body scroll */}
      <div style={{ flex: 1, overflow: 'auto', padding: '0 22px 24px' }}>
        {children}
      </div>

      {/* Sticky continue */}
      <div style={{ padding: '14px 22px 20px', background: TBL.cream, borderTop: `1px solid ${TBL.line}` }}>
        <button
          onClick={disabled ? undefined : onNext}
          disabled={disabled}
          style={{
            background: disabled ? 'rgba(42,26,31,0.15)' : TBL.jam,
            color: disabled ? TBL.mute : TBL.cream,
            border: 'none',
            padding: '17px 28px', borderRadius: 999,
            fontFamily: SANS, fontSize: 15, fontWeight: 500,
            cursor: disabled ? 'not-allowed' : 'pointer',
            width: '100%', letterSpacing: -0.1,
            boxShadow: disabled ? 'none' : '0 1px 2px rgba(224,90,61,0.25), 0 4px 12px rgba(224,90,61,0.2)',
            transition: 'background 0.15s, color 0.15s',
          }}
        >Continue →</button>
        {disabled && (
          <div style={{ fontFamily: SANS, fontSize: 11, color: TBL.mute, textAlign: 'center', marginTop: 8 }}>
            Fill in the fields above to continue
          </div>
        )}
      </div>
    </div>
  );
}

// ── Typeable text input field ──
function InputField({ label, value, onChange, placeholder, type = 'text' }) {
  return (
    <div>
      <SubLabel>{label}</SubLabel>
      <input
        type={type}
        value={value || ''}
        onChange={(e) => onChange(e.target.value)}
        placeholder={placeholder}
        className="tbl-input"
        style={{
          width: '100%',
          background: '#fff',
          border: `1px solid ${TBL.line}`,
          borderRadius: 12,
          padding: '12px 14px',
          fontFamily: SANS,
          fontSize: 15,
          color: TBL.ink,
          outline: 'none',
          transition: 'border-color 0.15s',
        }}
        onFocus={(e) => e.target.style.borderColor = TBL.jam}
        onBlur={(e) => e.target.style.borderColor = TBL.line}
      />
    </div>
  );
}

// ── Native date picker input — renders a calendar popover in all modern browsers ──
function DateInput({ label, value, onChange }) {
  // Format YYYY-MM-DD → "Fri, May 15" for display when filled, otherwise show empty
  return (
    <div>
      <SubLabel>{label}</SubLabel>
      <div style={{ position: 'relative' }}>
        <input
          type="date"
          value={value || ''}
          onChange={(e) => onChange(e.target.value)}
          className="tbl-input tbl-date"
          style={{
            width: '100%',
            background: '#fff',
            border: `1px solid ${TBL.line}`,
            borderRadius: 12,
            padding: '12px 14px',
            fontFamily: SANS,
            fontSize: 15,
            color: value ? TBL.ink : TBL.mute,
            fontStyle: value ? 'normal' : 'italic',
            outline: 'none',
            transition: 'border-color 0.15s',
            WebkitAppearance: 'none',
            appearance: 'none',
          }}
          onFocus={(e) => e.target.style.borderColor = TBL.jam}
          onBlur={(e) => e.target.style.borderColor = TBL.line}
        />
      </div>
    </div>
  );
}

Object.assign(window, { OnboardingStep1, OnboardingStep2, OnboardingStep3, VIBE_TILES, InputField, DateInput });
