/* ============ AUTH: onboarding intro, register/login, profile setup ============ */
(function(){
  const { useState } = React;
  const { AvatarPicker, AvatarImg, CHARACTERS } = window;

  const SLIDES=[
    {emoji:'🏦', title:'הבנק של הבקבוקים', text:'כל פחית, בקבוק וצנצנת הם הפקדה קטנה. מזינים כמה אספתם — ובנקבוק מחשב בדיוק כמה הפקדתם, לפי הפיקדון בישראל.'},
    {emoji:'🎯', title:'יעד משותף', text:'חוסכים לטרמפולינה? לטיול? הציבו יעד לקבוצה וצפו בפס ההתקדמות מתמלא יחד — "עוד 12 פחיות והגעתם!".'},
    {emoji:'🏆', title:'מי באלופים?', text:'טבלת דירוג חיה: מי אסף הכי הרבה כסף, הכי הרבה מכלים. מדליות, נקודות ותחרות ידידותית שמרימה את כולם.'},
    {emoji:'💬', title:'מדברים ומתלהבים', text:'צ\'אט קבוצתי לכל מי שאוסף יחד — לתאם, לעודד ולחגוג כל יעד שמושג.'},
    {emoji:'✨', title:'סבתא מכפילה', text:'אפשר להגדיר "מכפיל" לקבוצה — סבתא, סבא או כל תומך נדיב שמכפיל את הסכום שאספתם ונותן בוסט אדיר למוטיבציה.'},
  ];

  function Onboarding({onDone}){
    const [i,setI]=useState(0);
    const last=i===SLIDES.length-1;
    const s=SLIDES[i];
    return (
      <div className="center-screen">
        <div className="brandmark">
          <div className="logo">
            <img src="icons/icon-192.png" alt="בנקבוק"/>
          </div>
          <h1>בַּנְקְבּוּק</h1>
          <p>אוספים · חוסכים · מתחרים</p>
        </div>
        <div className="card" style={{textAlign:'center'}}>
          <div style={{fontSize:'4.4rem',lineHeight:1,margin:'6px 0 14px'}}>{s.emoji}</div>
          <h2 style={{fontFamily:"'Varela Round'",margin:'0 0 10px',fontSize:'1.5rem',color:'var(--ink)'}}>{s.title}</h2>
          <p style={{color:'#5e7468',fontWeight:600,fontSize:'1rem',lineHeight:1.5,margin:'0 0 18px',textWrap:'pretty'}}>{s.text}</p>
          <div style={{display:'flex',justifyContent:'center',gap:6,marginBottom:18}}>
            {SLIDES.map((_,k)=>(<div key={k} style={{width:k===i?22:8,height:8,borderRadius:99,background:k===i?'var(--leaf)':'#d8e6dc',transition:'width .2s'}}></div>))}
          </div>
          {last
            ? <button className="btn" onClick={onDone}>בואו נתחיל! 🚀</button>
            : <button className="btn cyan" onClick={()=>setI(i+1)}>הבא →</button>}
          {!last && <button className="linkbtn" style={{marginTop:8}} onClick={onDone}>דלגו</button>}
        </div>
      </div>
    );
  }

  function heErr(code){
    const m={
      'auth/invalid-email':'כתובת אימייל לא תקינה',
      'auth/email-already-in-use':'האימייל הזה כבר רשום — נסו להתחבר',
      'auth/weak-password':'הסיסמה קצרה מדי (לפחות 6 תווים)',
      'auth/wrong-password':'סיסמה שגויה',
      'auth/user-not-found':'לא נמצא משתמש עם האימייל הזה',
      'auth/invalid-credential':'אימייל או סיסמה שגויים',
      'auth/too-many-requests':'יותר מדי ניסיונות, נסו שוב עוד רגע',
      'auth/network-request-failed':'אין חיבור לאינטרנט',
      'auth/popup-blocked':'הדפדפן חסם את חלון ההתחברות — נסו שוב',
      'auth/account-exists-with-different-credential':'האימייל כבר רשום בדרך אחרת — התחברו עם אימייל וסיסמה',
      'auth/unauthorized-domain':'הדומיין לא מאושר ב-Firebase (הוסיפו אותו ב-Authentication → Settings)',
      'auth/operation-not-allowed':'שיטת הכניסה לא מופעלת — הפעילו Email/Password ב-Firebase → Authentication → Sign-in method',
      'auth/configuration-not-found':'הכניסה לא מוגדרת ב-Firebase — ודאו ש-Email/Password מופעל (Authentication → Sign-in method)',
      'auth/admin-restricted-operation':'הרשמה חסומה ב-Firebase — הפעילו את שיטת הכניסה (Sign-in method)',
      'auth/api-key-not-valid':'מפתח ה-API לא תקין',
      'auth/internal-error':'שגיאה פנימית ב-Firebase — בדקו שהפעלתם את שיטת הכניסה',
    };
    return m[code]||('משהו השתבש'+(code?' ('+code+')':'')+' — נסו שוב');
  }

  const GoogleG=()=>(
    <svg width="20" height="20" viewBox="0 0 48 48" aria-hidden="true"><path fill="#4285F4" d="M45.12 24.5c0-1.56-.14-3.06-.4-4.5H24v8.51h11.84c-.51 2.75-2.06 5.08-4.39 6.64v5.52h7.11c4.16-3.83 6.56-9.47 6.56-16.17z"/><path fill="#34A853" d="M24 46c5.94 0 10.92-1.97 14.56-5.33l-7.11-5.52c-1.97 1.32-4.49 2.1-7.45 2.1-5.73 0-10.58-3.87-12.31-9.07H4.34v5.7C7.96 41.07 15.4 46 24 46z"/><path fill="#FBBC05" d="M11.69 28.18c-.44-1.32-.69-2.73-.69-4.18s.25-2.86.69-4.18v-5.7H4.34A21.99 21.99 0 0 0 2 24c0 3.55.85 6.91 2.34 9.88l7.35-5.7z"/><path fill="#EA4335" d="M24 10.75c3.23 0 6.13 1.11 8.41 3.29l6.31-6.31C34.91 4.18 29.93 2 24 2 15.4 2 7.96 6.93 4.34 14.12l7.35 5.7c1.73-5.2 6.58-9.07 12.31-9.07z"/></svg>
  );

  function AuthScreen({onKidsLogin}){
    // family "kids" entrance: typing this username + password routes to kids mode
    // (anonymous under the hood) instead of a real account. Invisible to everyone else.
    const KIDS_USERNAMES=['בנות','banot'];
    const KIDS_PASS='בנקבוק';
    const isKidsCred=(u,p)=> KIDS_USERNAMES.includes((u||'').trim().toLowerCase()) && p===KIDS_PASS;
    const [mode,setMode]=useState('register'); // register | login
    const [email,setEmail]=useState('');
    const [pw,setPw]=useState('');
    const [busy,setBusy]=useState(false);
    const [err,setErr]=useState('');
    const [info,setInfo]=useState('');
    const submit=async(e)=>{
      e.preventDefault(); setErr('');
      if(onKidsLogin && isKidsCred(email,pw)){ onKidsLogin(); return; }
      setBusy(true);
      try{
        if(mode==='register') await window.fbAuth.createUserWithEmailAndPassword(email.trim(), pw);
        else await window.fbAuth.signInWithEmailAndPassword(email.trim(), pw);
      }catch(ex){ console.error('[auth]', ex.code, ex.message); setErr(heErr(ex.code)); setBusy(false); }
    };
    const forgot=async()=>{
      const em=email.trim(); setInfo('');
      if(!em){ setErr('הזינו קודם את האימייל ואז לחצו "שכחתי סיסמה"'); return; }
      setErr(''); setBusy(true);
      try{ await window.fbAuth.sendPasswordResetEmail(em); setInfo('שלחנו קישור לאיפוס סיסמה ל-'+em+' 📩 בדקו גם בספאם'); setBusy(false); }
      catch(ex){ setErr(heErr(ex.code)); setBusy(false); }
    };
    const googleSignIn=async()=>{
      setErr(''); setBusy(true);
      const provider=new firebase.auth.GoogleAuthProvider();
      try{
        await window.fbAuth.signInWithPopup(provider);
      }catch(ex){
        console.error('[google]', ex.code, ex.message);
        if(ex.code==='auth/popup-closed-by-user'||ex.code==='auth/cancelled-popup-request'){ setBusy(false); return; }
        if(ex.code==='auth/popup-blocked'||ex.code==='auth/operation-not-supported-in-this-environment'){
          try{ await window.fbAuth.signInWithRedirect(provider); }catch(e2){ setErr(heErr(e2.code)); setBusy(false); }
          return;
        }
        setErr(heErr(ex.code)); setBusy(false);
      }
    };
    return (
      <div className="center-screen">
        <div className="brandmark">
          <div className="logo">
            <img src="icons/icon-192.png" alt="בנקבוק"/>
          </div>
          <h1>{mode==='register'?'הצטרפו לְבַּנְקְבּוּק':'ברוכים השבים!'}</h1>
          <p>{mode==='register'?'פתחו חשבון ותתחילו לאסוף':'התחברו כדי להמשיך לאסוף'}</p>
        </div>
        <form className="card" onSubmit={submit}>
          {err && <div className="err">{err}</div>}
          {info && <div className="err" style={{background:'#e3f9ec',color:'var(--leaf-dk)'}}>{info}</div>}
          <label className="fld"><span className="lab">אימייל</span>
            <input className="input" type="text" inputMode="email" dir="ltr" autoComplete="username" required value={email} onChange={e=>setEmail(e.target.value)} placeholder="you@example.com"/>
          </label>
          <label className="fld"><span className="lab">סיסמה</span>
            <input className="input" type="password" dir="ltr" autoComplete={mode==='register'?'new-password':'current-password'} required value={pw} onChange={e=>setPw(e.target.value)} placeholder="לפחות 6 תווים"/>
          </label>
          {mode==='login' && <div style={{textAlign:'start',marginTop:-4,marginBottom:10}}><button type="button" className="linkbtn" onClick={forgot} disabled={busy}>שכחתי סיסמה?</button></div>}
          <button className="btn" type="submit" disabled={busy}>{busy?'רגע…':(mode==='register'?'יצירת חשבון':'התחברות')}</button>
          <div className="divider">או</div>
          <button className="btn google" type="button" onClick={googleSignIn} disabled={busy}><GoogleG/>המשך עם Google</button>
          <div style={{textAlign:'center',marginTop:14}}>
            <span className="muted">{mode==='register'?'כבר יש לכם חשבון?':'עדיין אין לכם חשבון?'}</span>
            <button type="button" className="linkbtn" onClick={()=>{setMode(mode==='register'?'login':'register');setErr('');setInfo('');}}>
              {mode==='register'?'להתחברות':'להרשמה'}
            </button>
          </div>
        </form>
        <p className="muted" style={{maxWidth:380,textAlign:'center',marginTop:16,color:'#9bb0a4'}}>
          🔒 הנתונים שלכם מאובטחים. כל קבוצה רואה רק את עצמה.
        </p>
      </div>
    );
  }

  function ProfileSetup({uid, defaultName, defaultPhoto, onSaved}){
    const [name,setName]=useState(defaultName||'');
    const [avatar,setAvatar]=useState(defaultPhoto || CHARACTERS[Math.floor(Math.random()*CHARACTERS.length)].id);
    const [busy,setBusy]=useState(false);
    const save=async(e)=>{
      e.preventDefault(); if(!name.trim())return; setBusy(true);
      try{
        await window.fbDb.ref('users/'+uid).update({name:name.trim(), avatar, createdAt:Date.now()});
        onSaved&&onSaved();
      }catch(ex){ setBusy(false); }
    };
    return (
      <div className="center-screen">
        <div className="brandmark">
          <AvatarImg value={avatar} size={84}/>
          <h1 style={{marginTop:6}}>מי אתם?</h1>
          <p>בחרו דמות ושם שיראו לכולם</p>
        </div>
        <form className="card" onSubmit={save}>
          <label className="fld"><span className="lab">השם שלכם</span>
            <input className="input" required value={name} onChange={e=>setName(e.target.value)} placeholder="איך לקרוא לכם?" maxLength={20}/>
          </label>
          <span className="lab" style={{display:'block',marginBottom:2}}>הדמות שלכם</span>
          <AvatarPicker value={avatar} onChange={setAvatar}/>
          <button className="btn" type="submit" disabled={busy} style={{marginTop:12}}>{busy?'שומר…':'יאללה, קדימה! ✨'}</button>
        </form>
      </div>
    );
  }

  Object.assign(window, { Onboarding, AuthScreen, ProfileSetup });
})();
