// 12-screen onboarding spec for Professor Curious
// Tokens per brief: #6947BF primary, #F0EDF9 selected fill, Nunito, pill buttons
// Progress gradient: #FFB038 → #FF6363 → #6100FF

const TOKENS = {
  primary: '#6947BF',
  primaryShadow: '#412785',
  primaryTint: '#F0EDF9',
  ink: '#1A1230',
  inkMuted: 'rgba(26,18,48,0.48)',
  inkFaint: 'rgba(26,18,48,0.08)',
  bg: '#FFFFFF',
  bgWarm: 'linear-gradient(180deg, #FFE3C7 0%, #FFFFFF 52%)',
  gradStops: ['#FFB038', '#FF6363', '#6100FF'],
  font: '"Nunito", -apple-system, system-ui, sans-serif',
  radiusBtn: 100,
  radiusCard: 20,
};

const SCREENS = [
  // 1. WELCOME
  {
    id: 'welcome',
    headline: 'A genius in your pocket',
    sub: 'Your 24/7 AI prof who explains concepts until they finally click.',
    cta: "Let\u2019s meet Professor Curious",
    secondary: 'Already have an account? Log in',
    badge: 'Trusted by 25K+ students · 4.8★',
  },
  // 2. GOAL (single select)
  {
    id: 'goal',
    headline: "What\u2019s your biggest goal right now?",
    sub: "We\u2019ll tell Professor Curious so he can help you get there.",
    cta: "That\u2019s my goal",
    options: [
      { icon: '🎯', label: 'Crush the SAT' },
      { icon: '📚', label: 'Ace the ACT' },
      { icon: '⭐', label: 'Score 5s on AP exams' },
      { icon: '📈', label: 'Boost my grades this semester' },
      { icon: '🆘', label: 'Get homework help fast' },
      { icon: '🤔', label: "Just exploring \u2014 show me what you\u2019ve got" },
    ],
    defaultSelected: 2,
  },
  // 3. PAIN POINTS (multi)
  {
    id: 'pains',
    headline: 'What makes studying hard for you?',
    sub: 'Pick all that apply — no judgement here.',
    cta: 'Continue',
    multi: true,
    options: [
      { icon: '🌙', label: "No one to ask when I\u2019m stuck at night" },
      { icon: '💸', label: 'Tutors are way too expensive' },
      { icon: '🔁', label: 'I study hard but my score barely moves' },
      { icon: '🧭', label: "I don\u2019t know what to focus on" },
      { icon: '🔋', label: 'I lose motivation halfway through' },
      { icon: '😰', label: 'I get anxious before every test' },
      { icon: '😴', label: 'I end up cramming the night before' },
    ],
    defaultSelected: [0, 2, 3],
  },
  // 4. SOCIAL PROOF
  {
    id: 'social',
    headline: "You\u2019re not alone",
    hero: '25,000+ students',
    sub: 'already study smarter with Professor Curious.',
    cta: 'See how it works',
    badge: '4.8 ★ from 2,400+ ratings',
    credibility: 'Built by minds from Stanford, MIT, Caltech & Princeton',
    testimonials: [
      { quote: 'Professor Curious made me actually enjoy studying for the SAT. My score jumped 150 points in 2 months.', name: 'Sarah K.', tag: 'SAT Prep' },
      { quote: "It\u2019s like having a tutor who\u2019s always available. I asked the same question 3 times and it never made me feel dumb.", name: 'Marcus T.', tag: 'AP Chemistry' },
      { quote: 'The scan feature is insane — I take a photo of my homework and get the full explanation in seconds.', name: 'Priya R.', tag: 'Better Grades' },
    ],
  },
  // 5. TINDER CARDS
  {
    id: 'tinder',
    headline: 'Do any of these sound like you?',
    sub: 'Swipe right if yes, left if no.',
    cta: 'Continue',
    cards: [
      'I stare at a problem for 20 minutes, then just skip it.',
      'I study for hours but my test scores barely move.',
      "I\u2019m too embarrassed to ask my teacher to explain it again.",
      'I cram everything the night before and just hope for the best.',
      'I spend more time finding answers online than actually learning.',
    ],
  },
  // 6. PERSONALIZED SOLUTION
  {
    id: 'solution',
    headline: "Here\u2019s how Professor Curious fixes that",
    sub: 'Based on what you told us.',
    cta: 'Set up my professor',
    items: [
      { icon: '⚡', pain: 'Stuck with no one to ask', sol: 'Get step-by-step explanations in under 10 seconds — day or night.' },
      { icon: '📈', pain: 'Studying hard, scores not moving', sol: 'Learn the exam tricks 83% of top scorers use — trap questions, elimination, essay structure.' },
      { icon: '💰', pain: "Can\u2019t afford a tutor", sol: 'Professor Curious costs less than one hour of tutoring — and is available 24/7.' },
      { icon: '🎯', pain: "Don\u2019t know what to focus on", sol: 'AI spots your weak areas and builds a study plan that targets exactly what you need.' },
    ],
  },
  // 7. SUBJECTS (multi)
  {
    id: 'subjects',
    headline: 'What subjects do you need help with?',
    sub: 'Professor Curious will prep for these first.',
    cta: 'Meet my professor',
    multi: true,
    grid: true,
    options: [
      { icon: '📐', label: 'Math' },
      { icon: '🧪', label: 'Science' },
      { icon: '📚', label: 'English' },
      { icon: '🌎', label: 'History' },
      { icon: '💻', label: 'Computer Science' },
      { icon: '🎨', label: 'Arts' },
      { icon: '🧬', label: 'Biology' },
      { icon: '⚛️', label: 'Physics' },
      { icon: '⚗️', label: 'Chemistry' },
      { icon: '💶', label: 'Economics' },
    ],
    defaultSelected: [0, 7, 8],
  },
  // 8. PROCESSING
  {
    id: 'processing',
    lines: [
      'Analyzing your goals…',
      'Finding your weak spots…',
      'Building your study plan…',
      'Waking up Professor Curious…',
    ],
  },
  // 9. SCAN DEMO
  {
    id: 'call',
    headline: 'Try it — call your professor',
    sub: 'Pick something you\u2019ve always wanted explained. Prof will pick up.',
    cta: "Take me in",
    samples: [
      {
        icon: '📐',
        subject: 'Math',
        problem: "Why does dividing by a fraction flip it?",
        steps: [
          "Great one. So \u2014 dividing means \u201chow many of these fit into that?\u201d",
          "If you ask \u201chow many halves fit into 3?\u201d \u2014 it\u2019s 6, right?",
          "That\u2019s the same as 3 \u00d7 2. The flip just turns the question around.",
          "Once you see it that way, you\u2019ll never forget it. \u2728",
        ],
      },
      {
        icon: '🧪',
        subject: 'Chemistry',
        problem: 'Why is salt added to icy roads?',
        steps: [
          'Mmm \u2014 classic. Salt lowers the freezing point of water.',
          'Ice molecules need to lock together. Salt gets in the way.',
          'So even at -5\u00b0C the water stays liquid instead of freezing.',
          'It\u2019s called freezing-point depression. Physics in your driveway. \u2744\ufe0f',
        ],
      },
      {
        icon: '⚛️',
        subject: 'Physics',
        problem: 'Why don\u2019t astronauts feel gravity in space?',
        steps: [
          "Trick question \u2014 they actually do feel gravity!",
          "The ISS is only 400 km up. Gravity there is almost as strong as on Earth.",
          "But the station is constantly falling around the Earth, and so are they.",
          "Free-fall = floating. Mind-bending, right? \ud83d\ude80",
        ],
      },
      {
        icon: '📖',
        subject: 'English',
        problem: 'What\u2019s the difference between metaphor and simile?',
        steps: [
          'Easy one. A simile uses \u201clike\u201d or \u201cas.\u201d',
          '\u201cHer smile was like sunshine\u201d \u2014 simile.',
          'A metaphor just states it: \u201cHer smile was sunshine.\u201d',
          'Same picture. Metaphor just hits harder. \ud83c\udfaf',
        ],
      },
    ],
  },
  // 10. VALUE DELIVERY
  {
    id: 'value',
    headline: 'Your first explanation — solved in seconds',
    sub: 'Imagine this for every problem, every subject, every night.',
    cta: 'Continue',
    share: 'Share with a study buddy',
    stat: 'Students who use Professor Curious daily improve scores by an average of 27%.',
    solveTime: '8 seconds',
  },
  // 11. NOTIFICATIONS
  {
    id: 'notif',
    headline: 'Never lose your study streak',
    sub: 'Quick reminders that keep you on track.',
    cta: 'Enable reminders',
    secondary: 'Not now',
    benefits: [
      { icon: '🔥', text: "Daily study streak reminders \u2014 don\u2019t break the chain" },
      { icon: '🔔', text: '"Professor Curious found a weak spot" \u2014 smart nudges based on your practice' },
      { icon: '🏆', text: "League and challenge updates \u2014 know when you\u2019re climbing" },
    ],
  },
  // 12. PAYWALL
  {
    id: 'paywall',
    headline: 'Your test day confidence starts here',
    sub: 'Start free, cancel anytime.',
    cta: 'Start your FREE 7-day trial',
    testimonial: { quote: 'I went from a 1200 to a 1350 on my SAT. Professor Curious made the difference.', name: 'Jordan M.' },
    plans: [
      { id: 'annual', label: 'Annual', sub: '7-day free trial, then $49.99/yr', per: '$4.17/mo', badge: 'BEST VALUE' },
      { id: 'monthly', label: 'Monthly', sub: 'Billed every month', per: '$19.99/mo' },
    ],
    defaultPlan: 'annual',
    benefits: [
      'Unlimited Scan & Solve',
      '24/7 AI professor access',
      'Personalized study plans',
      'All subjects & exam prep',
      'Flashcards, quizzes & practice tests',
    ],
    fine: 'Cancel anytime during trial. No charge until trial ends.',
    restore: 'Restore purchases',
    more: 'More options',
  },
];

// Progress bar — gradient fill from #FFB038 → #FF6363 → #6100FF
function ProgressBar({ value, total, tokens = TOKENS }) {
  const pct = (value / total) * 100;
  return (
    <div style={{
      width: '100%', height: 6, background: tokens.inkFaint,
      borderRadius: 100, overflow: 'hidden',
    }}>
      <div style={{
        width: `${pct}%`, height: '100%',
        background: `linear-gradient(90deg, ${tokens.gradStops.join(', ')})`,
        borderRadius: 100,
        transition: 'width 420ms cubic-bezier(.2,.8,.2,1)',
      }} />
    </div>
  );
}

// Primary pill button
function PillButton({ children, onClick, disabled, tokens = TOKENS, variant = 'primary' }) {
  const [pressed, setPressed] = React.useState(false);
  const isPrimary = variant === 'primary';
  return (
    <button
      onClick={onClick}
      disabled={disabled}
      onMouseDown={() => setPressed(true)}
      onMouseUp={() => setPressed(false)}
      onMouseLeave={() => setPressed(false)}
      style={{
        width: '100%', height: 56, border: 'none',
        borderRadius: tokens.radiusBtn,
        background: isPrimary ? tokens.primary : 'transparent',
        color: isPrimary ? '#fff' : tokens.primary,
        fontFamily: tokens.font,
        fontWeight: 800, fontSize: 16, letterSpacing: 0.1,
        cursor: disabled ? 'not-allowed' : 'pointer',
        opacity: disabled ? 0.4 : 1,
        boxShadow: isPrimary
          ? (pressed ? `0 1px 0 ${tokens.primaryShadow}` : `0 4px 0 ${tokens.primaryShadow}`)
          : 'none',
        transform: pressed ? 'translateY(3px)' : 'translateY(0)',
        transition: 'transform 80ms, box-shadow 80ms',
      }}
    >{children}</button>
  );
}

// Mascot placeholder — cheeky face in a soft card with moving eyes
function Mascot({ size = 180, tokens = TOKENS, eye = 'smart' }) {
  const [t, setT] = React.useState(0);
  React.useEffect(() => {
    let raf; const start = performance.now();
    const tick = (now) => { setT((now - start) / 1000); raf = requestAnimationFrame(tick); };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, []);
  const look = eye === 'smart' ? Math.sin(t * 1.8) * 3 : 0;
  const blink = Math.sin(t * 0.9) > 0.96 ? 0.12 : 1;
  return (
    <div style={{
      width: size, height: size, borderRadius: '50%',
      background: `radial-gradient(circle at 30% 28%, #FFD9A3, ${tokens.primary})`,
      position: 'relative', boxShadow: `0 16px 40px rgba(105,71,191,0.35)`,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
    }}>
      {/* mortarboard */}
      <div style={{
        position: 'absolute', top: -size * 0.12, left: '50%', transform: 'translateX(-50%) rotate(-8deg)',
        width: size * 0.82, height: size * 0.18, background: '#1A1230',
        borderRadius: 4, boxShadow: '0 2px 0 rgba(0,0,0,0.3)',
      }}>
        <div style={{
          position: 'absolute', top: size * 0.05, left: size * 0.6, width: 2, height: size * 0.22,
          background: '#FFB038',
        }} />
        <div style={{
          position: 'absolute', top: size * 0.24, left: size * 0.58, width: size * 0.1, height: size * 0.1,
          background: '#FFB038', borderRadius: '50%',
        }} />
      </div>
      {/* eyes */}
      <div style={{
        display: 'flex', gap: size * 0.1, marginTop: size * 0.02,
      }}>
        {[0, 1].map(i => (
          <div key={i} style={{
            width: size * 0.16, height: size * 0.16, borderRadius: '50%',
            background: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>
            <div style={{
              width: size * 0.08, height: size * 0.08 * blink, borderRadius: '50%',
              background: '#1A1230', transform: `translateX(${look}px)`,
              transition: 'height 60ms',
            }} />
          </div>
        ))}
      </div>
      {/* smirk */}
      <div style={{
        position: 'absolute', bottom: size * 0.22, width: size * 0.3, height: size * 0.12,
        borderBottom: `${size * 0.04}px solid #1A1230`, borderRadius: '0 0 50% 50%',
      }} />
    </div>
  );
}

// ---------------------------------------------------------------------------
// RevenueCat Web Billing — anonymous web2app flow.
// Anon appUserId is persisted in localStorage so a refresh doesn't fork the
// customer. On mobile, the app aliases this anon ID into the signed-in user
// when the redemption deep-link is opened.
// ---------------------------------------------------------------------------
const RC_CONFIG = {
  apiKey: 'test_weEwySYsBwwUyXhLUDqowuPfNMY',
  offeringId: 'test_offering',
  redeemHost: 'https://dl.zuai.co', // universal-link host registered to the app
};
const RC_ANON_KEY = 'pc_rc_anon_id';

function rcSDK() {
  // UMD bundle exposes window.Purchases (namespace); the class lives at .Purchases.
  const ns = typeof window !== 'undefined' ? window.Purchases : null;
  return ns && ns.Purchases ? ns : null;
}

function rcAnonId() {
  try {
    let id = localStorage.getItem(RC_ANON_KEY);
    if (!id) {
      const sdk = rcSDK();
      id = sdk
        ? sdk.Purchases.generateRevenueCatAnonymousAppUserId()
        : '$RCAnonymousID:' + Math.random().toString(36).slice(2) + Date.now().toString(36);
      localStorage.setItem(RC_ANON_KEY, id);
    }
    return id;
  } catch {
    return '$RCAnonymousID:' + Math.random().toString(36).slice(2) + Date.now().toString(36);
  }
}

let _rcConfigured = false;
function rcInit() {
  if (_rcConfigured) return rcSDK();
  const sdk = rcSDK();
  if (!sdk) return null;
  try {
    sdk.Purchases.configure({ apiKey: RC_CONFIG.apiKey, appUserId: rcAnonId() });
    _rcConfigured = true;
    return sdk;
  } catch (e) {
    console.error('[rc] configure failed', e);
    return null;
  }
}

async function rcGetOffering() {
  const sdk = rcInit();
  if (!sdk) {
    return { ok: false, error: 'SDK not loaded — check the purchases-js <script> in index.html.' };
  }
  let offerings;
  try {
    offerings = await sdk.Purchases.getSharedInstance().getOfferings();
  } catch (e) {
    console.error('[rc] getOfferings rejected', e);
    return { ok: false, error: e?.message || String(e) };
  }
  console.log('[rc] offerings raw', offerings);
  const all = offerings.all || {};
  const off = all[RC_CONFIG.offeringId] || offerings.current;
  if (!off) {
    const keys = Object.keys(all);
    return {
      ok: false,
      error: `Offering "${RC_CONFIG.offeringId}" not found. Available: ${keys.join(', ') || '(none)'}.`,
    };
  }
  // Resolve packages — prefer the canonical .annual/.monthly accessors, then
  // standard package IDs, then pick by package type from availablePackages.
  const pkgs = off.availablePackages || [];
  const byType = (t) => pkgs.find(p => (p.packageType || '').toUpperCase() === t);
  const annual = off.annual
    || off.yearly
    || off.packagesById?.['$rc_annual']
    || off.packagesById?.['$rc_yearly']
    || byType('ANNUAL')
    || byType('YEARLY')
    || null;
  const monthly = off.monthly
    || off.packagesById?.['$rc_monthly']
    || byType('MONTHLY')
    || null;
  if (!annual && !monthly && pkgs.length === 0) {
    return { ok: false, error: `Offering "${off.identifier}" has no packages.` };
  }
  return {
    ok: true,
    raw: off,
    annual,
    monthly,
    fallback: !annual || !monthly ? pkgs : null,
  };
}

async function rcPurchase(pkg) {
  const sdk = rcInit();
  if (!sdk || !pkg) return { ok: false, error: new Error('rc not ready') };
  try {
    const res = await sdk.Purchases.getSharedInstance().purchase({ rcPackage: pkg });
    return { ok: true, customerInfo: res.customerInfo, redemptionInfo: res.redemptionInfo };
  } catch (e) {
    const cancelled = sdk.ErrorCode &&
      e?.errorCode === sdk.ErrorCode.UserCancelledError;
    return { ok: false, cancelled, error: e };
  }
}

// RC returns the redemption URL ready-built when the dashboard has a redeem
// host registered. Fall back to building it from the configured host if the
// SDK only hands back a token. URL spec:
//   <host>/redeem_web_purchase?redemption_token=<TOKEN>
function rcRedeemUrl(redemptionInfo) {
  if (!redemptionInfo) return null;
  if (redemptionInfo.redeemUrl) return redemptionInfo.redeemUrl;
  const token = redemptionInfo.redemptionToken || redemptionInfo.token;
  if (!token) return null;
  return `${RC_CONFIG.redeemHost.replace(/\/$/, '')}/redeem_web_purchase?redemption_token=${encodeURIComponent(token)}`;
}

// Display price helper — packages expose webBillingProduct with currency/price.
function rcPriceLabel(pkg) {
  const p = pkg?.webBillingProduct;
  if (!p) return null;
  if (p.currentPrice?.formattedPrice) return p.currentPrice.formattedPrice;
  if (p.price?.formattedPrice) return p.price.formattedPrice;
  return null;
}

Object.assign(window, {
  TOKENS, SCREENS, ProgressBar, PillButton, Mascot,
  RC_CONFIG, rcInit, rcGetOffering, rcPurchase, rcRedeemUrl, rcPriceLabel,
});
