/* ============ KIDS MODE: no-email family entry (anonymous auth + "who are you?") ============
   The three girls share devices and can't use email. So:
   - We sign in ANONYMOUSLY in the background (only to satisfy security rules).
   - Each girl is a fixed MEMBER SLOT in one family group (separate profile + score).
   - A big "מי את?" picker chooses the active slot; all counting writes to counts/{slot}.
   - On first run we create the family group, migrating the old recycle/state counts
     SPLIT EQUALLY between the three girls.
============================================================================== */
(function(){
  const { useState } = React;
  const db = ()=>window.fbDb;

  const FAMILY_GID = 'BANOT';               // fixed code; contains 'O' so it can never collide with genCode()
  const SLOT_KEY   = 'bottlex-kids-slot';
  const MODE_KEY   = 'bottlex-kids';

  const A = (window.KID_AVATARS||{});
  const KID_SLOTS = [
    { id:'yiska', name:'יסכה', avatar:A.yiska },
    { id:'rivka', name:'רבקה', avatar:A.rivka },
    { id:'yael',  name:'יעל',  avatar:A.yael  },
  ];
  const FAMILY = { name:'המויאלים', icon:'🏡', boostName:'באבי', boostMult:2 };
  const SPLIT_IDS = ['can','plastic_s','plastic_l','glass','glass_l'];

  // ---- anonymous sign-in ----
  async function ensureAnon(){
    if(!window.fbAuth) throw new Error('no-auth');
    if(window.fbAuth.currentUser) return window.fbAuth.currentUser;
    const cred = await window.fbAuth.signInAnonymously();
    return cred.user;
  }

  // ---- create the family group once, migrating + splitting old counts ----
  async function ensureFamilyGroup(){
    const ref = db().ref('groups/'+FAMILY_GID);
    // existence check via the `name` child — readable by any authed user
    // (reading the whole group node is blocked until you're a member / openJoin).
    const nameSnap = await ref.child('name').get();
    if(nameSnap.exists()) return false;            // already created — nothing to do

    // read legacy pooled state from the original family page
    let legacy={}, goalName='', goalAmount='';
    try{
      const ls = await db().ref('recycle/state').get();
      const v = ls.val();
      if(v && typeof v==='object'){
        legacy = v.counts||{};
        goalName = v.goalName||'';
        goalAmount = (v.goalAmount==null?'':String(v.goalAmount));
      }
    }catch(e){ /* recycle not readable — start fresh */ }

    // split each container type equally between the 3 girls (remainder spread 1-by-1)
    const counts = { yiska:{}, rivka:{}, yael:{} };
    const order = ['yiska','rivka','yael'];
    SPLIT_IDS.forEach(cid=>{
      const total = Math.max(0, Math.round(Number(legacy[cid])||0));
      const base = Math.floor(total/3); let rem = total - base*3;
      order.forEach(slot=>{ let v=base; if(rem>0){ v++; rem--; } if(v>0) counts[slot][cid]=v; });
    });

    const now = Date.now();
    const uid = window.fbAuth.currentUser.uid;
    const members = {};
    KID_SLOTS.forEach((k,i)=>{ members[k.id]={ name:k.name, avatar:k.avatar, joinedAt:now, role: i===0?'admin':'member' }; });

    await ref.set({
      name:FAMILY.name, icon:FAMILY.icon,
      goalName, goalAmount,
      boostName:FAMILY.boostName, boostMult:FAMILY.boostMult,
      createdBy:uid, createdAt:now,
      openJoin:true, family:true,
      members, counts,
    });
    return true;
  }

  // ---- add a brand-new kid slot to the family group ----
  async function addKidSlot(name, avatar){
    const id = 'k'+Date.now().toString(36)+Math.floor(Math.random()*1000);
    await db().ref('groups/'+FAMILY_GID+'/members/'+id).set({ name:(name||'').trim()||'חבר/ה', avatar, joinedAt:Date.now(), role:'member' });
    return id;
  }

  // ---- GENERAL: any parent (group admin) adds a child profile (no login) ----
  async function addChildToGroup(gid, name, avatar){
    const id = 'c'+Date.now().toString(36)+Math.floor(Math.random()*1000);
    await db().ref('groups/'+gid+'/members/'+id).set({ name:(name||'').trim()||'\u05d9\u05dc\u05d3/\u05d4', avatar, joinedAt:Date.now(), role:'member', child:true });
    return id;
  }

  function heAuthErr(e){
    const c = (e && (e.code || e.message)) || '';
    if(/operation-not-allowed|admin-restricted|configuration-not-found/i.test(c))
      return 'מצב הילדים עדיין לא מופעל ב-Firebase: Authentication → Sign-in method → הפעילו Anonymous (Enable + Save).';
    if(/permission|denied/i.test(c))
      return 'אין הרשאה — צריך לפרסם את כללי האבטחה: Realtime Database → Rules → הדביקו את firebase-rules.json → Publish.';
    if(/network/i.test(c)) return 'אין חיבור לאינטרנט — נסו שוב.';
    return 'משהו השתבש'+(c?' ('+c+')':'')+' — נסו שוב.';
  }

  /* ---- "מי את?" picker ---- */
  function KidsPicker({members, onPick, toast, onExit}){
    const [adding,setAdding]=useState(false);
    const [name,setName]=useState('');
    const [avatar,setAvatar]=useState(()=> (window.CHARACTERS?window.CHARACTERS[Math.floor(Math.random()*window.CHARACTERS.length)].id:'fox'));
    const [busy,setBusy]=useState(false);

    // members come from the live group; fall back to the fixed slots while it loads
    const list = members && Object.keys(members).length
      ? Object.keys(members).map(id=>({ id, name:members[id].name, avatar:members[id].avatar }))
      : KID_SLOTS;

    const addChild=async(e)=>{
      e.preventDefault(); if(!name.trim())return; setBusy(true);
      try{ const id=await addKidSlot(name, avatar); onPick(id); }
      catch(ex){ console.error(ex); toast&&toast('לא הצלחנו להוסיף — נסו שוב'); setBusy(false); }
    };

    return (
      <div className="center-screen kids-pick">
        <div className="brandmark">
          <div className="logo"><img src="icons/icon-192.png" alt="בנקבוק"/></div>
          <h1>מי אַתְּ?</h1>
          <p>לוחצות על הפרצוף שלכן ומתחילות לאסוף 🌳</p>
        </div>

        {!adding ? (
          <div className="card kids-grid-card">
            <div className="kids-grid">
              {list.map(k=>(
                <button type="button" className="kid-tile" key={k.id} onClick={()=>onPick(k.id)}>
                  <div className="kid-face"><window.AvatarImg value={k.avatar} size={92}/></div>
                  <div className="kid-name">{k.name}</div>
                </button>
              ))}
              <button type="button" className="kid-tile add" onClick={()=>setAdding(true)}>
                <div className="kid-face plus">＋</div>
                <div className="kid-name">עוד ילד/ה</div>
              </button>
            </div>
          </div>
        ) : (
          <form className="card" onSubmit={addChild}>
            <label className="fld"><span className="lab">איך קוראים לך?</span>
              <input className="input" autoFocus value={name} onChange={e=>setName(e.target.value)} placeholder="השם שלך" maxLength={16}/>
            </label>
            <span className="lab" style={{display:'block',marginBottom:2}}>בחרו דמות</span>
            <window.AvatarPicker value={avatar} onChange={setAvatar}/>
            <div style={{display:'flex',gap:8,marginTop:12}}>
              <button className="btn" type="submit" disabled={busy} style={{flex:1}}>{busy?'רגע…':'יאללה! ✨'}</button>
              <button className="btn ghost" type="button" onClick={()=>setAdding(false)}>חזרה</button>
            </div>
          </form>
        )}
        {onExit && !adding && <button type="button" className="linkbtn" style={{marginTop:16,color:'#9bb0a4'}} onClick={onExit}>כניסה עם חשבון אחר ←</button>}
      </div>
    );
  }

  Object.assign(window, {
    KidsApi: { ensureAnon, ensureFamilyGroup, addKidSlot, addChildToGroup, heAuthErr, FAMILY_GID, SLOT_KEY, MODE_KEY, KID_SLOTS },
    KidsPicker,
  });
})();
