// Onboarding — six-step setup wired to real store (auth + DB).
// startStep / skipSignIn props let the dashboard "Add kid" flow reuse this screen.

function Onboarding({ accent = 'mango', startStep = 0, skipSignIn = false, mode = 'first-run' }) {
  const store = window.useStore();
  const [step, setStep] = React.useState(startStep);
  const [family, setFamily] = React.useState(() => store.household?.name || '');
  const [kid, setKid] = React.useState({ name: '', age: 6, color: 'mango' });
  const [photo, setPhoto] = React.useState(null);
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState(null);

  React.useEffect(() => {
    if (store.household?.name && !family) setFamily(store.household.name);
  }, [store.household?.name]); // eslint-disable-line

  const steps = skipSignIn
    ? ['Family', 'Your kid', 'Photo', 'Tasks', 'Invite']
    : ['Sign in', 'Family', 'Your kid', 'Photo', 'Tasks', 'Invite'];

  const moodsByStep = skipSignIn
    ? ['happy', 'thinking', 'cheer', 'happy', 'proud']
    : ['wave',  'happy',    'thinking', 'cheer', 'happy', 'proud'];

  const messagesByStep = skipSignIn
    ? [
        "What do you call your family?",
        `Tell me about ${mode === 'add-kid' ? 'your next' : 'your first'} kid.`,
        `Want to add a photo of ${kid.name || 'them'}?`,
        "Here's a starter set of tasks — you can tweak these later.",
        "Anyone else helping out?",
      ]
    : [
        "Hoot! I'm Suri. Let's set up your family.",
        "What do you call your family?",
        "Tell me about your first kid.",
        `Want to add a photo of ${kid.name || 'them'}?`,
        "Here's a starter set of tasks — you can tweak these later.",
        "Anyone else helping out?",
      ];

  const suriColor = window.KID_COLORS_V3[kid.color]?.hex || '#FF6B2C';

  const onPhoto = (e) => {
    const f = e.target.files?.[0];
    if (!f) return;
    const r = new FileReader();
    r.onload = () => setPhoto(r.result);
    r.readAsDataURL(f);
  };

  const handleSignIn = async () => {
    setBusy(true); setErr(null);
    try { await store.signInWithGoogle(); }
    catch (e) { setErr(e?.message || 'Sign-in failed'); setBusy(false); }
  };

  const handleSaveFamily = async () => {
    if (family && family !== store.household?.name) {
      try { await store.renameHousehold(family.trim()); } catch (e) { console.error(e); }
    }
    setStep(s => s + 1);
  };

  const finishOnboarding = async () => {
    setBusy(true); setErr(null);
    try {
      // Always seed every new kid with the same 4 good + 4 bad starter set.
      // The parent can edit / delete / add more from the Tasks screen later.
      const tasksToSave = (window.DEFAULT_STARTER_TASKS || []).map(t => ({
        emoji: t.emoji, label: t.label, points: t.points,
      }));
      await store.addKid({
        name: kid.name.trim() || 'Kid',
        color: kid.color,
        age: kid.age,
        goal: 50,
        photo,
        tasks: tasksToSave,
      });
      window.sprinkleStars({ count: 48 });
      setTimeout(() => {
        window.location.hash = '#/dashboard';
      }, 600);
    } catch (e) {
      setErr(e?.message || 'Could not save. Please try again.');
      setBusy(false);
    }
  };

  // Convert step index → label (when skipSignIn we shift by 1 internally so step 0 is "Family")
  // To keep code simple, the component always uses internal step indices that match steps[].
  // If !skipSignIn, step 0 = Sign In, step 1 = Family, …, step 5 = Invite.
  // If  skipSignIn, step 0 = Family,  step 1 = Your kid, …, step 4 = Invite.

  const renderStep = () => {
    if (!skipSignIn) {
      if (step === 0) return <StepSignIn onNext={handleSignIn} busy={busy} err={err} />;
      if (step === 1) return <StepFamily value={family} onChange={setFamily} onNext={handleSaveFamily} onBack={() => setStep(0)} />;
      if (step === 2) return <StepKid kid={kid} setKid={setKid} onNext={() => setStep(3)} onBack={() => setStep(1)} />;
      if (step === 3) return <StepPhoto kid={kid} photo={photo} onPhoto={onPhoto} setPhoto={setPhoto} onNext={() => setStep(4)} onBack={() => setStep(2)} />;
      if (step === 4) return <StepTasks kid={kid} onNext={() => setStep(5)} onBack={() => setStep(3)} />;
      if (step === 5) return <StepInvite onDone={finishOnboarding} onBack={() => setStep(4)} busy={busy} err={err} />;
    } else {
      if (step === 0) return <StepFamily value={family} onChange={setFamily} onNext={handleSaveFamily} onBack={null} />;
      if (step === 1) return <StepKid kid={kid} setKid={setKid} onNext={() => setStep(2)} onBack={() => setStep(0)} />;
      if (step === 2) return <StepPhoto kid={kid} photo={photo} onPhoto={onPhoto} setPhoto={setPhoto} onNext={() => setStep(3)} onBack={() => setStep(1)} />;
      if (step === 3) return <StepTasks kid={kid} onNext={() => setStep(4)} onBack={() => setStep(2)} />;
      if (step === 4) return <StepInvite onDone={finishOnboarding} onBack={() => setStep(3)} busy={busy} err={err} />;
    }
    return null;
  };

  return (
    <div className="onb-wrap">
      <style>{`
        .onb-wrap {
          min-height: 100vh;
          background: var(--paper);
          display: grid;
          grid-template-rows: auto 1fr;
        }
        .onb-hero {
          background: var(--dusk);
          color: var(--paper);
          padding: 36px 64px 80px;
          position: relative;
          overflow: hidden;
        }
        .onb-hero::after {
          content: '';
          position: absolute; bottom: -60px; left: 0; right: 0; height: 120px;
          background: var(--paper);
          border-radius: 50% 50% 0 0 / 100% 100% 0 0;
        }
        .onb-stage {
          margin: -64px auto 80px;
          max-width: 720px;
          width: calc(100% - 48px);
          position: relative;
          z-index: 2;
        }
        .onb-card {
          background: var(--paper-2);
          border-radius: 32px;
          padding: 44px 48px 36px;
          box-shadow: 0 4px 8px rgba(31,26,61,0.08), 0 40px 80px -20px rgba(31,26,61,0.25);
        }
        .onb-steps-row { display: flex; align-items: center; gap: 12px; margin-bottom: 24px; }
        .step-label {
          font-family: var(--font-display); font-weight: 500; font-size: 13px;
          letter-spacing: -0.005em; color: rgba(251,246,235,0.55);
        }
        .step-label.active { color: var(--paper); }
        .step-label.done   { color: rgba(251,246,235,0.7); }
        .onb-mascot-line { display: flex; align-items: flex-end; gap: 18px; margin-bottom: 8px; }
        .onb-bg-dots {
          position: absolute; inset: 0; opacity: 0.4;
          background-image: radial-gradient(circle, rgba(255,210,63,0.5) 1px, transparent 1px);
          background-size: 28px 28px;
        }
        @media (max-width: 760px) {
          .onb-hero  { padding: 24px 20px 80px; }
          .onb-card  { padding: 28px 22px; }
          .onb-stage { width: calc(100% - 32px); margin-top: -56px; }
        }
      `}</style>

      <header className="onb-hero">
        <div className="onb-bg-dots" />
        <div style={{ position: 'relative', zIndex: 1, maxWidth: 1200, margin: '0 auto' }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 32 }}>
            <div style={{
              display: 'flex', alignItems: 'center', gap: 10,
              fontFamily: 'var(--font-display)', fontWeight: 700,
              fontSize: 22, color: 'var(--paper)', letterSpacing: '-0.02em',
            }}>
              <span className="brand-mark">s</span>
              sirisora
            </div>
            {mode === 'add-kid' && (
              <button onClick={() => { window.location.hash = '#/dashboard'; }} style={{
                background: 'rgba(255,255,255,0.08)', color: 'var(--paper)',
                padding: '8px 16px', borderRadius: 999,
                border: '1px solid rgba(255,255,255,0.18)',
                fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 13,
              }}>✕ Cancel</button>
            )}
          </div>

          <div className="onb-mascot-line">
            <div className="mascot-idle" key={step}>
              <window.Suri mood={moodsByStep[step]} size={120} color={suriColor} wave={step === 0 && !skipSignIn} />
            </div>
            <div className="pop-in" key={'b-' + step} style={{ paddingBottom: 12 }}>
              <window.SuriBubble>{messagesByStep[step]}</window.SuriBubble>
            </div>
          </div>

          <div style={{ marginTop: 18, display: 'flex', gap: 22, flexWrap: 'wrap' }}>
            {steps.map((label, i) => (
              <div key={label} style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <div style={{
                  width: 22, height: 22, borderRadius: '50%',
                  border: '1.5px solid rgba(251,246,235,0.3)',
                  background: i < step ? 'var(--mint)' : i === step ? 'var(--mango)' : 'transparent',
                  borderColor: i < step ? 'var(--mint)' : i === step ? 'var(--mango)' : 'rgba(251,246,235,0.3)',
                  display: 'grid', placeItems: 'center',
                  fontSize: 11, fontWeight: 700, color: i <= step ? 'white' : 'rgba(251,246,235,0.5)',
                  transition: 'all 280ms cubic-bezier(.4,1.4,.5,1)',
                  transform: i === step ? 'scale(1.15)' : 'scale(1)',
                  boxShadow: i === step ? '0 0 0 6px rgba(255,107,44,0.25)' : 'none',
                }}>
                  {i < step ? '✓' : i + 1}
                </div>
                <span className={`step-label ${i === step ? 'active' : i < step ? 'done' : ''}`}>{label}</span>
              </div>
            ))}
          </div>
        </div>
      </header>

      <div className="onb-stage">
        <div className="onb-card pop-in" key={step}>
          {renderStep()}
        </div>
      </div>
    </div>
  );
}

// ── Steps ───────────────────────────────────────────────────────────────
function StepSignIn({ onNext, busy, err }) {
  return (
    <div>
      <window.Eyebrow>Welcome</window.Eyebrow>
      <h1 className="h-display h2" style={{ marginTop: 10 }}>
        Tiny habits.<br/>
        <em style={{ fontStyle: 'normal', color: 'var(--mango)' }}>Real</em> rewards.
      </h1>
      <p className="lede" style={{ marginTop: 18 }}>
        Sirisora is a family points app where small wins add up. Parents set it up — kids see their progress, drop earned stars into reward jars, and own their habits.
      </p>
      <div style={{ marginTop: 36 }}>
        <button className="btn btn-google" onClick={onNext} disabled={busy}
          style={{ opacity: busy ? 0.6 : 1 }}>
          <GoogleG /> {busy ? 'Opening Google…' : 'Continue with Google'}
        </button>
        {err && <div style={{ marginTop: 14, color: 'var(--alert)', fontSize: 14 }}>{err}</div>}
        <div style={{ fontSize: 13, color: 'var(--ink-faint)', marginTop: 14, maxWidth: 420, lineHeight: 1.5 }}>
          We use Google sign-in so you don't have to remember another password. Your kids never sign in directly — you control everything.
        </div>
      </div>
    </div>
  );
}

function StepFamily({ value, onChange, onNext, onBack }) {
  return (
    <div>
      <window.Eyebrow>{onBack ? 'Step 2 · Your family' : 'Your family'}</window.Eyebrow>
      <h1 className="h-display h2" style={{ marginTop: 10 }}>What's your family called?</h1>
      <div style={{ marginTop: 28 }} className="field">
        <label>Family name</label>
        <input
          type="text" placeholder="The Iyer Family" autoFocus
          value={value} onChange={(e) => onChange(e.target.value)}
          style={{ fontSize: 24, fontFamily: 'var(--font-display)', fontWeight: 600, padding: '18px 20px', letterSpacing: '-0.02em' }}
        />
        <div style={{ fontSize: 13, color: 'var(--ink-faint)', marginTop: 6 }}>
          You can change this any time.
        </div>
      </div>
      <FormNav onBack={onBack} onNext={onNext} canNext={!!value.trim()} />
    </div>
  );
}

function StepKid({ kid, setKid, onNext, onBack }) {
  const colors = ['mango', 'mint', 'periwinkle', 'blush', 'butter', 'berry'];
  return (
    <div>
      <window.Eyebrow>Your kid</window.Eyebrow>
      <h1 className="h-display h2" style={{ marginTop: 10 }}>Add a kid.</h1>
      <p style={{ marginTop: 10, color: 'var(--ink-soft)', fontSize: 16 }}>
        You can add more later. Each kid gets their own color.
      </p>

      <div style={{ display: 'grid', gap: 24, marginTop: 28 }}>
        <div className="field">
          <label>Their name</label>
          <input type="text" placeholder="Maya" value={kid.name} onChange={(e) => setKid({ ...kid, name: e.target.value })}
                 style={{ fontSize: 20, fontFamily: 'var(--font-display)', fontWeight: 600 }} autoFocus />
        </div>

        <div className="field">
          <label>How old?</label>
          <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
            {[3,4,5,6,7,8,9,10,11,12].map((a) => (
              <button key={a} onClick={() => setKid({ ...kid, age: a })} style={{
                width: 50, height: 50, borderRadius: 14,
                background: kid.age === a ? 'var(--ink)' : 'var(--paper-2)',
                color: kid.age === a ? 'var(--paper)' : 'var(--ink)',
                border: '1.5px solid ' + (kid.age === a ? 'var(--ink)' : 'var(--rule-strong)'),
                fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 17,
                transition: 'all 160ms cubic-bezier(.4,1.4,.5,1)',
              }}>{a}</button>
            ))}
          </div>
        </div>

        <div className="field">
          <label>Pick a color</label>
          <div style={{ display: 'flex', gap: 14, flexWrap: 'wrap' }}>
            {colors.map((c) => {
              const hex = window.KID_COLORS_V3[c].hex;
              return (
                <button key={c} onClick={() => setKid({ ...kid, color: c })} aria-label={c} style={{
                  width: 52, height: 52, borderRadius: '50%', background: hex,
                  border: kid.color === c ? '3px solid var(--ink)' : '3px solid transparent',
                  boxShadow: kid.color === c ? `0 0 0 6px ${hex}40, 0 8px 20px -8px ${hex}` : '0 6px 16px -6px ' + hex + '80',
                  transition: 'transform 220ms cubic-bezier(.4,1.4,.5,1)',
                  transform: kid.color === c ? 'scale(1.1)' : 'scale(1)',
                }} />
              );
            })}
          </div>
        </div>
      </div>
      <FormNav onBack={onBack} onNext={onNext} canNext={!!kid.name.trim()} />
    </div>
  );
}

function StepPhoto({ kid, photo, onPhoto, setPhoto, onNext, onBack }) {
  const fileRef = React.useRef(null);
  const hex = window.KID_COLORS_V3[kid.color].hex;
  return (
    <div>
      <window.Eyebrow>Photo · optional</window.Eyebrow>
      <h1 className="h-display h2" style={{ marginTop: 10 }}>A photo of {kid.name || 'them'}?</h1>
      <p style={{ marginTop: 10, color: 'var(--ink-soft)', fontSize: 16 }}>
        Photos stay private to your family. Never shared, never used to train anything. Totally optional.
      </p>

      <div style={{ display: 'flex', gap: 28, alignItems: 'center', marginTop: 32, flexWrap: 'wrap' }}>
        <label style={{
          width: 180, height: 180,
          borderRadius: 36,
          background: photo ? `url(${photo}) center/cover` : 'var(--paper-soft)',
          border: photo ? `4px solid ${hex}` : '2.5px dashed var(--rule-strong)',
          display: 'grid', placeItems: 'center',
          fontFamily: 'var(--font-display)', fontWeight: 500, fontSize: 14,
          color: 'var(--ink-soft)', cursor: 'pointer',
          transition: 'all 200ms ease', textAlign: 'center',
        }}>
          {!photo && <div><div style={{ fontSize: 32, marginBottom: 4 }}>📷</div>Tap to upload<br/>or drop here</div>}
          <input ref={fileRef} type="file" accept="image/*" onChange={onPhoto} style={{ display: 'none' }} />
        </label>
        <div style={{ display: 'grid', gap: 12 }}>
          <button className="btn btn-primary" onClick={() => fileRef.current?.click()}>Choose photo</button>
          {photo && <button className="btn btn-ghost" onClick={() => setPhoto(null)}>Remove</button>}
          {!photo && <div style={{ fontSize: 14, color: 'var(--ink-faint)', maxWidth: 240, lineHeight: 1.5 }}>
            Or skip — we'll use their initial on the color circle.
          </div>}
        </div>
      </div>
      <FormNav onBack={onBack} onNext={onNext} canNext={true} nextLabel={photo ? 'Continue' : 'Skip for now'} />
    </div>
  );
}

// Every kid is auto-seeded with the same starter set of 4 good + 4 bad tasks.
// This step just previews them so the parent isn't surprised, then they can
// tweak everything from the Tasks screen after onboarding.
function StepTasks({ kid, onNext, onBack }) {
  const all = window.DEFAULT_STARTER_TASKS || [];
  const goods = all.filter(t => t.kind === 'good');
  const bads  = all.filter(t => t.kind === 'bad');
  const renderRow = (t, i) => {
    const isGood = t.kind === 'good';
    return (
      <div key={`${t.kind}-${i}`} style={{
        display: 'flex', alignItems: 'center', gap: 14,
        padding: '12px 16px',
        background: isGood ? 'var(--mint-soft)' : 'var(--blush-soft)',
        border: '1.5px solid ' + (isGood ? 'var(--mint)' : 'rgba(231,75,88,0.45)'),
        borderRadius: 14,
      }}>
        <span style={{ fontSize: 24 }}>{t.emoji}</span>
        <span style={{ flex: 1, fontFamily: 'var(--font-display)', fontWeight: 500, fontSize: 15 }}>{t.label}</span>
        <span style={{ fontFamily: 'var(--font-chunky)', fontSize: 20,
          color: isGood ? 'var(--success)' : 'var(--alert)' }}>
          {t.points > 0 ? `+${t.points}` : t.points}
        </span>
      </div>
    );
  };
  return (
    <div>
      <window.Eyebrow>Starter tasks</window.Eyebrow>
      <h1 className="h-display h2" style={{ marginTop: 10 }}>
        Here's where {kid.name || 'they'} start.
      </h1>
      <p style={{ marginTop: 10, color: 'var(--ink-soft)', fontSize: 16 }}>
        Every kid begins with the same 8 — four to grow stars, four that lose
        them. You can edit, remove, or add more on the Tasks screen any time.
      </p>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))', gap: 18, marginTop: 22 }}>
        <div>
          <div className="eyebrow" style={{ marginBottom: 8, color: 'var(--success)' }}>Grow stars</div>
          <div style={{ display: 'grid', gap: 6 }}>{goods.map(renderRow)}</div>
        </div>
        <div>
          <div className="eyebrow" style={{ marginBottom: 8, color: 'var(--alert)' }}>Lose stars</div>
          <div style={{ display: 'grid', gap: 6 }}>{bads.map(renderRow)}</div>
        </div>
      </div>

      <FormNav onBack={onBack} onNext={onNext} canNext={true} nextLabel="Looks good →" />
    </div>
  );
}

function StepInvite({ onDone, onBack, busy, err }) {
  const [email, setEmail] = React.useState('');
  return (
    <div>
      <window.Eyebrow>Invite · optional</window.Eyebrow>
      <h1 className="h-display h2" style={{ marginTop: 10 }}>Anyone else helping out?</h1>
      <p style={{ marginTop: 10, color: 'var(--ink-soft)', fontSize: 16 }}>
        Invite a co-parent, grandparent, or carer to mark tasks done. You can always add them later.
      </p>

      <div className="field" style={{ marginTop: 24 }}>
        <label>Email</label>
        <input type="email" placeholder="partner@example.com" value={email} onChange={(e) => setEmail(e.target.value)} />
        <div style={{ fontSize: 12, color: 'var(--ink-faint)', marginTop: 6 }}>
          Invitations are coming soon — for now this is just so you can plan ahead.
        </div>
      </div>

      <div style={{
        marginTop: 36, padding: 24,
        background: 'linear-gradient(135deg, var(--mint-soft) 0%, var(--periwinkle-soft) 100%)',
        borderRadius: 22, display: 'flex', alignItems: 'center', gap: 18,
      }}>
        <window.Suri mood="proud" size={64} color="#00C896" />
        <div>
          <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 20, letterSpacing: '-0.02em' }}>You're all set!</div>
          <div style={{ fontSize: 15, color: 'var(--ink-soft)', marginTop: 2 }}>Open the dashboard to see your first day take shape.</div>
        </div>
      </div>

      {err && <div style={{ marginTop: 16, color: 'var(--alert)', fontSize: 14 }}>{err}</div>}

      <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 32, alignItems: 'center', flexWrap: 'wrap', gap: 12 }}>
        <button className="btn btn-ghost" onClick={onBack} disabled={busy}>Back</button>
        <button className="btn btn-primary" onClick={onDone} disabled={busy}
          style={{ opacity: busy ? 0.6 : 1 }}>
          {busy ? 'Saving…' : 'Finish ✨'}
        </button>
      </div>
    </div>
  );
}

function FormNav({ onBack, onNext, canNext, nextLabel = 'Continue' }) {
  return (
    <div style={{ display: 'flex', justifyContent: onBack ? 'space-between' : 'flex-end', marginTop: 36, alignItems: 'center' }}>
      {onBack && <button className="btn btn-ghost" onClick={onBack}>← Back</button>}
      <button className="btn btn-primary" disabled={!canNext} onClick={onNext}
        style={{ opacity: canNext ? 1 : 0.4, pointerEvents: canNext ? 'auto' : 'none' }}>
        {nextLabel} →
      </button>
    </div>
  );
}

function GoogleG() {
  return (
    <svg width="20" height="20" viewBox="0 0 48 48" aria-hidden="true">
      <path fill="#FFC107" d="M43.6 20.5H42V20H24v8h11.3c-1.6 4.7-6 8-11.3 8-6.6 0-12-5.4-12-12s5.4-12 12-12c3 0 5.8 1.1 7.9 3l5.7-5.7C34 6.1 29.3 4 24 4 12.9 4 4 12.9 4 24s8.9 20 20 20 20-8.9 20-20c0-1.3-.1-2.4-.4-3.5z"/>
      <path fill="#FF3D00" d="M6.3 14.7l6.6 4.8C14.7 16 19 13 24 13c3 0 5.8 1.1 7.9 3l5.7-5.7C34 6.1 29.3 4 24 4 16.3 4 9.7 8.3 6.3 14.7z"/>
      <path fill="#4CAF50" d="M24 44c5.2 0 9.9-2 13.4-5.3l-6.2-5.2c-2 1.5-4.5 2.5-7.2 2.5-5.3 0-9.7-3.3-11.3-8L6.2 33C9.5 39.5 16.2 44 24 44z"/>
      <path fill="#1976D2" d="M43.6 20.5H42V20H24v8h11.3c-.8 2.2-2.2 4.1-4 5.5l6.2 5.2C41.4 35.6 44 30.2 44 24c0-1.3-.1-2.4-.4-3.5z"/>
    </svg>
  );
}

window.Onboarding = Onboarding;
