// Memoriz onboarding — Loading + Plan Reveal + Paywall + Success

// ---------------- Helper data ----------------
const TIMELINE_NAMES = {
  child:  { title: "Baby's First Year",  icon: '👶' },
  family: { title: 'Our Family Story',   icon: '🏡' },
  couple: { title: 'Us',                 icon: '💑' },
  trips:  { title: 'Adventures',         icon: '✈️' },
};

const REVEAL_HEADLINES = {
  child:  'Your baby timeline is ready.',
  family: 'Your family space is ready.',
  couple: "Your couple's space is ready.",
  trips:  'Your travel journal is ready.',
};

const MOMENT_SLOT = {
  photo:     { emoji: '📸', label: 'Ready to add your first photo',         hint: 'Tap the camera in your timeline.' },
  voice:     { emoji: '🎤', label: 'Ready to save your first voice message', hint: 'Tap & hold to record.' },
  video:     { emoji: '🎬', label: 'Ready to keep your first video safe',    hint: 'Up to 60s, any moment.' },
  milestone: { emoji: '📝', label: 'Ready to mark your first milestone',     hint: 'A date worth remembering.' },
};

const CIRCLE_LABELS = {
  partner: 'Partner', mom: 'Mom', dad: 'Dad', grandma: 'Grandma',
  grandpa: 'Grandpa', sibling: 'Sib', friend: 'Friend', other: 'Other'
};
const CIRCLE_INITIAL = {
  partner: 'P', mom: 'M', dad: 'D', grandma: 'G', grandpa: 'P', sibling: 'S', friend: 'F', other: '+'
};

const PERSONAL_BULLET = {
  child:  'A timeline that grows with your child',
  family: 'A shared space the whole family can enjoy',
  couple: 'Your love story, organized and safe',
  trips:  'Every adventure saved and easy to relive',
};

// ---------------- LOADING SCREEN ----------------
const LoadingScreen = ({ goal, circle, moment, onDone }) => {
  const messages = useMemo(() => [
    'Creating your space…',
    `Building "${TIMELINE_NAMES[goal].title}"…`,
    circle && circle.length > 0 ? `Reserving spots for ${circle.length} loved one${circle.length>1?'s':''}…` : 'Setting up your circle…',
    'Almost ready ✨',
  ], [goal, circle]);
  const [msgIdx, setMsgIdx] = useState(0);

  useEffect(() => {
    const t1 = setTimeout(() => setMsgIdx(1), 500);
    const t2 = setTimeout(() => setMsgIdx(2), 1100);
    const t3 = setTimeout(() => setMsgIdx(3), 1700);
    const tEnd = setTimeout(() => onDone(), 2200);
    return () => { clearTimeout(t1); clearTimeout(t2); clearTimeout(t3); clearTimeout(tEnd); };
  }, []);

  // Up to 4 avatars to drop in
  const avatars = (circle || []).slice(0, 4);

  return (
    <div className="screen">
      <div className="aurora subtle" />
      <StatusBar />
      <div className="loading-screen">
        <div className="loading-canvas">
          {/* central vertical timeline */}
          <div className="timeline-line" />

          {/* 3 timeline nodes that pop in */}
          <div className="node" style={{ top: '28%', animationDelay: '0.6s' }} />
          <div className="node" style={{ top: '50%', animationDelay: '1.0s' }} />
          <div className="node" style={{ top: '72%', animationDelay: '1.4s' }} />

          {/* polaroids dropping near the nodes */}
          <div className="polaroid" style={{ top: '28%', left: '78%', '--rot': '7deg', animationDelay: '0.7s' }}>
            <div className="photo" style={{ backgroundImage: 'url(assets/photo-baby.png)' }} />
          </div>
          <div className="polaroid" style={{ top: '50%', left: '22%', '--rot': '-9deg', animationDelay: '1.05s' }}>
            <div className="photo" style={{ backgroundImage: 'url(assets/photo-wedding.jpg)' }} />
          </div>
          <div className="polaroid" style={{ top: '72%', left: '78%', '--rot': '6deg', animationDelay: '1.4s' }}>
            <div className="photo" style={{ backgroundImage: 'url(assets/photo-couple-sunset.png)' }} />
          </div>

          {/* avatars (people from the circle) landing into the space */}
          {avatars.map((c, i) => {
            const positions = [
              { top: '14%',  left: '22%' },
              { top: '14%',  left: '78%' },
              { top: '86%',  left: '22%' },
              { top: '86%',  left: '78%' },
            ];
            return (
              <div key={c}
                   className={'avatar-blob' + (i === 0 ? ' solid' : '')}
                   style={{ ...positions[i], animationDelay: `${1.5 + i * 0.15}s` }}>
                <span style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 14 }}>
                  {CIRCLE_INITIAL[c]}
                </span>
              </div>
            );
          })}

          {/* sparkles */}
          <div className="sparkle" style={{ top: '8%', left: '50%', animationDelay: '0.4s' }}>
            <Icon name="sparkle" size={14} color="#EE9B6A" />
          </div>
          <div className="sparkle" style={{ top: '92%', left: '50%', animationDelay: '1.2s' }}>
            <Icon name="sparkle" size={14} color="#EE9B6A" />
          </div>
          <div className="sparkle" style={{ top: '50%', left: '8%', animationDelay: '0.9s' }}>
            <Icon name="sparkle" size={11} color="#FA9ED7" />
          </div>
          <div className="sparkle" style={{ top: '50%', left: '92%', animationDelay: '1.6s' }}>
            <Icon name="sparkle" size={11} color="#7FD8B2" />
          </div>
        </div>

        <p className="loading-text" key={msgIdx}>
          <span className="lt-shimmer">{messages[msgIdx]}</span>
        </p>
        <div className="loading-progress"><div className="lpf" /></div>
      </div>
    </div>
  );
};

// ---------------- SCREEN 4: PLAN REVEAL ----------------
const ScreenPlanReveal = ({ step, total, goal, circle, moment, onContinue, onBack }) => {
  const tl = TIMELINE_NAMES[goal];
  const slot = MOMENT_SLOT[moment];
  const headline = REVEAL_HEADLINES[goal];

  const circleNames = (circle || []).map(c => CIRCLE_LABELS[c]);
  const visibleNames = circleNames.slice(0, 3);
  const extra = circleNames.length - visibleNames.length;
  const circleStrShort = visibleNames.join(', ') + (extra > 0 ? ` +${extra}` : '');

  return (
    <div className="screen">
      <div className="aurora" />
      <StatusBar />
      <TopNav step={step} total={total} onBack={onBack} />

      <div className="reveal-headline">
        <div className="sparkle-dot">
          <Icon name="sparkle" size={14} color="#EE9B6A" /> Just for you
        </div>
        <h1>{headline}</h1>
      </div>

      <div className="body-region" style={{ padding: 0 }}>
        <div className="reveal-card">
          {/* Floating sparkles */}
          <div className="reveal-sparkle" style={{ top: 14, right: 14, animationDelay: '0s' }}>
            <Icon name="sparkle" size={12} color="#EE9B6A" />
          </div>
          <div className="reveal-sparkle" style={{ bottom: 12, left: 16, animationDelay: '1.2s' }}>
            <Icon name="sparkle" size={10} color="#FA9ED7" />
          </div>

          <div className="timeline-head">
            <div className="ico"><Icon name="timeline" size={18} color="#EE9B6A" stroke={2.2} /></div>
            <div className="title">{tl.title}</div>
            <div className="private-chip"><Icon name="lock" size={9} color="#fff" stroke={2.4}/> PRIVATE</div>
          </div>

          <div className="divider" />

          <div className="moment-slot">
            <div className="slot-icon">{slot.emoji}</div>
            <div className="slot-text">
              <b>{slot.label}</b>
              <span>{slot.hint}</span>
            </div>
          </div>

          <div className="divider" />

          <div className="invite-row">
            <div className="stack">
              {visibleNames.slice(0, 3).map((n, i) => (
                <div className="av" key={i}>{n.charAt(0)}</div>
              ))}
              {extra > 0 && <div className="av more">+{extra}</div>}
              {circleNames.length === 0 && <div className="av">+</div>}
            </div>
            <div className="invite-text">
              <b>Invite when you're ready</b>
              <span>{circleStrShort || 'Add people anytime'}</span>
            </div>
          </div>
        </div>

        <div className="privacy-line">
          <Icon name="lock" size={14} color="#EE9B6A" stroke={2.2}/>
          Private. No algorithms. Just your family.
        </div>
      </div>

      <div className="bottom-halo" />
      <div className="cta-region">
        <button className="btn primary" onClick={onContinue}>Continue</button>
      </div>
    </div>
  );
};

// ---------------- SCREEN 5: PAYWALL ----------------
const ScreenPaywall = ({ step, total, goal, onBack, onPay, onMaybeLater }) => {
  const [plan, setPlan] = useState('yearly');
  return (
    <div className="screen">
      <div className="aurora" />
      <StatusBar />
      <TopNav step={step} total={total} onBack={onBack} />

      <div className="paywall-top">
        <MemorizLogo size={26} />
        <h1>Keep your family's story safe — forever.</h1>
      </div>

      <div className="bullets">
        <div className="bullet">
          <span className="check"><Icon name="check" size={13} stroke={2.6}/></span>
          <span className="lbl">Private space for your family only</span>
        </div>
        <div className="bullet">
          <span className="check"><Icon name="check" size={13} stroke={2.6}/></span>
          <span className="lbl">Photos, videos &amp; voice messages in one timeline</span>
        </div>
        <div className="bullet">
          <span className="check"><Icon name="check" size={13} stroke={2.6}/></span>
          <span className="lbl"><b>{PERSONAL_BULLET[goal]}</b></span>
        </div>
      </div>

      <div className="social-proof">
        <span className="stars">★★★★★</span> 4.8 — Loved by families
      </div>

      <div className="plans">
        <div className={'plan' + (plan === 'yearly' ? ' selected' : '')} onClick={() => setPlan('yearly')}>
          <span className="badge">7 DAYS FREE</span>
          <div>
            <h3>Yearly</h3>
            <div className="sub">🎉 Save 80.4 € (67%)</div>
          </div>
          <div className="right">
            <div className="price-block">
              <div className="price">3.29 €</div>
              <div className="per">/month</div>
            </div>
            <span className="check-circle"><Icon name="check" size={13} stroke={2.6}/></span>
          </div>
        </div>
        <div className={'plan muted' + (plan === 'monthly' ? ' selected' : '')} onClick={() => setPlan('monthly')}>
          <div>
            <h3>Monthly</h3>
            <div className="sub">No commitment</div>
          </div>
          <div className="right">
            <div className="price-block">
              <div className="price">9.99 €</div>
              <div className="per">/month</div>
            </div>
            <span className="check-circle"><Icon name="check" size={13} stroke={2.6}/></span>
          </div>
        </div>
      </div>

      <div className="bottom-halo" />
      <div className="cta-region">
        <button className="btn primary" onClick={() => onPay(plan)} style={{ fontSize: 16 }}>
          Start My Free Trial — 7 Days
        </button>
        <div className="risk-line">Cancel anytime. We'll remind you before your trial ends.</div>
        <div className="legal-line">
          <a href="#">Terms of Use</a><span className="pipe">|</span><a href="#">Privacy Policy</a>
        </div>
        <div className="restore-line"><a href="#" style={{color: 'var(--memoriz-gray-mute)'}}>Restore Purchases</a></div>
        <button className="maybe-later" onClick={onMaybeLater}>Maybe later</button>
      </div>
    </div>
  );
};

// ---------------- POST-PAYWALL SUCCESS ----------------
const SuccessScreen = ({ goal, moment, onReplay }) => {
  const tl = TIMELINE_NAMES[goal];
  const slot = MOMENT_SLOT[moment];
  return (
    <div className="screen">
      <div className="aurora" />
      <StatusBar />
      <div className="success-screen">
        <div className="checkmark">
          <Icon name="check" size={44} color="#fff" stroke={2.6}/>
        </div>
        <h2>Your trial has started.</h2>
        <p>"{tl.title}" is waiting for you.<br/>{slot.label}.</p>
        <div className="replay">
          <button className="btn primary" onClick={onReplay}>Replay onboarding</button>
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { LoadingScreen, ScreenPlanReveal, ScreenPaywall, SuccessScreen });
