/* ── Zafa — onboarding, role, phone/OTP, profile setup ──────────────── */

/* small EN/AR toggle */
function LangToggle({ dark }) {
  const { lang, setLang } = useZafa();
  return (
    <div style={{ display: 'flex', gap: 2, background: dark ? 'rgba(255,255,255,.18)' : '#fff', border: dark ? 'none' : '1px solid var(--line)', borderRadius: 999, padding: 3, backdropFilter: 'blur(8px)' }}>
      {['en', 'ar'].map((l) =>
      <button key={l} onClick={() => setLang(l)} style={{ width: 38, height: 30, borderRadius: 999, border: 'none', cursor: 'pointer',
        background: lang === l ? 'var(--rose)' : 'transparent', color: lang === l ? 'var(--ink)' : dark ? '#fff' : 'var(--ink-2)',
        fontWeight: 700, fontSize: 12, fontFamily: l === 'ar' ? 'var(--serif)' : 'var(--sans)' }}>{l === 'ar' ? 'ع' : 'EN'}</button>
      )}
    </div>);

}

/* numeric keypad */
function Keypad({ onKey, onBack }) {
  const keys = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '', '0', 'del'];
  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 10, padding: '4px 6px' }}>
      {keys.map((k, i) => {
        if (k === '') return <div key={i} />;
        const del = k === 'del';
        return (
          <button key={i} onClick={() => del ? onBack() : onKey(k)}
          style={{ height: 54, borderRadius: 16, border: 'none', cursor: 'pointer', background: del ? 'transparent' : '#fff',
            boxShadow: del ? 'none' : 'var(--sh-sm)', fontFamily: 'var(--sans)', fontSize: 24, fontWeight: 600, color: 'var(--ink)',
            display: 'flex', alignItems: 'center', justifyContent: 'center', transition: 'transform .1s' }}
          onMouseDown={(e) => e.currentTarget.style.transform = 'scale(.94)'}
          onMouseUp={(e) => e.currentTarget.style.transform = 'scale(1)'}
          onMouseLeave={(e) => e.currentTarget.style.transform = 'scale(1)'}>
            {del ? <Icon name="left" size={24} className="flip-x" /> : k}
          </button>);

      })}
    </div>);

}

/* ── Onboarding: 3 slides ── */
function Onboarding({ onDone }) {
  const { lang } = useZafa();
  const rtl = lang === 'ar';
  const [i, setI] = React.useState(0);
  const s = ONBOARDING[i];
  const last = i === ONBOARDING.length - 1;
  const next = () => last ? onDone() : setI(i + 1);
  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: 'var(--bg)', position: 'relative', overflow: 'hidden' }}>
      {/* centered brand logo at top */}
      <img src={window.ASSET('logo')} alt="" style={{ position: 'absolute', top: 16, insetInlineStart: '50%', transform: 'translateX(-50%)', height: 38, zIndex: 3 }} />
      {/* decorative floral watermark — right side, under the image */}
      <img src={window.ASSET('floral')} alt="" aria-hidden="true" style={{ position: 'absolute', top: 392, insetInlineEnd: -46, width: 200, height: 'auto', opacity: .5, pointerEvents: 'none', zIndex: 0, transform: rtl ? 'scaleX(-1)' : 'none' }} />
      {/* hero arched art */}
      <div style={{ position: 'relative', padding: '60px 16px 0', zIndex: 1 }}>
        <div className="arch" style={{ height: 366 }}>
          <CoverArt key={s.theme + i} theme={s.theme} icon={s.icon} src={i === 0 ? window.ASSET('onbVenue') : i === 1 ? window.ASSET('onbExplore') : window.ASSET('onbConnect')} kw={['wedding,venue,ceremony', 'bouquet', 'celebration'][i] || 'wedding'} id={`onb-${i}`} seed={['onbVenue', 'onb1', 'onb2'][i]} w={800} h={760} ph={L(lang, 'Add image', 'أضف صورة')} />
        </div>
        <div style={{ position: 'absolute', top: 74, insetInlineStart: 24 }}><LangToggle dark /></div>
        <button onClick={onDone} style={{ position: 'absolute', top: 76, insetInlineEnd: 26, background: 'rgba(255,255,255,.85)', border: 'none', borderRadius: 999, padding: '7px 14px', fontWeight: 600, fontSize: 13, color: 'var(--ink)', cursor: 'pointer', fontFamily: 'var(--sans)' }}>{L(lang, 'Skip', 'تخطّي')}</button>
      </div>

      {/* copy */}
      <div className="fade-up" key={i} style={{ flex: 1, padding: '34px 26px 0', display: 'flex', flexDirection: 'column' }}>
        <span className="eyebrow">{L(lang, s.eyebrowEn, s.eyebrowAr)}</span>
        <h1 className="h1" style={{ margin: '12px 0 12px', fontSize: 32, whiteSpace: 'pre-line' }}>{L(lang, s.titleEn, s.titleAr)}</h1>
        <p className="sec" style={{ margin: 0, fontSize: 15.5, lineHeight: 1.55, textWrap: 'pretty' }}>{L(lang, s.bodyEn, s.bodyAr)}</p>
      </div>

      {/* controls */}
      <div style={{ padding: '18px 26px 30px', display: 'flex', alignItems: 'center', gap: 16 }}>
        <div style={{ display: 'flex', gap: 7, alignItems: 'center', flex: 1 }}>
          {ONBOARDING.map((_, k) => <i key={k} onClick={() => setI(k)} style={{ display: 'block', height: 7, width: k === i ? 22 : 7, borderRadius: 99, background: k === i ? 'var(--rose)' : 'var(--line)', transition: 'all .25s', cursor: 'pointer' }} />)}
        </div>
        <button onClick={next} className="z-btn z-btn--rose" style={{ width: last ? 'auto' : 60, padding: last ? '0 26px' : 0, height: 60, borderRadius: last ? 16 : '50%', flexShrink: 0 }}>
          {last ? <>{L(lang, 'Get started', 'لنبدأ')}<Icon name="arrow" size={19} className="flip-x" /></> : <Icon name="arrow" size={24} className="flip-x" />}
        </button>
      </div>
    </div>);

}

/* ── Who's signing in? ── */
function RoleSelect({ onContinue }) {
  const { lang, t } = useZafa();
  const [sel, setSel] = React.useState('customer');
  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: 'var(--bg)', padding: '8px 22px 26px', position: 'relative' }}>
      <div style={{ position: 'relative', display: 'flex', justifyContent: 'flex-end', alignItems: 'center', minHeight: 38, paddingTop: 4, zIndex: 1 }}>
        <img src={window.ASSET('logo')} alt="" style={{ height: 38, position: 'absolute', left: '50%', top: '50%', transform: 'translate(-50%, -50%)' }} />
        <LangToggle />
      </div>
      <div style={{ marginTop: 26, position: 'relative', zIndex: 1 }}>
        <h1 className="h1" style={{ margin: 0, fontSize: 30 }}>{t('whoSigning')}</h1>
        <p className="sec" style={{ margin: '8px 0 0', fontSize: 15 }}>{t('whoSub')}</p>
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 13, marginTop: 26, flex: 1, position: 'relative', zIndex: 1 }}>
        {PERSONAS.map((p) => {
          const on = sel === p.id;
          return (
            <div key={p.id}>
              <button className={`z-persona${on ? ' z-persona--on' : ''}`} onClick={() => setSel(p.id)}>
                <div style={{ width: 54, height: 54, borderRadius: 16, flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'center',
                  background: p.orbBg, color: p.orbIc }}>
                  <Icon name={p.icon} size={26} stroke={1.9} />
                </div>
                <div style={{ flex: 1 }}>
                  <h3 className="serif" style={{ margin: 0, fontSize: 18, fontWeight: 600 }}>{L(lang, p.titleEn, p.titleAr)}</h3>
                  <p className="sec" style={{ margin: '3px 0 0', fontSize: 13, lineHeight: 1.4 }}>{L(lang, p.descEn, p.descAr)}</p>
                </div>
                <div className="z-persona-radio" style={{ width: 24, height: 24, borderRadius: '50%', border: on ? '7px solid var(--ink)' : '2px solid var(--line)', background: '#fff', flexShrink: 0, transition: 'border-color .15s, border-width .15s' }} />
              </button>
              {on && p.id !== 'customer' &&
              <p className="fade-up" style={{ margin: '8px 4px 0', fontSize: 12.5, color: 'var(--rose-deep)', display: 'flex', alignItems: 'center', gap: 6 }}>
                  <Icon name="spark" size={14} />{t('comingSoon')}
                </p>
              }
            </div>);

        })}
      </div>

      <Btn variant="rose" iconR="arrow" onClick={() => onContinue(sel)} style={{ marginTop: 18 }}>{t('continue')}</Btn>
    </div>);

}

/* ── Phone entry ── */
function AuthPhone({ onNext, onBack }) {
  const { lang, t } = useZafa();
  const [num, setNum] = React.useState('');
  const fmt = (n) => {const a = n.slice(0, 2),b = n.slice(2, 5),c = n.slice(5, 9);return [a, b, c].filter(Boolean).join(' ');};
  const valid = num.length >= 9;
  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', padding: '0 22px 26px' }}>
      <div style={{ paddingTop: 4 }}><ScreenHeader title={L(lang, 'Sign in', 'تسجيل الدخول')} onBack={onBack} right={<LangToggle />} /></div>
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', paddingTop: 18 }}>
        <h2 className="h1" style={{ margin: '0 0 8px' }}>{t('phoneTitle')}</h2>
        <p className="sec" style={{ margin: 0, fontSize: 15, lineHeight: 1.5 }}>{t('phoneSub')}</p>
        <div style={{ marginTop: 26, display: 'flex', gap: 10 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, height: 60, padding: '0 14px', borderRadius: 14, border: '1.5px solid var(--line)', background: '#fff', flexShrink: 0 }}>
            <span style={{ fontSize: 22 }}>🇦🇪</span><span style={{ fontWeight: 600, fontSize: 16 }}>+971</span>
          </div>
          <div style={{ flex: 1, display: 'flex', alignItems: 'center', height: 60, padding: '0 16px', borderRadius: 14, border: `1.5px solid ${num ? 'var(--rose)' : 'var(--line)'}`, background: '#fff', boxShadow: num ? '0 0 0 4px var(--rose-100)' : 'none', transition: 'all .15s' }}>
            <span style={{ fontSize: 22, fontWeight: 600, color: num ? 'var(--ink)' : 'var(--muted)', letterSpacing: '.04em', direction: 'ltr' }}>{num ? fmt(num) : t('phonePlaceholder')}</span>
            <span style={{ width: 2, height: 26, background: 'var(--rose)', marginInlineStart: 4, animation: 'fadeIn 1s steps(2) infinite alternate' }} />
          </div>
        </div>
      </div>
      <Keypad onKey={(k) => setNum((n) => (n + k).slice(0, 9))} onBack={() => setNum((n) => n.slice(0, -1))} />
      <div style={{ marginTop: 12 }}><Btn variant="rose" disabled={!valid} onClick={() => onNext('+971 ' + fmt(num))} iconR="arrow">{t('sendCode')}</Btn></div>
    </div>);

}

/* ── OTP ── */
function AuthOTP({ phone, onVerified, onBack }) {
  const { lang, t } = useZafa();
  const [code, setCode] = React.useState('');
  const [status, setStatus] = React.useState('idle');
  const [secs, setSecs] = React.useState(38);
  const N = 4;
  React.useEffect(() => {if (secs <= 0) return;const id = setTimeout(() => setSecs((s) => s - 1), 1000);return () => clearTimeout(id);}, [secs]);
  React.useEffect(() => {
    if (code.length === N) {
      setStatus('verifying');
      const id = setTimeout(() => {
        if (code === '1234') onVerified();else
        {setStatus('error');setTimeout(() => {setCode('');setStatus('idle');}, 1100);}
      }, 950);
      return () => clearTimeout(id);
    }
  }, [code]);
  const err = status === 'error';
  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', padding: '0 22px 26px' }}>
      <div style={{ paddingTop: 4 }}><ScreenHeader title={L(lang, 'Verify', 'تحقق')} onBack={onBack} /></div>
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', paddingTop: 18 }}>
        <h2 className="h1" style={{ margin: '0 0 8px' }}>{t('otpTitle')}</h2>
        <p className="sec" style={{ margin: 0, fontSize: 15, lineHeight: 1.5 }}>{t('otpSub')} <span style={{ color: 'var(--ink)', fontWeight: 600, direction: 'ltr', display: 'inline-block' }}>{phone}</span></p>
        <div style={{ display: 'flex', gap: 9, marginTop: 28, direction: 'ltr' }}>
          {Array.from({ length: N }).map((_, i) => {
            const ch = code[i];const active = i === code.length && status !== 'verifying';
            return (
              <div key={i} style={{ flex: 1, height: 62, borderRadius: 14, display: 'flex', alignItems: 'center', justifyContent: 'center', background: '#fff', fontSize: 26, fontWeight: 700, color: err ? '#C0392B' : 'var(--ink)',
                border: `1.5px solid ${err ? '#E8A99F' : active ? 'var(--rose)' : ch ? 'var(--rose-200)' : 'var(--line)'}`, boxShadow: active ? '0 0 0 4px var(--rose-100)' : 'none', transition: 'all .15s' }}>
                {ch || (active ? <span style={{ width: 2, height: 24, background: 'var(--rose)', animation: 'fadeIn 1s steps(2) infinite alternate' }} /> : '')}
              </div>);

          })}
        </div>
        <div style={{ marginTop: 16, minHeight: 24, display: 'flex', alignItems: 'center', gap: 8 }}>
          {status === 'verifying' && <><span className="z-spin z-spin--ink" /><span className="sec" style={{ fontSize: 14 }}>{t('verifying')}</span></>}
          {err && <span style={{ color: '#C0392B', fontSize: 14, fontWeight: 600, display: 'flex', alignItems: 'center', gap: 6 }}><Icon name="x" size={16} />{t('wrongCode')}</span>}
          {status === 'idle' && (secs > 0 ?
          <span className="muted" style={{ fontSize: 14 }}>{t('resendIn')} 0:{String(secs).padStart(2, '0')}</span> :
          <button onClick={() => setSecs(38)} style={{ background: 'none', border: 'none', color: 'var(--rose-deep)', fontWeight: 600, fontSize: 14, cursor: 'pointer', fontFamily: 'var(--sans)' }}>{t('resend')}</button>)}
        </div>
        <div style={{ marginTop: 8, padding: '10px 14px', borderRadius: 12, background: 'var(--rose-100)', display: 'inline-flex', alignSelf: 'flex-start', gap: 7, alignItems: 'center' }}>
          <Icon name="spark" size={15} style={{ color: 'var(--rose-deep)' }} /><span style={{ fontSize: 12.5, color: 'var(--rose-deep)', fontWeight: 600 }}>{L(lang, 'Demo code — use 1234', 'رمز التجربة — ١٢٣٤')}</span>
        </div>
      </div>
      <Keypad onKey={(k) => status !== 'verifying' && setCode((c) => (c + k).slice(0, N))} onBack={() => setCode((c) => c.slice(0, -1))} />
    </div>);

}

/* ── Profile setup ── */
function ProfileSetup({ onDone }) {
  const { lang, t } = useZafa();
  const [name, setName] = React.useState('');
  const [email, setEmail] = React.useState('');
  const [date, setDate] = React.useState('');
  const [city, setCity] = React.useState('Dubai');
  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: 'var(--bg)' }}>
      <div style={{ padding: '6px 22px 6px' }}>
        <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
          <button onClick={onDone} style={{ background: 'none', border: 'none', color: 'var(--muted)', fontWeight: 600, fontSize: 14, cursor: 'pointer', fontFamily: 'var(--sans)' }}>{t('skipNow')}</button>
        </div>
      </div>
      <div className="z-scroll no-bar" style={{ flex: 1, padding: '4px 22px 12px' }}>
        {/* avatar */}
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', marginBottom: 18 }}>
          <div style={{ position: 'relative', width: 96, height: 96 }}>
            <div style={{ width: 96, height: 96, borderRadius: '50%', overflow: 'hidden', border: '2px solid var(--rose-200)' }}><Img id="me-avatar" radius={48} ph="" /></div>
            <span style={{ position: 'absolute', bottom: 0, insetInlineEnd: 0, width: 32, height: 32, borderRadius: '50%', background: 'var(--rose)', display: 'flex', alignItems: 'center', justifyContent: 'center', border: '2px solid var(--bg)' }}><Icon name="camera" size={16} stroke={2} /></span>
          </div>
        </div>
        <h1 className="h1" style={{ margin: '0 0 6px', textAlign: 'center', fontSize: 27 }}>{t('setupTitle')}</h1>
        <p className="sec" style={{ margin: '0 0 24px', textAlign: 'center', fontSize: 14.5, lineHeight: 1.45, fontFamily: "Montserrat", fontWeight: "500" }}>{t('setupSub')}</p>

        {/* basic info */}
        <p className="lbl" style={{ marginBottom: 12, display: 'flex', alignItems: 'center', gap: 8 }}><span style={{ width: 22, height: 22, borderRadius: 7, background: 'var(--rose-100)', color: 'var(--rose-deep)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}><Icon name="user" size={14} /></span>{t('basicInfo')}</p>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12, marginBottom: 26 }}>
          <SetupField label={t('fullName')}><input className="z-input" value={name} onChange={(e) => setName(e.target.value)} placeholder={L(lang, 'e.g. Sara Al Mansoori', 'مثال: سارة المنصوري')} /></SetupField>
          <SetupField label={t('emailAddr')}><input className="z-input" type="email" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="you@email.com" style={{ direction: 'ltr', textAlign: lang === 'ar' ? 'right' : 'left' }} /></SetupField>
        </div>

        {/* planning */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
          <span style={{ width: 22, height: 22, borderRadius: 7, background: 'var(--rose-100)', color: 'var(--rose-deep)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}><Icon name="heart" size={14} /></span>
          <p className="lbl" style={{ margin: 0 }}>{t('planningQ')}</p>
          <span style={{ fontSize: 11, fontWeight: 700, color: 'var(--muted)', background: 'var(--line-2)', padding: '3px 8px', borderRadius: 999, marginInlineStart: 'auto' }}>{t('optional')}</span>
        </div>
        <p className="sec" style={{ margin: '0 0 14px', fontSize: 12.5 }}>{t('planningSub')}</p>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14, marginBottom: 8 }}>
          <SetupField label={t('weddingDate')}>
            <div style={{ position: 'relative' }}>
              <input className="z-input" type="date" value={date} onChange={(e) => setDate(e.target.value)} style={{ direction: 'ltr', textAlign: lang === 'ar' ? 'right' : 'left', color: date ? 'var(--ink)' : 'var(--muted)' }} />
              <Icon name="calendar" size={20} style={{ position: 'absolute', insetInlineEnd: 14, top: 18, color: 'var(--rose-deep)', pointerEvents: 'none' }} />
            </div>
          </SetupField>
          <div>
            <span className="lbl" style={{ display: 'block', marginBottom: 9 }}>{t('cityLabel')}</span>
            <div className="no-bar" style={{ display: 'flex', gap: 9, overflowX: 'auto', paddingBottom: 4 }}>
              {CITIES.map((c) => <Chip key={c} on={city === c} onClick={() => setCity(c)}>{c}</Chip>)}
            </div>
          </div>
        </div>
      </div>
      <div style={{ padding: '12px 22px 28px', borderTop: '1px solid var(--line)', background: '#fff' }}>
        <Btn variant="rose" iconR="arrow" onClick={onDone}>{t('finish')}</Btn>
      </div>
    </div>);

}

function SetupField({ label, children }) {
  return <label style={{ display: 'block' }}><span className="lbl" style={{ display: 'block', marginBottom: 7, fontFamily: "var(--sans)" }}>{label}</span>{children}</label>;
}

Object.assign(window, { LangToggle, Keypad, Onboarding, RoleSelect, AuthPhone, AuthOTP, ProfileSetup, SetupField });