// Onboarding — the magical first 30 seconds.

function OnboardingApp() {
  const wedding = useWedding();
  const [step, setStep] = React.useState(0);
  const [basics, setBasics] = React.useState(() => ({
    brides:     wedding.brides     || '',
    groom:      wedding.groom      || '',
    dateISO:    wedding.dateISO    || '',
    city:       wedding.city       || '',
    venue:      wedding.venue      || '',
    guestCount: wedding.guestCount || '',
    budget:     wedding.budget     || '',
  }));
  const [priorities, setPriorities] = React.useState(['elegant', 'intimate']);
  const [stress, setStress] = React.useState(['budget', 'seating']);

  const commitBasics = () => {
    const patch = {
      brides:     basics.brides.trim(),
      groom:      basics.groom.trim(),
      dateISO:    basics.dateISO,
      city:       basics.city.trim(),
      cityShort:  basics.city.trim(),
      venue:      basics.venue.trim(),
      guestCount: Number(basics.guestCount) || 0,
      budget:     Number(basics.budget)     || 0,
    };
    wedding.setWedding(patch);
  };

  const next = () => {
    if (step === 1) commitBasics();
    setStep(s => Math.min(s + 1, 5));
  };
  const back = () => setStep(s => Math.max(s - 1, 0));

  // When onboarding completes, swap in the real app.
  if (step === 5) return <MobileApp/>;

  return (
    <IOSDevice>
      <div style={{
        height: '100%', overflowY: 'auto', overflowX: 'hidden',
        background: W.bg,
      }}>
        <PhoneStatusBarOverlay/>

        <div style={{ paddingTop: 56 }}/>

        {/* Top: step indicator + back */}
        {step > 0 && step < 4 && (
          <div style={{
            padding: '12px 22px 8px',
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          }}>
            <button onClick={back} style={{
              background: 'transparent', border: 'none', cursor: 'pointer',
              fontFamily: FONT_UI, fontSize: 14, color: W.ink2,
              padding: 0, display: 'flex', alignItems: 'center', gap: 4,
            }}>
              <Icon name="chevronL" size={14} color={W.ink2}/>
              Back
            </button>
            <StepDots count={4} active={step - 1}/>
            <div style={{ width: 40 }}/>
          </div>
        )}

        {step === 0 && <Step0Welcome onContinue={next}/>}
        {step === 1 && <Step1Basics values={basics} onChange={setBasics} onContinue={next}/>}
        {step === 2 && <Step2Priorities selected={priorities} onChange={setPriorities} onContinue={next}/>}
        {step === 3 && <Step3Stress selected={stress} onChange={setStress} onContinue={next}/>}
        {step === 4 && <Step4Ready onContinue={next}/>}
      </div>
    </IOSDevice>
  );
}

function StepDots({ count, active }) {
  return (
    <div style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
      {Array.from({ length: count }).map((_, i) => (
        <div key={i} style={{
          width: i === active ? 22 : 6, height: 6, borderRadius: 999,
          background: i === active ? W.ink : '#ddd0b4',
          transition: 'all 250ms ease',
        }}/>
      ))}
    </div>
  );
}

function PrimaryButton({ label, onClick, sub }) {
  const disabled = onClick == null;
  return (
    <div style={{
      position: 'sticky', bottom: 0, padding: '14px 22px 38px',
      background: 'linear-gradient(180deg, rgba(250,246,236,0) 0%, rgba(250,246,236,0.95) 25%, rgba(250,246,236,1) 60%)',
    }}>
      <button onClick={onClick || undefined} disabled={disabled} style={{
        width: '100%',
        background: disabled ? '#d8cdb6' : W.ink,
        color: disabled ? 'rgba(255,255,255,0.78)' : W.bg,
        border: 'none', cursor: disabled ? 'not-allowed' : 'pointer',
        padding: '16px 18px', borderRadius: 18,
        fontFamily: FONT_UI, fontSize: 15, fontWeight: 500,
        display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
        boxShadow: disabled ? 'none' : '0 8px 24px -8px rgba(29,24,18,0.35)',
        transition: 'background 200ms ease',
      }}>
        {label}
        <Icon name="arrow" size={15} color={disabled ? 'rgba(255,255,255,0.78)' : W.bg}/>
      </button>
      {sub && (
        <div style={{
          textAlign: 'center', marginTop: 12,
          fontFamily: FONT_UI, fontSize: 12, color: W.muted,
        }}>{sub}</div>
      )}
    </div>
  );
}

// ─── Step 0: Welcome ────────────────────────────────────────

function Step0Welcome({ onContinue }) {
  return (
    <div style={{
      minHeight: 'calc(100% - 56px)',
      display: 'flex', flexDirection: 'column',
    }}>
      <div style={{
        padding: '40px 22px 0',
        flex: 1, display: 'flex', flexDirection: 'column',
      }}>
        {/* Brand */}
        <div style={{
          fontFamily: FONT_DISPLAY, fontStyle: 'italic', fontSize: 22,
          color: W.ink, letterSpacing: 0.3,
        }}>weddingos</div>

        {/* Illustrative card stack */}
        <div style={{ flex: 1, position: 'relative', marginTop: 36, marginBottom: 24 }}>
          {/* Back card */}
          <div style={{
            position: 'absolute', top: 10, left: 30, right: 30, height: 220,
            background: '#f0e3cc', borderRadius: 22,
            border: `0.5px solid ${W.line}`, transform: 'rotate(-3deg)',
            boxShadow: '0 16px 40px -20px rgba(60,40,20,0.20)',
          }}/>
          <div style={{
            position: 'absolute', top: 4, left: 14, right: 14, height: 220,
            background: '#fbf6ea', borderRadius: 22,
            border: `0.5px solid ${W.line}`, transform: 'rotate(1.5deg)',
            boxShadow: '0 18px 44px -22px rgba(60,40,20,0.25)',
          }}/>
          {/* Front card — countdown preview */}
          <div style={{
            position: 'relative', height: 220,
            background: W.cardDeep, color: '#f5efe2',
            borderRadius: 22, padding: '24px 22px',
            boxShadow: '0 22px 50px -24px rgba(29,24,18,0.5)',
            overflow: 'hidden',
          }}>
            <div style={{
              position: 'absolute', inset: 0, pointerEvents: 'none',
              background: 'radial-gradient(120% 80% at 100% 0%, rgba(199,155,145,0.20), transparent 60%), radial-gradient(80% 60% at 0% 100%, rgba(168,122,79,0.22), transparent 60%)',
            }}/>
            <div style={{ position: 'relative' }}>
              <div style={{
                fontFamily: FONT_UI, fontSize: 9.5, fontWeight: 600,
                letterSpacing: 1.8, textTransform: 'uppercase',
                color: 'rgba(245,239,226,0.55)',
              }}>The Wedding of</div>
              <div style={{
                fontFamily: FONT_DISPLAY, fontSize: 24, fontWeight: 500,
                marginTop: 4, letterSpacing: -0.2,
              }}>You <span style={{ fontStyle: 'italic', opacity: 0.85 }}>&amp;</span> Yours</div>
              <div style={{
                fontFamily: FONT_DISPLAY, fontSize: 90, fontWeight: 400,
                lineHeight: 0.9, letterSpacing: -3, marginTop: 18,
              }}>—</div>
              <div style={{
                fontFamily: FONT_UI, fontSize: 11, fontWeight: 600,
                letterSpacing: 1.6, textTransform: 'uppercase', marginTop: 6,
                color: 'rgba(245,239,226,0.65)',
              }}>Days until your day</div>
            </div>
          </div>
        </div>

        {/* Headline */}
        <div>
          <div style={{
            fontFamily: FONT_DISPLAY, fontSize: 38, fontWeight: 500,
            color: W.ink, lineHeight: 1, letterSpacing: -0.5,
          }}>
            Plan your wedding<br/>
            <span style={{ fontStyle: 'italic' }}>without</span> the chaos.
          </div>
          <div style={{
            fontFamily: FONT_UI, fontSize: 14.5, color: W.ink2,
            lineHeight: 1.5, marginTop: 14, maxWidth: 320,
          }}>
            Budget, guests, seating, vendors — calm, beautiful, and offline-ready.
            No accounts. Set up in two minutes.
          </div>
        </div>

        <div style={{ height: 30 }}/>
      </div>

      <PrimaryButton label="Begin" onClick={onContinue} sub="Takes about two minutes"/>
    </div>
  );
}

// ─── Step 1: Basics ─────────────────────────────────────────

function Step1Basics({ values, onChange, onContinue }) {
  const set = (k, v) => onChange({ ...values, [k]: v });
  const canContinue = values.brides.trim() && values.groom.trim();
  return (
    <div style={{
      minHeight: 'calc(100% - 90px)',
      display: 'flex', flexDirection: 'column',
    }}>
      <div style={{ padding: '20px 22px 0', flex: 1 }}>
        <div style={{
          fontFamily: FONT_DISPLAY, fontSize: 30, fontWeight: 500,
          color: W.ink, letterSpacing: -0.4, lineHeight: 1.1,
        }}>Tell us about<br/>your wedding.</div>
        <div style={{
          fontFamily: FONT_UI, fontSize: 13.5, color: W.ink2, marginTop: 10,
          lineHeight: 1.5,
        }}>
          Just the basics. You can change anything later.
        </div>

        <div style={{ marginTop: 24, display: 'flex', flexDirection: 'column', gap: 14 }}>
          <FieldGroup label="The couple">
            <InputRow
              hint="Your name"
              placeholder="e.g. Alex Morgan"
              value={values.brides}
              onChange={v => set('brides', v)}/>
            <FieldDivider/>
            <InputRow
              hint="Their name"
              placeholder="e.g. Jordan Reed"
              value={values.groom}
              onChange={v => set('groom', v)}/>
          </FieldGroup>

          <FieldGroup label="When & where">
            <InputRow
              hint="Date" icon="calendar" type="date"
              value={values.dateISO ? values.dateISO.slice(0, 10) : ''}
              onChange={v => set('dateISO', v ? new Date(v + 'T16:00:00').toISOString() : '')}/>
            <FieldDivider/>
            <InputRow
              hint="City or region" icon="leaf"
              placeholder="e.g. Hudson Valley, NY"
              value={values.city}
              onChange={v => set('city', v)}/>
            <FieldDivider/>
            <InputRow
              hint="Venue" icon="home"
              placeholder="e.g. Hollow Tree (or skip for now)"
              value={values.venue}
              onChange={v => set('venue', v)}/>
          </FieldGroup>

          <FieldGroup label="The shape of it">
            <InputRow
              hint="Guest count" icon="users" type="number" inputMode="numeric"
              placeholder="120"
              suffix=" guests"
              value={values.guestCount}
              onChange={v => set('guestCount', v.replace(/[^0-9]/g, ''))}/>
            <FieldDivider/>
            <InputRow
              hint="Target budget" icon="wallet" type="number" inputMode="numeric"
              placeholder="60000"
              prefix="$"
              value={values.budget}
              onChange={v => set('budget', v.replace(/[^0-9]/g, ''))}/>
          </FieldGroup>
        </div>

        <div style={{ height: 24 }}/>
      </div>

      <PrimaryButton
        label="Continue"
        onClick={canContinue ? onContinue : null}
        sub={!canContinue ? 'Add both names to continue' : null}/>
    </div>
  );
}

function FieldGroup({ label, children }) {
  return (
    <div>
      <div style={{
        fontFamily: FONT_UI, fontSize: 10.5, fontWeight: 600,
        letterSpacing: 1.4, textTransform: 'uppercase', color: W.muted,
        marginBottom: 8, paddingLeft: 4,
      }}>{label}</div>
      <Card style={{ padding: '0' }}>
        {children}
      </Card>
    </div>
  );
}
function FieldDivider() {
  return <div style={{ height: 0.5, background: W.lineSoft, marginLeft: 16 }}/>;
}
function InputRow({ value, hint, icon, type = 'text', inputMode, placeholder, prefix, suffix, onChange }) {
  return (
    <label style={{
      padding: '12px 16px', display: 'flex', alignItems: 'center', gap: 12,
      cursor: 'text',
    }}>
      {icon && <Icon name={icon} size={16} color={W.muted} strokeWidth={1.4}/>}
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{
          fontFamily: FONT_UI, fontSize: 11.5, color: W.muted, marginBottom: 2,
        }}>{hint}</div>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 0 }}>
          {prefix && (
            <span style={{
              fontFamily: FONT_UI, fontSize: 15, fontWeight: 500, color: value ? W.ink : W.faint,
            }}>{prefix}</span>
          )}
          <input
            type={type === 'date' ? 'date' : 'text'}
            inputMode={inputMode}
            value={value || ''}
            onChange={(e) => onChange(e.target.value)}
            placeholder={placeholder}
            style={{
              flex: 1, minWidth: 0,
              border: 'none', background: 'transparent', outline: 'none', padding: 0,
              fontFamily: FONT_UI, fontSize: 15, fontWeight: 500, color: W.ink,
            }}/>
          {suffix && value && (
            <span style={{
              fontFamily: FONT_UI, fontSize: 13, color: W.muted, marginLeft: 4,
            }}>{suffix}</span>
          )}
        </div>
      </div>
    </label>
  );
}

// ─── Step 2: Priorities ─────────────────────────────────────

const PRIORITY_OPTIONS = [
  { id: 'elegant',     label: 'Elegant',     sub: 'Editorial & considered' },
  { id: 'affordable',  label: 'Affordable',  sub: 'Spend smart, look great' },
  { id: 'destination', label: 'Destination', sub: 'Out of town, weekend-long' },
  { id: 'luxury',      label: 'Luxury',      sub: 'No corners cut' },
  { id: 'intimate',    label: 'Intimate',    sub: 'Closer circle, deeper feel' },
  { id: 'party',       label: 'Party-first', sub: 'Dancing past midnight' },
];

function Step2Priorities({ selected, onChange, onContinue }) {
  const toggle = id => onChange(
    selected.includes(id) ? selected.filter(x => x !== id) : [...selected, id]
  );
  return (
    <div style={{
      minHeight: 'calc(100% - 90px)',
      display: 'flex', flexDirection: 'column',
    }}>
      <div style={{ padding: '20px 22px 0', flex: 1 }}>
        <div style={{
          fontFamily: FONT_DISPLAY, fontSize: 30, fontWeight: 500,
          color: W.ink, letterSpacing: -0.4, lineHeight: 1.1,
        }}>What matters<br/>most?</div>
        <div style={{
          fontFamily: FONT_UI, fontSize: 13.5, color: W.ink2, marginTop: 10,
          lineHeight: 1.5,
        }}>Pick a few. We'll shape your dashboard around them.</div>

        <div style={{
          marginTop: 22,
          display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10,
        }}>
          {PRIORITY_OPTIONS.map(opt => (
            <PriorityCard key={opt.id}
              opt={opt}
              selected={selected.includes(opt.id)}
              onToggle={() => toggle(opt.id)}/>
          ))}
        </div>

        <div style={{ height: 24 }}/>
      </div>

      <PrimaryButton
        label="Continue"
        onClick={onContinue}
        sub={`${selected.length} selected`}
      />
    </div>
  );
}

function PriorityCard({ opt, selected, onToggle }) {
  return (
    <button onClick={onToggle} style={{
      background: selected ? W.cardDeep : W.card,
      color: selected ? '#f5efe2' : W.ink,
      border: selected ? 'none' : `0.5px solid ${W.line}`,
      borderRadius: 18, padding: '16px 14px',
      textAlign: 'left', cursor: 'pointer',
      display: 'flex', flexDirection: 'column', gap: 4,
      transition: 'all 180ms ease',
      boxShadow: selected
        ? '0 6px 18px -6px rgba(29,24,18,0.35)'
        : '0 1px 2px rgba(60,40,20,0.03)',
      minHeight: 92,
    }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <div style={{
          fontFamily: FONT_DISPLAY, fontSize: 19, fontWeight: 500, letterSpacing: -0.2,
        }}>{opt.label}</div>
        {selected && (
          <div style={{
            width: 20, height: 20, borderRadius: 999, background: '#f5efe2',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>
            <Icon name="check" size={12} color={W.cardDeep} strokeWidth={2.2}/>
          </div>
        )}
      </div>
      <div style={{
        fontFamily: FONT_UI, fontSize: 11.5, fontWeight: 400,
        color: selected ? 'rgba(245,239,226,0.7)' : W.muted,
        marginTop: 'auto',
      }}>{opt.sub}</div>
    </button>
  );
}

// ─── Step 3: Stress ─────────────────────────────────────────

const STRESS_OPTIONS = [
  { id: 'budget',   label: 'Budget' },
  { id: 'guests',   label: 'Guest list' },
  { id: 'vendors',  label: 'Vendors' },
  { id: 'timeline', label: 'Timeline' },
  { id: 'seating',  label: 'Seating' },
  { id: 'family',   label: 'Family politics' },
  { id: 'logistics',label: 'Logistics' },
  { id: 'nothing',  label: 'I feel calm, actually' },
];

function Step3Stress({ selected, onChange, onContinue }) {
  const toggle = id => onChange(
    selected.includes(id) ? selected.filter(x => x !== id) : [...selected, id]
  );
  return (
    <div style={{
      minHeight: 'calc(100% - 90px)',
      display: 'flex', flexDirection: 'column',
    }}>
      <div style={{ padding: '20px 22px 0', flex: 1 }}>
        <div style={{
          fontFamily: FONT_DISPLAY, fontSize: 30, fontWeight: 500,
          color: W.ink, letterSpacing: -0.4, lineHeight: 1.1,
        }}>Where does it<br/><span style={{ fontStyle: 'italic' }}>feel</span> heaviest?</div>
        <div style={{
          fontFamily: FONT_UI, fontSize: 13.5, color: W.ink2, marginTop: 10,
          lineHeight: 1.5,
        }}>We'll put these front and center, so you never have to hunt.</div>

        <div style={{
          marginTop: 24,
          display: 'flex', flexWrap: 'wrap', gap: 8,
        }}>
          {STRESS_OPTIONS.map(opt => {
            const isSel = selected.includes(opt.id);
            return (
              <button key={opt.id} onClick={() => toggle(opt.id)} style={{
                background: isSel ? W.ink : W.card,
                color: isSel ? W.bg : W.ink2,
                border: isSel ? 'none' : `0.5px solid ${W.line}`,
                padding: '10px 14px', borderRadius: 999,
                fontFamily: FONT_UI, fontSize: 13.5, fontWeight: 500,
                cursor: 'pointer',
                display: 'flex', alignItems: 'center', gap: 6,
                transition: 'all 150ms ease',
              }}>
                {isSel && <Icon name="check" size={12} color={W.bg} strokeWidth={2}/>}
                {opt.label}
              </button>
            );
          })}
        </div>

        <div style={{ marginTop: 30 }}>
          <Card style={{ padding: 16, background: W.cardSoft }}>
            <div style={{
              fontFamily: FONT_DISPLAY, fontStyle: 'italic',
              fontSize: 15, color: W.ink2, lineHeight: 1.5,
            }}>
              "I just want it to feel like us — not like a logistics project."
            </div>
            <div style={{
              fontFamily: FONT_UI, fontSize: 11, color: W.muted, marginTop: 8,
              letterSpacing: 0.3,
            }}>— a bride, last spring</div>
          </Card>
        </div>

        <div style={{ height: 24 }}/>
      </div>

      <PrimaryButton label="Finish setup" onClick={onContinue}/>
    </div>
  );
}

// ─── Step 4: Ready ──────────────────────────────────────────

function Step4Ready({ onContinue }) {
  const wedding = useWedding();
  const signals = usePlanningSignals();
  const daysLine = wedding.daysUntil != null
    ? `With ${wedding.daysUntil} days to go${wedding.guestCount ? ` and ${wedding.guestCount} guests` : ''}, here's what deserves your attention first.`
    : `You can plan at your own pace — add details as they're decided.`;
  return (
    <div style={{
      minHeight: 'calc(100% - 56px)',
      display: 'flex', flexDirection: 'column',
    }}>
      <div style={{
        padding: '36px 22px 0', flex: 1,
        display: 'flex', flexDirection: 'column', alignItems: 'center',
        textAlign: 'center',
      }}>
        {/* Ring icon */}
        <div style={{
          width: 56, height: 56, borderRadius: 999,
          background: W.cardDeep, color: '#f5efe2',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          boxShadow: '0 10px 28px -10px rgba(29,24,18,0.4)',
          marginTop: 8,
        }}>
          <Icon name="rings" size={24} color="#f5efe2" strokeWidth={1.4}/>
        </div>

        <div style={{
          fontFamily: FONT_DISPLAY, fontSize: 32, fontWeight: 500,
          color: W.ink, letterSpacing: -0.4, lineHeight: 1.05,
          marginTop: 22,
        }}>
          You're all set,<br/>
          <span style={{ fontStyle: 'italic' }}>
            {wedding.couple || 'beautifully'}.
          </span>
        </div>
        <div style={{
          fontFamily: FONT_DISPLAY, fontStyle: 'italic', fontSize: 15,
          color: W.ink2, marginTop: 14, lineHeight: 1.5, maxWidth: 320,
        }}>{daysLine}</div>

        {/* Signals preview — only if we have any */}
        {signals.length > 0 && (
          <div style={{
            marginTop: 28, alignSelf: 'stretch', textAlign: 'left',
            display: 'flex', flexDirection: 'column', gap: 8,
          }}>
            {signals.slice(0, 3).map(s => (
              <SignalCard key={s.id} signal={s} compact/>
            ))}
          </div>
        )}

        <div style={{
          marginTop: 18, padding: '10px 14px', background: W.cardSoft,
          borderRadius: 12, border: `0.5px solid ${W.lineSoft}`,
          display: 'flex', alignItems: 'center', gap: 8, alignSelf: 'stretch',
        }}>
          <Icon name="sparkle" size={14} color={W.clay} strokeWidth={1.4}/>
          <div style={{
            fontFamily: FONT_UI, fontSize: 12, color: W.ink2, textAlign: 'left',
          }}>Sync to your other devices later — your data stays local until you do.</div>
        </div>

        <div style={{ height: 24 }}/>
      </div>

      <PrimaryButton label="Open WeddingOS" onClick={onContinue}/>
    </div>
  );
}

function SummaryRow({ icon, k, v }) {
  return (
    <div style={{
      padding: '12px 14px', display: 'flex', alignItems: 'center', gap: 12,
    }}>
      <Icon name={icon} size={15} color={W.clay} strokeWidth={1.4}/>
      <div style={{
        flex: 1, fontFamily: FONT_UI, fontSize: 12.5, color: W.muted,
      }}>{k}</div>
      <div style={{
        fontFamily: FONT_UI, fontSize: 14, fontWeight: 500, color: W.ink,
      }}>{v}</div>
    </div>
  );
}

Object.assign(window, { OnboardingApp });
