// screens-onboarding.jsx — splash, phone, OTP, profile setup

function SplashScreen({ onNext }) {
  React.useEffect(() => {
    const t = setTimeout(onNext, 2400);
    return () => clearTimeout(t);
  }, []);
  return (
    <div style={{
      width: '100%', height: '100%', background: '#000',
      display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
      position: 'relative', overflow: 'hidden',
    }}>
      {/* gold particles bg */}
      <svg style={{ position: 'absolute', inset: 0 }} width="100%" height="100%" viewBox="0 0 400 800" preserveAspectRatio="none">
        <defs>
          <radialGradient id="glow" cx="50%" cy="50%">
            <stop offset="0" stopColor="#D4AF37" stopOpacity="0.18" />
            <stop offset="1" stopColor="#D4AF37" stopOpacity="0" />
          </radialGradient>
        </defs>
        <circle cx="200" cy="400" r="280" fill="url(#glow)" />
        <path d="M0 600 Q 100 580 200 600 T 400 600" stroke="#D4AF37" strokeWidth="0.8" fill="none" opacity="0.4" />
        <path d="M0 640 Q 100 620 200 640 T 400 640" stroke="#D4AF37" strokeWidth="0.6" fill="none" opacity="0.25" />
        <path d="M0 680 Q 100 660 200 680 T 400 680" stroke="#D4AF37" strokeWidth="0.4" fill="none" opacity="0.15" />
      </svg>
      <div style={{
        animation: 'fadeUp 0.8s ease-out',
        display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 18, zIndex: 2,
      }}>
        <TrustaLogo size={92} />
        <Wordmark size={36} />
        <div style={{
          fontFamily: 'Inter, system-ui', fontSize: 10, fontWeight: 500,
          color: 'rgba(255,255,255,0.55)', letterSpacing: '0.28em',
          textTransform: 'uppercase', textAlign: 'center',
        }}>WHERE TRUST MEETS OPPORTUNITY</div>
      </div>
      <style>{`@keyframes fadeUp { from { opacity:0; transform:translateY(12px) } to { opacity:1; transform:translateY(0) } }`}</style>
    </div>
  );
}

function PhoneScreen({ onNext, t, lang }) {
  const [phone, setPhone] = React.useState('');
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState(null);
  const [errorCode, setErrorCode] = React.useState(null);

  const submit = async () => {
    if (loading) return;
    setError(null);
    setErrorCode(null);

    // Garde-fou : numéro doit avoir au moins 8 chiffres
    const digits = (phone || '').replace(/\D/g, '');
    if (digits.length < 8) {
      setError(lang === 'ka' ? 'არასწორი ნომერი' : 'Numéro invalide');
      return;
    }

    if (!window.API_AVAILABLE) {
      // Mode dev/preview : pas d'API, on passe direct
      onNext(phone);
      return;
    }

    setLoading(true);
    try {
      const res = await window.TrustaAPI.requestOtp(phone, lang);
      onNext(res.phone || phone);
    } catch (err) {
      setError(errorMessage(err, lang));
      setErrorCode(err?.code || null);
      setLoading(false);
    }
  };

  // Mode "SMS down" : affiché quand notre opérateur SMS bloque les envois
  const smsDown = errorCode === 'sms_failed';

  return (
    <div style={{ width: '100%', height: '100%', background: COLORS.bg, display: 'flex', flexDirection: 'column' }}>
      <div style={{ padding: '90px 28px 0', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 16 }}>
        <TrustaLogo size={64} />
        <Wordmark size={26} />
      </div>
      <div style={{
        fontFamily: 'Inter, system-ui', fontSize: 13, color: COLORS.text2,
        textAlign: 'center', marginTop: 18, marginBottom: 36,
      }}>{t('signin_register')}</div>

      <div style={{ padding: '0 24px', display: 'flex', flexDirection: 'column', gap: 14 }}>
        <div style={{
          height: 56, borderRadius: 14, background: COLORS.card,
          border: `1px solid ${error ? COLORS.red : COLORS.borderSoft}`,
          display: 'flex', alignItems: 'center', padding: '0 18px', gap: 10,
        }}>
          <svg width="18" height="18" viewBox="0 0 18 18"><path d="M4 2 H7 L8.5 6 L6.5 7.5 C7.5 9.5 9 11 11 12 L12.5 10 L16.5 11.5 V14 C16.5 15 15.5 16 14.5 16 C7.5 16 2 10.5 2 3.5 C2 2.5 3 2 4 2 Z" fill={COLORS.gold} /></svg>
          <input
            value={phone}
            onChange={e => setPhone(e.target.value)}
            type="tel"
            inputMode="tel"
            disabled={loading}
            placeholder="+33 6 12 34 56 78"
            style={{
              flex: 1, background: 'transparent', border: 'none', outline: 'none',
              color: '#fff', fontFamily: 'Inter, system-ui', fontSize: 16, fontWeight: 500,
              letterSpacing: 0.3, opacity: loading ? 0.5 : 1,
            }}
          />
        </div>
        {error && !smsDown && (
          <div style={{ fontFamily: 'Inter, system-ui', fontSize: 12, color: COLORS.red, textAlign: 'center' }}>
            {error}
          </div>
        )}
        <GoldButton onClick={submit} disabled={loading}>
          {loading ? '...' : t('continue')}
        </GoldButton>
        {smsDown ? (
          <div style={{
            marginTop: 10, padding: '14px 16px', borderRadius: 12,
            background: 'rgba(212, 175, 55, 0.08)',
            border: `1px solid ${COLORS.gold}`,
            fontFamily: 'Inter, system-ui', fontSize: 12.5, lineHeight: 1.5,
            color: '#fff',
          }}>
            <div style={{ fontWeight: 600, color: COLORS.gold, marginBottom: 6, fontSize: 13 }}>
              {lang === 'ka' ? '⚠️ SMS დროებით მიუწვდომელია' : '⚠️ SMS temporairement indisponible'}
            </div>
            <div style={{ color: COLORS.text2 }}>
              {lang === 'ka'
                ? 'ჩვენმა SMS ოპერატორმა გაშვების გამო ყველა გაგზავნა ანტი-სპამის შემოწმებაში გადაიტანა. ვამუშავებთ. სცადე ხვალ დილით ან მომწერე პირადში Facebook-ზე — დაგეხმარები ხელით.'
                : 'Notre opérateur SMS a temporairement bloqué les envois (vérification anti-spam suite au lancement). On rétablit ça dans la nuit. Réessaie demain matin, ou écris-moi en privé sur Facebook — je te connecte à la main 💛'}
            </div>
          </div>
        ) : (
          <div style={{
            fontFamily: 'Inter, system-ui', fontSize: 12, color: COLORS.text3,
            textAlign: 'center', marginTop: 6,
          }}>{t('sms_disclaimer')}</div>
        )}
      </div>

      <div style={{ flex: 1 }} />
      <div style={{
        textAlign: 'center', paddingBottom: 60,
        fontFamily: 'Inter, system-ui', fontSize: 13, color: COLORS.text2,
      }}>
        {t('no_account')} <span style={{ color: COLORS.gold, fontWeight: 600 }}>{t('register_link')}</span>
      </div>
    </div>
  );
}

function errorMessage(err, lang) {
  const msgs = {
    invalid_phone:           { fr: 'Numéro invalide', ka: 'არასწორი ნომერი' },
    rate_limited:            { fr: 'Trop de demandes, réessayez plus tard', ka: 'ძალიან ბევრი მოთხოვნა, სცადეთ მოგვიანებით' },
    too_many_requests_phone: { fr: 'Trop de demandes pour ce numéro', ka: 'ძალიან ბევრი მოთხოვნა ამ ნომრისთვის' },
    too_many_requests_ip:    { fr: 'Trop de demandes depuis votre IP', ka: 'ძალიან ბევრი მოთხოვნა' },
    phone_not_verified_trial:{ fr: 'Numéro non vérifié (compte Twilio trial)', ka: 'ნომერი არ არის გადამოწმებული' },
    invalid_code:            { fr: 'Code incorrect ou expiré', ka: 'არასწორი ან ვადაგასული კოდი' },
    network_error:           { fr: 'Pas de connexion internet', ka: 'ინტერნეტის გარეშე' },
    sms_failed:              { fr: 'Échec envoi SMS, réessayez', ka: 'SMS-ის გაგზავნა ვერ მოხერხდა' },
  };
  const code = err?.code;
  if (code && msgs[code]) return msgs[code][lang] || msgs[code].fr;
  // Pas de mapping connu → on affiche le vrai message backend (utile pour debug)
  if (err?.message) return err.message;
  return msgs.sms_failed[lang] || msgs.sms_failed.fr;
}
window.errorMessage = errorMessage;

function OtpScreen({ onNext, onBack, t, lang, phone }) {
  const [code, setCode] = React.useState(['', '', '', '', '', '']);
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState(null);
  const refs = React.useRef([]);

  // Garde-fou : si on arrive sur cet écran sans phone, retour à PhoneScreen
  React.useEffect(() => {
    if (!phone && onBack) {
      console.warn('[OtpScreen] No phone provided, going back to PhoneScreen');
      onBack();
    }
  }, [phone]);

  const verify = async (digits) => {
    if (loading) return;
    setError(null);

    if (!window.API_AVAILABLE) {
      // Mode dev/preview : pas de vérification, on passe direct
      setTimeout(() => onNext({ isNewUser: true }), 350);
      return;
    }

    setLoading(true);
    try {
      const res = await window.TrustaAPI.verifyOtp(phone, digits);
      onNext({ isNewUser: res.is_new_user, user: res.user });
    } catch (err) {
      setError(window.errorMessage(err, lang));
      setCode(['', '', '', '', '', '']);
      refs.current[0]?.focus();
      setLoading(false);
    }
  };

  const setDigit = (i, v) => {
    if (!/^\d?$/.test(v)) return;
    const nc = [...code]; nc[i] = v; setCode(nc);
    if (v && i < 5) refs.current[i + 1]?.focus();
    if (nc.every(d => d) && nc.join('').length === 6) {
      verify(nc.join(''));
    }
  };

  return (
    <div style={{ width: '100%', height: '100%', background: COLORS.bg, display: 'flex', flexDirection: 'column' }}>
      <Header onBack={onBack} title="" />
      <div style={{ padding: '40px 28px 0', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 12 }}>
        <TrustaLogo size={48} />
        <div style={{ fontFamily: '"Playfair Display", serif', fontSize: 24, color: '#fff', marginTop: 12 }}>{t('enter_code')}</div>
        <div style={{ fontFamily: 'Inter, system-ui', fontSize: 13, color: COLORS.text2, textAlign: 'center' }}>
          {t('code_sent_to')} {phone || '...'}
        </div>
      </div>

      <div style={{ display: 'flex', justifyContent: 'center', gap: 8, marginTop: 36, padding: '0 16px' }}>
        {[0, 1, 2, 3, 4, 5].map(i => (
          <input
            key={i}
            ref={el => refs.current[i] = el}
            value={code[i]}
            onChange={e => setDigit(i, e.target.value)}
            maxLength={1}
            inputMode="numeric"
            disabled={loading}
            style={{
              width: 44, height: 56, borderRadius: 12,
              background: COLORS.card, border: `1px solid ${error ? COLORS.red : (code[i] ? COLORS.gold : COLORS.borderSoft)}`,
              color: COLORS.gold, fontFamily: '"Playfair Display", serif', fontSize: 24, fontWeight: 600,
              textAlign: 'center', outline: 'none',
              opacity: loading ? 0.5 : 1,
            }}
            autoFocus={i === 0}
          />
        ))}
      </div>

      {error && (
        <div style={{ textAlign: 'center', marginTop: 16, fontFamily: 'Inter, system-ui', fontSize: 12, color: COLORS.red, padding: '0 24px' }}>
          {error}
        </div>
      )}

      <div style={{ padding: '36px 24px 0' }}>
        <GoldButton onClick={() => verify(code.join(''))} disabled={loading || code.join('').length < 6}>
          {loading ? '...' : t('verify')}
        </GoldButton>
      </div>
      <div style={{ textAlign: 'center', marginTop: 18, fontFamily: 'Inter, system-ui', fontSize: 13, color: COLORS.gold, cursor: 'pointer' }}>{t('resend_code')}</div>
    </div>
  );
}

function Field({ label, children }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
      <div style={{ fontFamily: 'Inter, system-ui', fontSize: 12, color: COLORS.text2, fontWeight: 500 }}>{label}</div>
      {children}
    </div>
  );
}

function ProfileSetupScreen({ onNext, t, lang }) {
  const [role, setRole] = React.useState('looking');
  const [name, setName] = React.useState(lang === 'ka' ? 'ანი გ.' : 'Ani G.');
  const [city, setCity] = React.useState(lang === 'ka' ? 'ლიონი' : 'Lyon');
  const [referral, setReferral] = React.useState('');
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState(null);

  const finish = async () => {
    if (loading) return;
    setError(null);

    if (!window.API_AVAILABLE) {
      onNext();
      return;
    }

    setLoading(true);
    try {
      await window.TrustaAPI.updateMe({
        name,
        city,
        role: role === 'looking' ? 'worker' : 'employer',
        language: lang,
        referred_by: referral || undefined,
      });
      onNext();
    } catch (err) {
      setError(window.errorMessage(err, lang));
      setLoading(false);
    }
  };

  const inputStyle = {
    height: 48, borderRadius: 12, background: COLORS.card,
    border: `1px solid ${COLORS.borderSoft}`, padding: '0 14px',
    color: '#fff', fontFamily: 'Inter, system-ui', fontSize: 15, outline: 'none',
  };

  return (
    <div style={{ width: '100%', height: '100%', background: COLORS.bg, display: 'flex', flexDirection: 'column' }}>
      <Header big title={t('profile_setup')} />
      <div style={{ padding: '20px 24px 0', display: 'flex', flexDirection: 'column', gap: 20 }}>
        <div style={{ display: 'flex', gap: 10 }}>
          {[
            { id: 'looking', label: t('i_am_looking') },
            { id: 'offering', label: t('i_am_offering') },
          ].map(r => (
            <button key={r.id} onClick={() => setRole(r.id)} style={{
              flex: 1, height: 48, borderRadius: 12,
              background: role === r.id ? COLORS.goldSoft : COLORS.card,
              border: `1px solid ${role === r.id ? COLORS.gold : COLORS.borderSoft}`,
              color: role === r.id ? COLORS.gold : COLORS.text2,
              fontFamily: 'Inter, system-ui', fontSize: 13, fontWeight: 600,
              cursor: 'pointer',
            }}>{r.label}</button>
          ))}
        </div>

        <Field label={t('full_name')}>
          <input value={name} onChange={e => setName(e.target.value)} style={inputStyle} />
        </Field>
        <Field label={t('city_in_france')}>
          <input value={city} onChange={e => setCity(e.target.value)} style={inputStyle} />
        </Field>
        <Field label={t('referral_code')}>
          <input value={referral} onChange={e => setReferral(e.target.value.toUpperCase())} placeholder="" style={inputStyle} />
        </Field>
        {error && (
          <div style={{ fontFamily: 'Inter, system-ui', fontSize: 12, color: COLORS.red, textAlign: 'center' }}>
            {error}
          </div>
        )}
      </div>
      <div style={{ flex: 1 }} />
      <div style={{ padding: '20px 24px 60px' }}>
        <GoldButton onClick={finish} disabled={loading || !name || !city}>
          {loading ? '...' : t('finish')}
        </GoldButton>
      </div>
    </div>
  );
}

window.SplashScreen = SplashScreen;
window.PhoneScreen = PhoneScreen;
window.OtpScreen = OtpScreen;
window.ProfileSetupScreen = ProfileSetupScreen;
