// screen-onboarding.jsx — Multi-step connect + brand import + plan selection
// Exports: OnboardingScreen

const PLAN_DATA = [
  {
    id: 'starter', name: 'Starter', price: '$100', period: '/mo',
    desc: 'For merchants just getting started with a mobile app.',
    features: ['Push notifications (limited)', 'Core app screens', 'Judge.me reviews', 'Email support', 'A/B testing (2 variants)'],
    highlight: false,
  },
  {
    id: 'growth', name: 'Growth', price: '$200', period: '/mo',
    desc: 'Most popular. Full feature set, 30-day free trial.',
    features: ['Push notifications (higher limit)', 'All app screens + editor', '5+ integrations', 'Priority email support', 'Up to 5 A/Z variants', 'Up to 3 team members'],
    highlight: true, trial: '30-day free trial',
  },
  {
    id: 'pro', name: 'Pro', price: '$300', period: '/mo',
    desc: 'For power merchants who need everything, unlimited.',
    features: ['Unlimited push campaigns', 'All integrations', 'Unlimited A/Z testing (2–26 variants)', 'Priority chat support', 'Unlimited team members', 'Custom components'],
    highlight: false,
  },
];

const OnboardingScreen = ({ onComplete, persona }) => {
  const [step, setStep] = React.useState(1);
  const [importProgress, setImportProgress] = React.useState(0);
  const [importStage, setImportStage] = React.useState(0);
  const [selectedPlan, setSelectedPlan] = React.useState('growth');
  const [animateIn, setAnimateIn] = React.useState(true);

  const STEPS = [
    { n: 1, label: 'Connect' },
    { n: 2, label: 'Import' },
    { n: 3, label: 'Preview' },
    { n: 4, label: 'Choose plan' },
  ];

  const importStages = [
    { label: 'Connecting to Shopify…', pct: 15 },
    { label: 'Importing brand kit…', pct: 35 },
    { label: 'Loading products…', pct: 58 },
    { label: 'Syncing collections…', pct: 75 },
    { label: 'Building your app preview…', pct: 92 },
    { label: 'Done!', pct: 100 },
  ];

  // Animate progress when on step 2
  React.useEffect(() => {
    if (step !== 2) return;
    setImportProgress(0); setImportStage(0);
    let stage = 0;
    const tick = () => {
      if (stage >= importStages.length - 1) { setTimeout(() => setStep(3), 800); return; }
      stage++;
      setImportStage(stage);
      setImportProgress(importStages[stage].pct);
      setTimeout(tick, stage === importStages.length - 1 ? 400 : 700);
    };
    setTimeout(tick, 500);
  }, [step]);

  const goTo = (n) => { setAnimateIn(false); setTimeout(() => { setStep(n); setAnimateIn(true); }, 120); };

  // ---- STEP 1: Connect ----
  const Step1 = () => (
    <div style={{ maxWidth: 480, margin: '0 auto', display: 'flex', flexDirection: 'column', gap: 28 }}>
      <div>
        <div style={{ fontFamily: 'var(--font-ui)', fontSize: 10, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--fg-3)', fontWeight: 500, marginBottom: 8 }}>Step 1 of 4</div>
        <h1 style={{ fontFamily: 'var(--font-display)', fontStyle: 'italic', fontSize: 40, lineHeight: 1.05, letterSpacing: '-0.02em', color: 'var(--ink)', margin: 0 }}>Connect your Shopify store.</h1>
        <p style={{ fontSize: 15, color: 'var(--fg-2)', lineHeight: 1.55, marginTop: 12, marginBottom: 0 }}>We use Shopify OAuth — no passwords, no API keys. One click and we pull in your brand, products, and collections automatically.</p>
      </div>

      <div style={{ background: 'var(--white)', border: '1px solid var(--hairline)', borderRadius: 12, padding: 24, display: 'flex', flexDirection: 'column', gap: 16 }}>
        <window.Input label="Your Shopify store URL" prefix="https://" value={persona.domain} placeholder="your-store.myshopify.com" help="We connect via OAuth — no password needed." />
        <window.Button size="lg" onClick={() => goTo(2)} style={{ width: '100%', justifyContent: 'center' }}>
          Connect with Shopify →
        </window.Button>
        <p style={{ fontSize: 12, color: 'var(--fg-3)', textAlign: 'center', margin: 0 }}>You'll be redirected to Shopify to authorize. Takes about 5 seconds.</p>
      </div>

      <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap' }}>
        {['OAuth 2.0 secure', 'Read-only access', 'Disconnect anytime'].map(f => (
          <div key={f} style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 12, color: 'var(--fg-2)' }}>
            <i data-lucide="check" style={{ width: 13, height: 13, color: 'var(--mint)' }}></i> {f}
          </div>
        ))}
      </div>
    </div>
  );

  // ---- STEP 2: Import animation ----
  const Step2 = () => (
    <div style={{ maxWidth: 480, margin: '0 auto', display: 'flex', flexDirection: 'column', gap: 32, alignItems: 'center', textAlign: 'center' }}>
      <div>
        <h1 style={{ fontFamily: 'var(--font-display)', fontStyle: 'italic', fontSize: 40, lineHeight: 1.05, color: 'var(--ink)', margin: '0 0 12px' }}>Building your app…</h1>
        <p style={{ fontSize: 15, color: 'var(--fg-2)', margin: 0 }}>We're pulling in your brand, products, and collections from Shopify.</p>
      </div>

      <div style={{ width: '100%', background: 'var(--white)', border: '1px solid var(--hairline)', borderRadius: 12, padding: 28, display: 'flex', flexDirection: 'column', gap: 20 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
          <div style={{ width: 44, height: 44, borderRadius: 12, background: 'var(--ink)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
            <window.Spinner size={20} color="var(--honey)" />
          </div>
          <div style={{ flex: 1, textAlign: 'left' }}>
            <div style={{ fontSize: 14, fontWeight: 500, color: 'var(--ink)', marginBottom: 4 }}>{importStages[importStage]?.label}</div>
            <window.ProgressBar value={importProgress} />
          </div>
          <div style={{ fontFamily: 'var(--font-mono)', fontSize: 13, color: 'var(--fg-2)', flexShrink: 0 }}>{importProgress}%</div>
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
          {importStages.slice(1).map((s, i) => {
            const done = importStage > i + 1;
            const active = importStage === i + 1;
            return (
              <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 10, opacity: active || done ? 1 : 0.3, transition: 'opacity 300ms var(--ease)' }}>
                <div style={{ width: 18, height: 18, borderRadius: '50%', background: done ? 'var(--mint-tint)' : active ? 'var(--honey-tint)' : 'var(--sand-100)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                  {done ? <i data-lucide="check" style={{ width: 10, height: 10, color: 'var(--mint)' }}></i>
                    : active ? <div style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--honey)' }}></div>
                    : null}
                </div>
                <span style={{ fontSize: 12, color: done ? 'var(--fg-2)' : active ? 'var(--ink)' : 'var(--fg-4)', fontWeight: active ? 500 : 400 }}>{s.label}</span>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );

  // ---- STEP 3: Preview moment ----
  const Step3 = () => (
    <div style={{ display: 'flex', gap: 64, alignItems: 'center', justifyContent: 'center', flexWrap: 'wrap' }}>
      <div style={{ maxWidth: 400 }}>
        <div style={{ fontSize: 10, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--fg-3)', fontWeight: 500, marginBottom: 8 }}>Your store, as an app</div>
        <h1 style={{ fontFamily: 'var(--font-display)', fontStyle: 'italic', fontSize: 44, lineHeight: 1.0, letterSpacing: '-0.02em', color: 'var(--ink)', margin: '0 0 16px' }}>
          {persona.id === 'nour' ? 'يا سلام.' : 'There it is.'}
        </h1>
        <p style={{ fontSize: 15, color: 'var(--fg-2)', lineHeight: 1.6, marginBottom: 28 }}>
          That's your store — your brand colors, your products, your logo. A fully native app, ready for the App Store. We imported {persona.id === 'nour' ? '340 products and 12 collections' : '1,248 products and 24 collections'} from your Shopify store.
        </p>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginBottom: 28 }}>
          {[
            { icon: 'check-circle', text: `Brand kit imported — ${persona.id === 'nour' ? 'Honey + Ink palette' : 'Dark + Carbon palette'}` },
            { icon: 'check-circle', text: `${persona.id === 'nour' ? '340' : '1,248'} products synced` },
            { icon: 'check-circle', text: 'Native checkout ready (Apple Pay + Shop Pay)' },
            { icon: 'check-circle', text: 'RTL layout ready for Arabic' },
          ].map(item => (
            <div key={item.text} style={{ display: 'flex', alignItems: 'flex-start', gap: 10, fontSize: 13, color: 'var(--fg-1)' }}>
              <i data-lucide={item.icon} style={{ width: 16, height: 16, color: 'var(--mint)', marginTop: 1, flexShrink: 0 }}></i>
              {item.text}
            </div>
          ))}
        </div>
        <window.Button size="lg" onClick={() => goTo(4)}>Choose your plan →</window.Button>
      </div>
      <window.MobileApp persona={persona} scale={0.9} />
    </div>
  );

  // ---- STEP 4: Plan selection ----
  const Step4 = () => (
    <div style={{ maxWidth: 860, margin: '0 auto' }}>
      <div style={{ textAlign: 'center', marginBottom: 36 }}>
        <div style={{ fontSize: 10, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--fg-3)', fontWeight: 500, marginBottom: 8 }}>All features included at every tier</div>
        <h1 style={{ fontFamily: 'var(--font-display)', fontStyle: 'italic', fontSize: 40, lineHeight: 1.05, color: 'var(--ink)', margin: 0 }}>Simple, all-inclusive pricing.</h1>
        <p style={{ fontSize: 15, color: 'var(--fg-2)', marginTop: 12, marginBottom: 0 }}>No per-feature fees. No surprises. Just one monthly price. Start with a 30-day free trial on Growth.</p>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 16, marginBottom: 28 }}>
        {PLAN_DATA.map(plan => (
          <div key={plan.id} onClick={() => setSelectedPlan(plan.id)} style={{
            background: selectedPlan === plan.id ? 'var(--ink)' : 'var(--white)',
            border: `2px solid ${selectedPlan === plan.id ? 'var(--ink)' : plan.highlight ? 'var(--honey)' : 'var(--hairline)'}`,
            borderRadius: 14, padding: 24, cursor: 'pointer',
            transition: 'all 200ms var(--ease)',
            color: selectedPlan === plan.id ? 'var(--paper)' : 'var(--ink)',
            position: 'relative',
          }}>
            {plan.trial && selectedPlan !== plan.id && (
              <div style={{ position: 'absolute', top: -10, left: '50%', transform: 'translateX(-50%)', background: 'var(--honey)', color: 'var(--ink)', fontSize: 10, fontWeight: 600, padding: '3px 10px', borderRadius: 999, whiteSpace: 'nowrap' }}>
                {plan.trial}
              </div>
            )}
            <div style={{ fontSize: 12, fontWeight: 600, letterSpacing: '0.05em', textTransform: 'uppercase', marginBottom: 8, color: selectedPlan === plan.id ? 'rgba(245,241,232,0.6)' : 'var(--fg-3)' }}>{plan.name}</div>
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 2, marginBottom: 8 }}>
              <span style={{ fontFamily: 'var(--font-display)', fontStyle: 'italic', fontSize: 36, lineHeight: 1 }}>{plan.price}</span>
              <span style={{ fontSize: 12, opacity: 0.6 }}>{plan.period}</span>
            </div>
            <div style={{ fontSize: 12, opacity: 0.7, marginBottom: 16, lineHeight: 1.5 }}>{plan.desc}</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
              {plan.features.map(f => (
                <div key={f} style={{ display: 'flex', alignItems: 'flex-start', gap: 7, fontSize: 12 }}>
                  <i data-lucide="check" style={{ width: 13, height: 13, flexShrink: 0, marginTop: 1, color: selectedPlan === plan.id ? 'var(--honey)' : 'var(--mint)' }}></i>
                  <span style={{ opacity: 0.9 }}>{f}</span>
                </div>
              ))}
            </div>
          </div>
        ))}
      </div>

      <div style={{ display: 'flex', justifyContent: 'center', gap: 12 }}>
        <window.Button variant="secondary" onClick={() => goTo(3)}>← Back</window.Button>
        <window.Button size="lg" onClick={onComplete}>
          {selectedPlan === 'growth' ? 'Start 30-day free trial →' : `Start with ${PLAN_DATA.find(p => p.id === selectedPlan)?.name} →`}
        </window.Button>
      </div>
      <div style={{ textAlign: 'center', marginTop: 12, fontSize: 12, color: 'var(--fg-3)' }}>No charge today. Cancel anytime.</div>
    </div>
  );

  const stepContent = { 1: <Step1 />, 2: <Step2 />, 3: <Step3 />, 4: <Step4 /> };

  return (
    <div style={{ minHeight: '100vh', background: 'var(--paper)', display: 'flex', flexDirection: 'column' }}>
      {/* Header */}
      <div style={{ height: 64, display: 'flex', alignItems: 'center', padding: '0 40px', borderBottom: '1px solid var(--hairline)', background: 'var(--bg)', flexShrink: 0 }}>
        <img src="assets/logo-lockup.svg" alt="Shoplix" style={{ height: 22 }} />
        <div style={{ flex: 1 }}></div>
        {/* Step dots */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 20 }}>
          {STEPS.map(s => (
            <div key={s.n} style={{ display: 'flex', alignItems: 'center', gap: 7, opacity: step < s.n ? 0.35 : 1 }}>
              <div style={{ width: 22, height: 22, borderRadius: '50%', background: step > s.n ? 'var(--mint)' : step === s.n ? 'var(--ink)' : 'var(--sand-100)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 11, fontWeight: 600, color: step === s.n ? 'var(--paper)' : step > s.n ? 'var(--white)' : 'var(--fg-3)', transition: 'all 250ms var(--ease)' }}>
                {step > s.n ? <i data-lucide="check" style={{ width: 11, height: 11 }}></i> : s.n}
              </div>
              <span style={{ fontSize: 12, fontWeight: step === s.n ? 500 : 400, color: step === s.n ? 'var(--ink)' : 'var(--fg-3)' }}>{s.label}</span>
              {s.n < STEPS.length && <div style={{ width: 24, height: 1, background: 'var(--hairline)', marginLeft: 6 }}></div>}
            </div>
          ))}
        </div>
      </div>

      {/* Content */}
      <div style={{ flex: 1, display: 'flex', alignItems: step === 3 ? 'center' : 'flex-start', justifyContent: 'center', padding: step === 3 ? '48px 40px' : '64px 40px', opacity: animateIn ? 1 : 0, transition: 'opacity 120ms var(--ease)', overflowY: 'auto' }}>
        {stepContent[step]}
      </div>
    </div>
  );
};

window.OnboardingScreen = OnboardingScreen;
window.PLAN_DATA = PLAN_DATA;
