/* ============ ADMIN: member management, count fixes, group deletion, owner super-admin ============
   Two tiers of power:
   - GROUP ADMIN (role==='admin' in the group): manages members of THEIR group —
     role toggle, edit participant/child profile, fix counts, remove member, delete group.
   - APP OWNER (email in OWNER_EMAILS): a super panel over ALL groups (read root /groups,
     delete any group). Matches the emails already trusted in firebase-rules.json.
   Every destructive action goes through a double-confirm dialog.
============================================================================== */
(function(){
  const { useState, useEffect } = React;
  const db = ()=>window.fbDb;
  const OWNER_EMAILS = ['netanelm87@gmail.com','moyalnh@gmail.com'];
  const isOwnerEmail = (email)=> !!email && OWNER_EMAILS.includes((email||'').trim().toLowerCase());

  // recompute the public/groups aggregate for the global leaderboard after an edit.
  // best-effort: the editor is a member/admin so this write is allowed by the rules.
  function recomputePublicGroup(gid, group, counts, members){
    try{
      const C = window.CONTAINERS||[];
      let money=0, cans=0;
      Object.keys(counts||{}).forEach(u=>{ C.forEach(d=>{ const n=(counts[u]&&counts[u][d.id])||0; money+=n*d.rate; cans+=n; }); });
      const mult = Math.max(1, group.boostMult||1);
      db().ref('public/groups/'+gid).update({
        name:group.name||'קבוצה', icon:group.icon||'♻️',
        cans, money, total:money*mult,
        members:Object.keys(members||{}).length, ts:Date.now()
      });
    }catch(e){}
  }

  /* ---------- reusable double-confirm dialog ---------- */
  function ConfirmDialog({title, body, confirmLabel, cancelLabel, danger, busy, onConfirm, onCancel}){
    return (
      <div className="sheet-bg confirm-bg" onClick={onCancel} style={{zIndex:70,alignItems:'center'}}>
        <div className="confirm-card" onClick={e=>e.stopPropagation()}>
          <div className={"confirm-ico"+(danger?' danger':'')}>{danger?'⚠️':'❓'}</div>
          <h3>{title}</h3>
          {body && <p className="confirm-body">{body}</p>}
          <div className="confirm-acts">
            <button type="button" className="btn ghost dark" onClick={onCancel} disabled={busy}>{cancelLabel||'ביטול'}</button>
            <button type="button" className={"btn"+(danger?' pink':'')} onClick={onConfirm} disabled={busy}>{busy?'רגע…':(confirmLabel||'אישור')}</button>
          </div>
        </div>
      </div>
    );
  }

  /* ---------- per-member action sheet (group admin) ---------- */
  function MemberActionSheet({gid, group, mid, selfUid, isOwner, toast, onClose, onAfterRemove}){
    const { AvatarImg, AvatarPicker } = window;
    const C = window.CONTAINERS||[];
    const m = (group.members&&group.members[mid])||{};
    const isSelf = mid===selfUid;
    const isChild = !!m.child;
    const members = group.members||{};
    const adminCount = Object.keys(members).filter(u=>members[u]&&members[u].role==='admin').length;
    const isLastAdmin = m.role==='admin' && adminCount<=1;

    const [view,setView]=useState('main'); // main | edit | counts | confirm
    const [busy,setBusy]=useState(false);
    const [confirmCfg,setConfirmCfg]=useState(null);

    // edit-profile state (children / participants)
    const [eName,setEName]=useState(m.name||'');
    const [eAvatar,setEAvatar]=useState(m.avatar);

    // count-fix state — local draft, saved on confirm
    const baseCounts = (group.counts&&group.counts[mid])||{};
    const [draft,setDraft]=useState(()=>{ const o={}; C.forEach(d=>{ o[d.id]=Math.max(0, Math.round(Number(baseCounts[d.id])||0)); }); return o; });
    const draftMoney = C.reduce((s,d)=>s+(draft[d.id]||0)*d.rate,0);
    const draftCans  = C.reduce((s,d)=>s+(draft[d.id]||0),0);
    const setN=(cid,v)=>setDraft(p=>({...p,[cid]:Math.max(0,Math.round(v)||0)}));

    const saveProfile=async(e)=>{
      e&&e.preventDefault(); if(!eName.trim())return; setBusy(true);
      try{
        await db().ref('groups/'+gid+'/members/'+mid).update({name:eName.trim(), avatar:eAvatar});
        toast('עודכן ✓'); setBusy(false); onClose();
      }catch(ex){ console.warn('[admin-edit]',ex&&ex.code); toast('שגיאה בשמירה'+(ex&&ex.code?' ('+ex.code+')':'')); setBusy(false); }
    };

    const saveCounts=async()=>{
      setBusy(true);
      try{
        const payload={}; C.forEach(d=>{ payload[d.id]=draft[d.id]||0; });
        await db().ref('groups/'+gid+'/counts/'+mid).set(payload);
        // refresh public aggregate
        const merged=Object.assign({}, group.counts||{}); merged[mid]=payload;
        recomputePublicGroup(gid, group, merged, members);
        toast('הספירה תוקנה ✓'); setBusy(false); onClose();
      }catch(ex){ console.warn('[admin-counts]',ex&&ex.code); toast('שגיאה בתיקון'+(ex&&ex.code?' ('+ex.code+')':'')); setBusy(false); }
    };

    const toggleRole=async()=>{
      const next = m.role==='admin' ? 'member' : 'admin';
      setBusy(true);
      try{ await db().ref('groups/'+gid+'/members/'+mid+'/role').set(next); toast(next==='admin'?'מונה למנהל/ת ✓':'הוסר תפקיד הניהול'); setBusy(false); onClose(); }
      catch(ex){ console.warn('[admin-role]',ex&&ex.code); toast('שגיאה'+(ex&&ex.code?' ('+ex.code+')':'')); setBusy(false); }
    };

    const removeMember=async()=>{
      setBusy(true);
      try{
        await db().ref('groups/'+gid+'/counts/'+mid).remove();
        await db().ref('groups/'+gid+'/members/'+mid).remove();
        // best-effort cleanup (allowed only for that user themselves / owner — ignore failures)
        db().ref('public/users/'+mid+'/groups/'+gid).remove().catch(()=>{});
        const merged=Object.assign({}, group.counts||{}); delete merged[mid];
        const remMem=Object.assign({}, members); delete remMem[mid];
        recomputePublicGroup(gid, group, merged, remMem);
        toast(isChild?'המשתתף/ת הוסר/ה':'החבר/ה הוסר/ה'); setBusy(false);
        onAfterRemove&&onAfterRemove(mid); onClose();
      }catch(ex){ console.warn('[admin-remove]',ex&&ex.code); toast('שגיאה בהסרה'+(ex&&ex.code?' ('+ex.code+')':'')); setBusy(false); }
    };

    const askRemove=()=>setConfirmCfg({
      title: isChild?'להסיר את '+m.name+'?':'להסיר את '+m.name+' מהקבוצה?',
      body:'הספירה שצברו תימחק מהקבוצה. אי-אפשר לבטל.',
      confirmLabel:'כן, להסיר', danger:true, run:removeMember,
    });

    /* ----- render header ----- */
    const header = (
      <div className="md-head">
        <AvatarImg value={m.avatar} size={56}/>
        <div>
          <h3 style={{margin:0}}>{m.name}{isSelf?' (אתם)':''}</h3>
          <div className="muted" style={{fontWeight:700}}>
            {m.role==='admin'?'מנהל/ת':'חבר/ה'}{isChild?' · משתתף/ת':''} · {draftCans} מכלים · <span dir="ltr">₪{draftMoney.toFixed(2)}</span>
          </div>
        </div>
      </div>
    );

    return (
      <div className="sheet-bg" onClick={onClose}>
        <div className="sheet" onClick={e=>e.stopPropagation()}>
          <div className="sheet-handle"></div>

          {view==='main' && (<>
            {header}
            <div className="adm-actions">
              {isChild && (
                <button type="button" className="adm-row" onClick={()=>setView('edit')}>
                  <span className="ai">✏️</span><span className="al">עריכת שם ודמות</span><span className="ar">›</span>
                </button>
              )}
              <button type="button" className="adm-row" onClick={()=>setView('counts')}>
                <span className="ai">🔢</span><span className="al">תיקון ספירה</span><span className="ar">›</span>
              </button>
              {!isChild && !isSelf && (
                <button type="button" className="adm-row" onClick={toggleRole} disabled={busy}>
                  <span className="ai">{m.role==='admin'?'⬇️':'⭐'}</span>
                  <span className="al">{m.role==='admin'?'ביטול הרשאת ניהול':'מינוי למנהל/ת'}</span>
                  <span className="ar">›</span>
                </button>
              )}
              {isSelf && m.role==='admin' && !isLastAdmin && (
                <button type="button" className="adm-row" onClick={toggleRole} disabled={busy}>
                  <span className="ai">⬇️</span><span className="al">ויתור על הרשאת הניהול שלי</span><span className="ar">›</span>
                </button>
              )}
              {!isSelf && (
                <button type="button" className="adm-row danger" onClick={askRemove} disabled={busy}>
                  <span className="ai">🗑️</span><span className="al">{isChild?'הסרת המשתתף/ת':'הסרה מהקבוצה'}</span><span className="ar">›</span>
                </button>
              )}
            </div>
            {isLastAdmin && isSelf && <p className="muted" style={{textAlign:'center',marginTop:12}}>אתם המנהל/ת היחיד/ה — מנו עוד מנהל/ת לפני שתוותרו על התפקיד.</p>}
            <button type="button" className="btn ghost dark" style={{marginTop:14}} onClick={onClose}>סגירה</button>
          </>)}

          {view==='edit' && (
            <form onSubmit={saveProfile}>
              <h3 style={{fontFamily:"'Varela Round'"}}>עריכת {m.name}</h3>
              <label className="fld"><span className="lab">השם</span>
                <input className="input" autoFocus value={eName} onChange={e=>setEName(e.target.value)} maxLength={16}/>
              </label>
              <span className="lab" style={{display:'block',marginBottom:2}}>הדמות</span>
              <AvatarPicker value={eAvatar} onChange={setEAvatar}/>
              <div style={{display:'flex',gap:8,marginTop:12}}>
                <button className="btn" type="submit" disabled={busy} style={{flex:1}}>{busy?'שומר…':'שמירה ✓'}</button>
                <button className="btn ghost dark" type="button" onClick={()=>setView('main')}>חזרה</button>
              </div>
            </form>
          )}

          {view==='counts' && (<>
            <h3 style={{fontFamily:"'Varela Round'"}}>תיקון ספירה · {m.name}</h3>
            <p className="muted" style={{margin:'0 0 12px',lineHeight:1.5}}>תקנו טעות הזנה. השינוי משפיע על הסך הקבוצתי ועל הדירוג.</p>
            <div className="adm-counts">
              {C.map(d=>(
                <div className="adm-cnt-row" key={d.id}>
                  <span className="acc-emoji">{d.emoji}</span>
                  <span className="acc-name">{d.nm}</span>
                  <div className="acc-step">
                    <button type="button" onClick={()=>setN(d.id,(draft[d.id]||0)-1)} aria-label="פחות">−</button>
                    <input className="input acc-num" type="number" min="0" dir="ltr" value={draft[d.id]||0} onChange={e=>setN(d.id,parseInt(e.target.value,10))}/>
                    <button type="button" onClick={()=>setN(d.id,(draft[d.id]||0)+1)} aria-label="עוד">+</button>
                  </div>
                </div>
              ))}
            </div>
            <div className="adm-cnt-total">סה"כ: <b>{draftCans}</b> מכלים · <b dir="ltr">₪{draftMoney.toFixed(2)}</b></div>
            <div style={{display:'flex',gap:8,marginTop:14}}>
              <button className="btn" type="button" onClick={saveCounts} disabled={busy} style={{flex:1}}>{busy?'שומר…':'שמירת התיקון ✓'}</button>
              <button className="btn ghost dark" type="button" onClick={()=>setView('main')}>חזרה</button>
            </div>
          </>)}
        </div>

        {confirmCfg && (
          <ConfirmDialog
            title={confirmCfg.title} body={confirmCfg.body} confirmLabel={confirmCfg.confirmLabel} danger={confirmCfg.danger} busy={busy}
            onCancel={()=>{ if(!busy) setConfirmCfg(null); }}
            onConfirm={async()=>{ await confirmCfg.run(); setConfirmCfg(null); }}/>
        )}
      </div>
    );
  }

  /* ---------- owner super-admin panel (app owners only) ---------- */
  function OwnerAdminPanel({selfUid, selfEmail, toast, onClose, onEnterGroup}){
    const { GroupIcon } = window;
    const C = window.CONTAINERS||[];
    const [groups,setGroups]=useState(null);
    const [leads,setLeads]=useState(null);
    const [q,setQ]=useState('');
    const [busy,setBusy]=useState(false);
    const [confirmCfg,setConfirmCfg]=useState(null);

    useEffect(()=>{
      const ref=db().ref('leads');
      const h=(s)=>{ const v=s.val()||{}; setLeads(Object.keys(v).map(k=>({id:k,...v[k]})).sort((a,b)=>(b.ts||0)-(a.ts||0))); };
      ref.on('value',h,()=>setLeads([])); return ()=>ref.off('value',h);
    },[]);
    const deleteLead=(id)=>db().ref('leads/'+id).remove().catch(()=>{});
    const fmtDate=(t)=>{ try{ return new Date(t).toLocaleDateString('he-IL',{day:'numeric',month:'short'}); }catch(e){ return ''; } };

    useEffect(()=>{
      const ref=db().ref('groups');
      const h=(s)=>setGroups(s.val()||{});
      const err=(e)=>{ console.warn('[owner-read]',e&&e.code); toast('אין הרשאת קריאה-על — בדקו שהמייל מאושר בכללים'); setGroups({}); };
      ref.on('value',h,err); return ()=>ref.off('value',h);
    },[]);

    const list = groups ? Object.keys(groups).map(gid=>{
      const g=groups[gid]||{};
      const counts=g.counts||{}; let money=0,cans=0;
      Object.keys(counts).forEach(u=>{ C.forEach(d=>{ const n=(counts[u]&&counts[u][d.id])||0; money+=n*d.rate; cans+=n; }); });
      return { gid, name:g.name||'(ללא שם)', icon:g.icon, members:Object.keys(g.members||{}).length, money, mult:Math.max(1,g.boostMult||1), createdAt:g.createdAt||0, family:!!g.family };
    }).sort((a,b)=>(b.createdAt||0)-(a.createdAt||0)) : [];
    const filtered = list.filter(x=> !q.trim() || x.name.includes(q.trim()) || x.gid.includes(q.trim().toUpperCase()));
    const totals = list.reduce((a,x)=>({groups:a.groups+1, members:a.members+x.members, money:a.money+x.money*x.mult}),{groups:0,members:0,money:0});

    const deleteGroup=async(gid)=>{
      setBusy(true);
      try{
        // members → clean their own group refs is not possible for the owner per-user,
        // but the owner CAN remove public + the whole group node.
        await db().ref('public/groups/'+gid).remove().catch(()=>{});
        await db().ref('groups/'+gid).remove();
        toast('הקבוצה נמחקה'); setBusy(false); setConfirmCfg(null);
      }catch(ex){ console.warn('[owner-del]',ex&&ex.code); toast('שגיאה במחיקה'+(ex&&ex.code?' ('+ex.code+')':'')); setBusy(false); }
    };

    return (
      <div className="owner-panel">
        <div className="op-top">
          <div>
            <h2>🛡️ ניהול-על</h2>
            <div className="op-sub">{selfEmail}</div>
          </div>
          <button className="gv-icon" onClick={onClose} aria-label="סגירה">✕</button>
        </div>

        <div className="op-stats">
          <div className="op-stat"><b>{totals.groups}</b><span>קבוצות</span></div>
          <div className="op-stat"><b>{totals.members}</b><span>חברים</span></div>
          <div className="op-stat"><b dir="ltr">₪{Math.round(totals.money)}</b><span>סה"כ נצבר</span></div>
        </div>

        <input className="input op-search" value={q} onChange={e=>setQ(e.target.value)} placeholder="חיפוש לפי שם או קוד…"/>

        {groups===null ? <div className="center-load" style={{minHeight:120}}><div className="spin"></div></div> : (
          <div className="op-list">
            {filtered.length===0 && <div className="muted" style={{textAlign:'center',padding:'20px 0'}}>אין קבוצות תואמות.</div>}
            {filtered.map(x=>(
              <div className="op-row" key={x.gid}>
                <GroupIcon value={x.icon} size={42} radius={12}/>
                <div className="op-info">
                  <div className="op-name">{x.name}{x.family && <span className="op-tag">משפחה</span>}</div>
                  <div className="op-meta">קוד {x.gid} · {x.members} חברים · <span dir="ltr">₪{Math.round(x.money*x.mult)}</span></div>
                </div>
                <button className="op-act enter" onClick={()=>onEnterGroup(x.gid)} aria-label="כניסה">↩</button>
                <button className="op-act del" onClick={()=>setConfirmCfg(x)} aria-label="מחיקה">🗑️</button>
              </div>
            ))}
          </div>
        )}

        {confirmCfg && (
          <ConfirmDialog
            title={'למחוק את "'+confirmCfg.name+'"?'}
            body={'הקבוצה (קוד '+confirmCfg.gid+'), כל החברים, הספירות והצ\'אט יימחקו לצמיתות. אי-אפשר לבטל.'}
            confirmLabel="מחיקה לצמיתות" danger={true} busy={busy}
            onCancel={()=>{ if(!busy) setConfirmCfg(null); }}
            onConfirm={()=>deleteGroup(confirmCfg.gid)}/>
        )}

        <div className="op-sectitle">📨 פניות ושיתופי פעולה{leads&&leads.length?(' ('+leads.length+')'):''}</div>
        {leads===null ? <div className="center-load" style={{minHeight:80}}><div className="spin"></div></div> : (
          leads.length===0 ? <div className="muted" style={{textAlign:'center',padding:'10px 0'}}>אין פניות עדיין.</div> : (
            <div className="op-leads">
              {leads.map(l=>(
                <div className="lead-row" key={l.id}>
                  <div className="lead-main">
                    <div className="lead-name">{l.name||'ללא שם'}{l.org?<span className="lead-org"> · {l.org}</span>:null}<span className="lead-date">{fmtDate(l.ts)}</span></div>
                    {l.contact ? <a className="lead-contact" href={/@/.test(l.contact)?('mailto:'+l.contact):undefined} dir="auto">{l.contact}</a> : null}
                    {l.msg ? <div className="lead-msg">“{l.msg}”</div> : null}
                  </div>
                  <button className="op-act del" onClick={()=>deleteLead(l.id)} aria-label="מחיקת פניה">🗑️</button>
                </div>
              ))}
            </div>
          )
        )}
      </div>
    );
  }

  Object.assign(window, { OWNER_EMAILS, isOwnerEmail, ConfirmDialog, MemberActionSheet, OwnerAdminPanel, recomputePublicGroup });
})();
