// W2Go screens — Onboarding flow: Splash, Onboarding, Location, Auth

const { useState: useStateA, useEffect: useEffectA, useRef: useRefA, useMemo: useMemoA } = React;

// ───────────────────────────────────────────────────────────────
// 1. SPLASH
// ───────────────────────────────────────────────────────────────
function SplashScreen({ go }) {
  useEffectA(() => {
    const t = setTimeout(() => go('onboarding'), 2600);
    return () => clearTimeout(t);
  }, []);
  return (
    <div onClick={() => go('onboarding')} style={{
      position: 'absolute', inset: 0, background: 'var(--w-onyx)',
      display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
      color: 'var(--w-cream)', overflow: 'hidden', textAlign: 'center',
    }}>
      {/* subtle brand pattern background */}
      <div style={{
        position: 'absolute', inset: 0,
        background: 'radial-gradient(60% 50% at 50% 35%, rgba(0,76,75,0.55) 0%, rgba(11,15,15,0.2) 60%, #0b0f0f 100%)'
      }}/>
      <img src="assets/box-3d.jpg" alt="" style={{
        position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover',
        opacity: 0.18, mixBlendMode: 'screen', filter: 'blur(1.5px) saturate(1.2)'
      }}/>

      <div style={{ position: 'relative', animation: 'w-fade-up 700ms .15s both' }}>
        <Wordmark size={88} color="#F9F2E8" sub="CRAFTED BY W DOHA"/>
      </div>

      <div style={{
        position: 'absolute', bottom: 80, left: 0, right: 0,
        fontSize: 11, opacity: 0.5, letterSpacing: 3.5, fontWeight: 600,
        animation: 'w-fade-up 700ms .5s both'
      }}>CRAVINGS  ·  DON'T  ·  WAIT</div>
      <div style={{
        position: 'absolute', bottom: 50, left: 0, right: 0,
        fontSize: 10, opacity: 0.32, letterSpacing: 2, fontWeight: 600,
        animation: 'w-fade 1.4s 1s both'
      }}>v1.0 · DOHA, QATAR</div>

      <style>{`
        @keyframes w-fade-up { from { opacity: 0; transform: translateY(14px); } to { opacity: 1; transform: none; } }
        @keyframes w-fade    { from { opacity: 0; } to { opacity: 0.32; } }
      `}</style>
    </div>
  );
}

// ───────────────────────────────────────────────────────────────
// 2. ONBOARDING (3 cards)
// ───────────────────────────────────────────────────────────────
const ONBOARDING = [
  {
    eyebrow: 'WELCOME TO W2GO',
    title: 'Taste every\ncraving.',
    body: 'Sushi, bowls, hot bites — crafted in the W Doha kitchen and sealed for the road.',
    tone: 'cream', img: 'assets/hero-craving.jpg',
  },
  {
    eyebrow: 'FLAVOR ON THE MOVE',
    title: 'From the W\nto your door\nin 30.',
    body: 'One outlet. No third-party. We cook, pack, and dispatch in a single continuous flow.',
    tone: 'green', img: 'assets/hero-marketing.jpg',
  },
  {
    eyebrow: 'CRAFTED BY W DOHA',
    title: 'Cravings\ndon\u2019t wait.',
    body: 'Save the order, reorder in two taps, rate the rider. Every craving lives in one app.',
    tone: 'onyx', img: 'assets/box-with-sushi.jpg',
  },
];

function OnboardingScreen({ go }) {
  const [i, setI] = useStateA(0);
  const step = ONBOARDING[i];
  const next = () => i < ONBOARDING.length - 1 ? setI(i + 1) : go('location');
  const dark = step.tone !== 'cream';
  return (
    <div style={{
      position: 'absolute', inset: 0, paddingTop: 50, boxSizing: 'border-box', background: dark ? (step.tone === 'green' ? 'var(--w-green)' : 'var(--w-onyx)') : 'var(--w-cream)',
      color: dark ? 'var(--w-cream)' : 'var(--w-onyx)',
      display: 'flex', flexDirection: 'column', transition: 'background .35s ease, color .35s ease'
    }}>
      {/* skip */}
      <div style={{ padding: '14px 20px 0', display: 'flex', justifyContent: 'flex-end' }}>
        <button onClick={() => go('location')} style={{
          background: 'none', border: 'none', color: 'inherit', opacity: 0.65,
          fontFamily: 'inherit', fontSize: 13, fontWeight: 600, letterSpacing: 0.5, cursor: 'pointer'
        }}>Skip →</button>
      </div>

      <div style={{ flex: 1, padding: '14px 24px 0', display: 'flex', flexDirection: 'column' }}>
        <div style={{ fontSize: 10.5, letterSpacing: 2.4, fontWeight: 700, opacity: 0.7, marginBottom: 18 }}>{step.eyebrow}</div>
        <Photo tone={step.tone === 'cream' ? 'warm' : (step.tone === 'green' ? 'cream' : 'charcoal')}
               src={step.img} tag={step.tag || 'hero'} height={320} radius={22}/>
        <div style={{
          fontSize: 42, lineHeight: 1.04, fontWeight: 800, marginTop: 26, whiteSpace: 'pre-line',
          letterSpacing: -1.2,
        }}>{step.title}</div>
        <div style={{
          marginTop: 14, fontSize: 15, lineHeight: 1.5, opacity: 0.78, fontWeight: 400, maxWidth: 320,
          textWrap: 'pretty'
        }}>{step.body}</div>
      </div>

      <div style={{ padding: '14px 24px 38px' }}>
        {/* dots */}
        <div style={{ display: 'flex', gap: 6, marginBottom: 18, alignItems: 'center' }}>
          {ONBOARDING.map((_, idx) => (
            <span key={idx} style={{
              height: 4, width: idx === i ? 32 : 12, borderRadius: 4,
              background: idx === i ? 'currentColor' : (dark ? 'rgba(255,255,255,0.25)' : 'rgba(23,25,25,0.15)'),
              transition: 'width .25s ease'
            }}/>
          ))}
        </div>
        <Btn full kind={dark ? 'cream' : 'primary'} onClick={next}
             iconRight={<Ic.Arrow size={18}/>}>
          {i === ONBOARDING.length - 1 ? 'Get started' : 'Next'}
        </Btn>
      </div>
    </div>
  );
}

// ───────────────────────────────────────────────────────────────
// 3. LOCATION
// ───────────────────────────────────────────────────────────────
function LocationScreen({ go, setAddress }) {
  const [q, setQ] = useStateA('');
  const filtered = W2_ADDRESSES.filter(a =>
    !q || (a.line + ' ' + a.city + ' ' + a.label).toLowerCase().includes(q.toLowerCase())
  );
  const pick = (a) => { setAddress(a); go('auth'); };
  return (
    <div style={{ position: 'absolute', inset: 0, paddingTop: 50, boxSizing: 'border-box', background: 'var(--w-cream)', display: 'flex', flexDirection: 'column' }}>
      {/* Map placeholder hero */}
      <div style={{ position: 'relative', height: 240 }}>
        <Photo tone="green" tag="map · w2go outlet + drop zone" height="100%" radius={0}/>
        {/* fake roads */}
        <svg width="100%" height="100%" style={{ position: 'absolute', inset: 0 }}>
          <path d="M-20,170 Q120,140 200,180 T440,150" stroke="rgba(249,242,232,0.18)" strokeWidth="22" fill="none"/>
          <path d="M0,80 Q90,100 160,70 T420,90" stroke="rgba(249,242,232,0.12)" strokeWidth="14" fill="none"/>
          <circle cx="190" cy="180" r="8" fill="#F9F2E8"/>
          <circle cx="190" cy="180" r="14" fill="none" stroke="#F9F2E8" strokeOpacity="0.4" strokeWidth="1.5"/>
        </svg>
        {/* pin */}
        <div style={{
          position: 'absolute', left: '50%', top: '46%', transform: 'translate(-50%, -100%)',
          color: 'var(--w-cream)', filter: 'drop-shadow(0 6px 8px rgba(0,0,0,0.3))'
        }}>
          <Ic.Pin size={44}/>
        </div>
      </div>

      <div style={{ flex: 1, padding: '24px 20px', display: 'flex', flexDirection: 'column' }}>
        <div style={{ fontSize: 32, fontWeight: 800, letterSpacing: -0.8, lineHeight: 1.05 }}>Where to?</div>
        <div style={{ fontSize: 14, opacity: 0.6, marginTop: 6, fontWeight: 500 }}>We deliver from the W2GO outlet within 4 miles.</div>

        <div style={{
          marginTop: 22, display: 'flex', alignItems: 'center', gap: 10,
          background: '#fff', borderRadius: 16, padding: '14px 16px',
          border: '1px solid rgba(23,25,25,0.08)'
        }}>
          <Ic.Search size={20} style={{ color: 'rgba(23,25,25,0.45)' }}/>
          <input value={q} onChange={e => setQ(e.target.value)}
                 placeholder="Enter your delivery address"
                 style={{
                   flex: 1, border: 'none', outline: 'none', background: 'transparent',
                   fontFamily: 'inherit', fontSize: 15, color: 'var(--w-onyx)'
                 }}/>
        </div>

        <button onClick={() => pick(W2_ADDRESSES[0])} style={{
          marginTop: 12, padding: '14px 16px', borderRadius: 16,
          background: 'rgba(0,76,75,0.08)', border: '1px dashed rgba(0,76,75,0.4)',
          display: 'flex', alignItems: 'center', gap: 12, color: 'var(--w-green)',
          fontFamily: 'inherit', fontWeight: 600, fontSize: 14, cursor: 'pointer'
        }}>
          <Ic.Crosshair size={20}/> Use my current location
        </button>

        <div style={{ fontSize: 10.5, letterSpacing: 2, opacity: 0.55, fontWeight: 700, margin: '24px 0 10px' }}>
          SAVED ADDRESSES
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {filtered.map(a => (
            <button key={a.id} onClick={() => pick(a)} style={{
              padding: '14px 16px', borderRadius: 16, background: '#fff',
              border: '1px solid rgba(23,25,25,0.08)', display: 'flex', gap: 14,
              alignItems: 'center', textAlign: 'left', cursor: 'pointer', fontFamily: 'inherit'
            }}>
              <div style={{
                width: 40, height: 40, borderRadius: 12, background: 'rgba(0,76,75,0.1)',
                color: 'var(--w-green)', display: 'flex', alignItems: 'center', justifyContent: 'center'
              }}><Ic.Pin size={20}/></div>
              <div style={{ flex: 1 }}>
                <div style={{ fontWeight: 700, fontSize: 14, display: 'flex', gap: 8, alignItems: 'center' }}>
                  {a.label}
                  {a.tag && <span style={{ fontSize: 9, letterSpacing: 1.2, fontWeight: 700, padding: '2px 6px', background: 'var(--w-green)', color: 'var(--w-cream)', borderRadius: 4 }}>{a.tag.toUpperCase()}</span>}
                </div>
                <div style={{ fontSize: 12.5, opacity: 0.65, marginTop: 2 }}>{a.line} · {a.city}</div>
              </div>
              <Ic.ChevronR size={18} style={{ opacity: 0.4 }}/>
            </button>
          ))}
          {filtered.length === 0 && (
            <div style={{ padding: 16, fontSize: 13, opacity: 0.6 }}>No saved addresses match.</div>
          )}
        </div>
      </div>
    </div>
  );
}

// ───────────────────────────────────────────────────────────────
// 4. AUTH — Phone + OTP
// ───────────────────────────────────────────────────────────────
function AuthScreen({ go, setUser }) {
  const [stage, setStage] = useStateA('phone'); // 'phone' | 'otp' | 'name'
  const [phone, setPhone] = useStateA('');
  const [otp, setOtp] = useStateA(['', '', '', '']);
  const [name, setName] = useStateA('');

  const validPhone = phone.replace(/\D/g, '').length >= 9;

  return (
    <div style={{ position: 'absolute', inset: 0, paddingTop: 50, boxSizing: 'border-box', background: 'var(--w-onyx)', color: 'var(--w-cream)',
                  display: 'flex', flexDirection: 'column' }}>
      <TopBar dark transparent onBack={() => stage === 'phone' ? go('location') : setStage('phone')}/>

      <div style={{ flex: 1, padding: '8px 24px 24px', display: 'flex', flexDirection: 'column' }}>
        <div style={{ marginTop: 8 }}><Wordmark size={36} color="var(--w-cream)" sub={null}/></div>

        {stage === 'phone' && <>
          <div style={{ fontSize: 34, fontWeight: 800, letterSpacing: -0.8, lineHeight: 1.05, marginTop: 28 }}>
            Let's get<br/>you set.
          </div>
          <div style={{ opacity: 0.65, marginTop: 8, fontSize: 14 }}>One number. One tap. No passwords.</div>

          <div style={{
            marginTop: 30, display: 'flex', gap: 10, background: 'rgba(255,255,255,0.08)',
            borderRadius: 16, padding: '14px 16px', alignItems: 'center'
          }}>
            <span style={{ fontWeight: 700, fontSize: 16 }}>🇶🇦 +974</span>
            <span style={{ width: 1, height: 22, background: 'rgba(255,255,255,0.18)' }}/>
            <input value={phone} onChange={e => setPhone(e.target.value)}
                   placeholder="5000 1234" inputMode="tel"
                   style={{
                     flex: 1, border: 'none', outline: 'none', background: 'transparent',
                     color: 'var(--w-cream)', fontFamily: 'inherit', fontSize: 17, fontWeight: 600,
                     letterSpacing: 1
                   }}/>
          </div>

          <div style={{ marginTop: 22 }}>
            <Btn full disabled={!validPhone} onClick={() => setStage('otp')} kind="cream"
                 iconRight={<Ic.Arrow size={18}/>}>Continue</Btn>
          </div>

          <div style={{ display: 'flex', alignItems: 'center', gap: 10, margin: '28px 0 18px', opacity: 0.55 }}>
            <div style={{ flex: 1, height: 1, background: 'rgba(255,255,255,0.2)' }}/>
            <span style={{ fontSize: 11, letterSpacing: 1.4, fontWeight: 600 }}>OR</span>
            <div style={{ flex: 1, height: 1, background: 'rgba(255,255,255,0.2)' }}/>
          </div>

          <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            <Btn full kind="ghostInv" icon={<Ic.Apple size={18}/>} onClick={() => { setUser({ name: 'Friend', phone: '+974 5000 0000' }); go('home'); }}>Continue with Apple</Btn>
            <Btn full kind="ghostInv" icon={<Ic.Google size={18}/>} onClick={() => { setUser({ name: 'Friend', phone: '+974 5000 0000' }); go('home'); }}>Continue with Google</Btn>
          </div>

          <div style={{ marginTop: 'auto', fontSize: 11, opacity: 0.45, textAlign: 'center', lineHeight: 1.6 }}>
            By continuing you agree to W2GO's<br/>
            <u>Terms</u> and <u>Privacy Policy</u>.
          </div>
        </>}

        {stage === 'otp' && <>
          <div style={{ fontSize: 30, fontWeight: 800, letterSpacing: -0.7, lineHeight: 1.05, marginTop: 28 }}>
            We sent a code.
          </div>
          <div style={{ opacity: 0.65, marginTop: 8, fontSize: 14 }}>
            4-digit code sent to <b style={{ color: 'var(--w-cream)' }}>+974 {phone}</b>.
          </div>

          <div style={{ marginTop: 30, display: 'flex', gap: 12, justifyContent: 'space-between' }}>
            {otp.map((d, i) => (
              <div key={i} style={{
                flex: 1, height: 64, borderRadius: 14,
                background: 'rgba(255,255,255,0.08)',
                border: '1.5px solid ' + (d ? 'var(--w-cream)' : 'rgba(255,255,255,0.12)'),
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontSize: 28, fontWeight: 700
              }}>{d || ''}</div>
            ))}
          </div>

          {/* numeric pad */}
          <div style={{ marginTop: 'auto', display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8 }}>
            {[1,2,3,4,5,6,7,8,9,'',0,'<'].map((k, i) => (
              <button key={i} onClick={() => {
                if (k === '<') {
                  const next = [...otp];
                  for (let j = next.length - 1; j >= 0; j--) { if (next[j]) { next[j] = ''; break; } }
                  setOtp(next);
                } else if (k !== '') {
                  const next = [...otp];
                  const j = next.findIndex(x => !x);
                  if (j !== -1) { next[j] = String(k); setOtp(next); if (j === 3) setTimeout(() => setStage('name'), 250); }
                }
              }} style={{
                height: 54, borderRadius: 14, border: 'none',
                background: k === '' ? 'transparent' : 'rgba(255,255,255,0.06)',
                color: 'var(--w-cream)', fontFamily: 'inherit', fontSize: 22, fontWeight: 700,
                cursor: k === '' ? 'default' : 'pointer'
              }}>{k}</button>
            ))}
          </div>
        </>}

        {stage === 'name' && <>
          <div style={{ fontSize: 32, fontWeight: 800, letterSpacing: -0.8, lineHeight: 1.05, marginTop: 28 }}>
            What should<br/>we call you?
          </div>
          <div style={{ opacity: 0.65, marginTop: 8, fontSize: 14 }}>One field. We don't need a life story.</div>

          <input value={name} onChange={e => setName(e.target.value)} autoFocus
                 placeholder="Your name"
                 style={{
                   marginTop: 30, height: 60, borderRadius: 16, padding: '0 18px',
                   background: 'rgba(255,255,255,0.08)', border: '1.5px solid rgba(255,255,255,0.12)',
                   color: 'var(--w-cream)', fontFamily: 'inherit', fontSize: 18, fontWeight: 600,
                   outline: 'none',
                 }}/>

          <div style={{ marginTop: 'auto', paddingBottom: 14 }}>
            <Btn full disabled={!name.trim()} onClick={() => {
              setUser({ name: name.trim() || 'Friend', phone: '+974 ' + phone });
              go('home');
            }} kind="cream" iconRight={<Ic.Arrow size={18}/>}>Enter W2GO</Btn>
          </div>
        </>}
      </div>
    </div>
  );
}

Object.assign(window, { SplashScreen, OnboardingScreen, LocationScreen, AuthScreen });
