// First-time profile setup — shown after LINE OAuth when no users row exists yet.

function OnboardingView({ session, onComplete }) {
  const [name, setName] = useState(session?.lineDisplayName || '');
  const [aboCode, setAboCode] = useState('');
  const [pin, setPin] = useState('');
  const [role, setRole] = useState('ABO');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  const PIN_LEVELS = ['3%','6%','9%','12%','15%','18%','21%','23%','Platinum','Ruby','Sapphire','Emerald','Diamond'];

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!name.trim()) { setError('กรุณากรอกชื่อ'); return; }
    setLoading(true);
    setError(null);

    const { data: { user }, error: userErr } = await window.supabase.auth.getUser();
    if (userErr || !user) { setError('ไม่พบ session กรุณาล็อกอินใหม่'); setLoading(false); return; }

    const { data, error: insertErr } = await window.supabase
      .from('users')
      .insert({
        auth_id: user.id,
        line_user_id: session?.lineUserId || user.user_metadata?.sub || null,
        line_display_name: session?.lineDisplayName || null,
        name: name.trim(),
        abo_code: aboCode.trim() || null,
        pin: pin || null,
        role,
        avatar: session?.avatar || null,
      })
      .select()
      .single();

    if (insertErr) {
      setError('เกิดข้อผิดพลาด: ' + insertErr.message);
      setLoading(false);
      return;
    }
    onComplete(data);
  };

  return (
    <div className="min-h-screen flex items-center justify-center relative overflow-hidden grid-bg">
      <div className="absolute -top-32 -left-32 w-[420px] h-[420px] rounded-full blur-3xl opacity-30" style={{ background: 'radial-gradient(circle, #2F5DE5, transparent 70%)' }} />
      <div className="absolute -bottom-32 -right-32 w-[420px] h-[420px] rounded-full blur-3xl opacity-30" style={{ background: 'radial-gradient(circle, #06C755, transparent 70%)' }} />

      <div className="relative w-full max-w-md mx-4">
        <div className="text-center mb-6">
          <div className="inline-flex items-center justify-center w-14 h-14 rounded-2xl bg-gradient-to-br from-ink-900 to-brand-700 text-white relative shadow-lift mb-3">
            <span className="text-xl font-bold">E</span>
            <div className="absolute top-0.5 right-0.5 w-3 h-3 bg-gold-400 rounded-full" />
          </div>
          {session?.avatar && (
            <div className="flex justify-center mb-3">
              <img src={session.avatar} className="w-14 h-14 rounded-full border-2 border-white shadow-lift" alt="" />
            </div>
          )}
          <h1 className="text-xl font-bold text-ink-900">สร้างโปรไฟล์ ABO</h1>
          <p className="text-xs text-ink-500 mt-1">กรอกข้อมูลเพื่อเริ่มใช้งาน EMPHASIS</p>
        </div>

        <Card className="shadow-lift">
          <form onSubmit={handleSubmit} className="py-1 space-y-4">

            <div>
              <label className="block text-xs font-medium text-ink-600 mb-1">
                ชื่อเล่น <span className="text-rose-500">*</span>
              </label>
              <input
                value={name}
                onChange={e => setName(e.target.value)}
                className="w-full h-10 px-3 rounded-lg border border-ink-200 text-sm focus:outline-none focus:ring-2 focus:ring-brand-300 bg-white"
                placeholder="ชื่อที่ใช้เรียก"
              />
            </div>

            <div>
              <label className="block text-xs font-medium text-ink-600 mb-1">ABO Number</label>
              <input
                value={aboCode}
                onChange={e => setAboCode(e.target.value)}
                className="w-full h-10 px-3 rounded-lg border border-ink-200 text-sm focus:outline-none focus:ring-2 focus:ring-brand-300 bg-white font-mono"
                placeholder="7014634134"
              />
            </div>



            {error && <p className="text-xs text-rose-600 text-center">{error}</p>}

            <button
              type="submit"
              disabled={loading}
              className="w-full h-11 rounded-xl font-semibold text-sm text-white transition-all flex items-center justify-center gap-2 disabled:opacity-70"
              style={{ background: '#2F5DE5', boxShadow: '0 6px 14px -4px rgba(47,93,229,0.4)' }}
            >
              {loading ? (
                <>
                  <svg className="animate-spin" width="18" height="18" viewBox="0 0 24 24" fill="none">
                    <circle cx="12" cy="12" r="10" stroke="white" strokeOpacity="0.3" strokeWidth="3" />
                    <path d="M22 12a10 10 0 0 0-10-10" stroke="white" strokeWidth="3" strokeLinecap="round" />
                  </svg>
                  <span>กำลังบันทึก...</span>
                </>
              ) : (
                <span>เริ่มใช้งาน EMPHASIS</span>
              )}
            </button>
          </form>
        </Card>
      </div>
    </div>
  );
}

window.OnboardingView = OnboardingView;
