/* ============ AVATARS: character set + picker + renderer ============ */
(function(){
  const { useState, useRef } = React;

  // avatar value = character id (string) OR a data: URL (uploaded photo)
  const BASE_CHARS=[
    {id:'fox',     e:'🦊', g:['#ff9a3f','#ff5e62']},
    {id:'frog',    e:'🐸', g:['#2fe07a','#16a85a']},
    {id:'unicorn', e:'🦄', g:['#ff7ac2','#b06bff']},
    {id:'penguin', e:'🐧', g:['#5be8f0','#2a6fdb']},
    {id:'dino',    e:'🦖', g:['#9be37a','#16a85a']},
    {id:'dragon',  e:'🐲', g:['#2fe07a','#1fd9e6']},
    {id:'lion',    e:'🦁', g:['#ffe14d','#ff9a3f']},
    {id:'panda',   e:'🐼', g:['#cfd8df','#7c8f95']},
    {id:'owl',     e:'🦉', g:['#c79bff','#7a4ddb']},
    {id:'octopus', e:'🐙', g:['#ff7ac2','#c81f6e']},
    {id:'bee',     e:'🐝', g:['#ffe14d','#e0a500']},
    {id:'cat',     e:'🐱', g:['#ffc36e','#ff7aa8']},
    {id:'robot',   e:'🤖', g:['#5be8f0','#0a9aa6']},
    {id:'alien',   e:'👽', g:['#7df0a8','#1fd9e6']},
    {id:'ghost',   e:'👻', g:['#dbe6ef','#9aa7b0']},
    {id:'monster', e:'👾', g:['#c79bff','#ff4d9d']},
    {id:'tiger',   e:'🐯', g:['#ffb347','#ff7a45']},
    {id:'koala',   e:'🐨', g:['#b7c4cc','#7c8f95']},
    {id:'turtle',  e:'🐢', g:['#6fe39a','#0f9a6a']},
    {id:'whale',   e:'🐳', g:['#5bc8f0','#2a6fdb']},
  ];
  // extra characters — lots more to choose from (ids stay stable so saved avatars never change)
  const _GRADS=[
    ['#ff9a3f','#ff5e62'],['#2fe07a','#16a85a'],['#ff7ac2','#b06bff'],['#5be8f0','#2a6fdb'],
    ['#9be37a','#16a85a'],['#2fe07a','#1fd9e6'],['#ffe14d','#ff9a3f'],['#cfd8df','#7c8f95'],
    ['#c79bff','#7a4ddb'],['#ff7ac2','#c81f6e'],['#ffe14d','#e0a500'],['#ffc36e','#ff7aa8'],
    ['#5be8f0','#0a9aa6'],['#7df0a8','#1fd9e6'],['#dbe6ef','#9aa7b0'],['#c79bff','#ff4d9d'],
    ['#ffb347','#ff7a45'],['#b7c4cc','#7c8f95'],['#6fe39a','#0f9a6a'],['#5bc8f0','#2a6fdb'],
  ];
  const _EXTRA='🐶🐰🐹🐻🐮🐷🐵🐔🦆🦅🐺🦌🦒🐘🦏🐊🐍🦎🦑🦀🐠🐬🦈🐅🦍🐎🐉🦋🐌🐞🌵🌻🌈⭐🌙🪐🚀🛸🔥🍄🍎🍓🍉🍕🍩🧁🍦🍭🥑🥕⚽🏀🎮🎯🎸🎺🥁🎨🛹🚲😎🤩🥳🤠🧚🧙🧜';
  const _EXTRA_ARR=Array.from(_EXTRA);
  const CHARACTERS=[...BASE_CHARS, ..._EXTRA_ARR.map((e,i)=>({id:'x'+i, e, g:_GRADS[i%_GRADS.length]}))];
  const charById=(id)=>CHARACTERS.find(c=>c.id===id)||CHARACTERS[0];
  const isPhoto=(v)=>typeof v==='string' && (v.startsWith('data:') || v.startsWith('http'));

  function AvatarImg({value, size=44, ring}){
    const px=size+'px';
    const style={width:px, height:px};
    if(ring) style.border='2px solid '+ring;
    if(isPhoto(value)){
      return <div className="ava-img" style={style}><img src={value} alt=""/></div>;
    }
    const c=charById(value);
    style.background='linear-gradient(150deg,'+c.g[0]+','+c.g[1]+')';
    return <div className="ava-img" style={style}><span className="em" style={{fontSize:(size*0.55)+'px'}}>{c.e}</span></div>;
  }

  // downscale an uploaded image to a small circular-ready square data URL
  function fileToAvatar(file, cb){
    const reader=new FileReader();
    reader.onload=()=>{
      const img=new Image();
      img.onload=()=>{
        const S=200; const cv=document.createElement('canvas'); cv.width=S; cv.height=S;
        const ctx=cv.getContext('2d');
        const min=Math.min(img.width,img.height);
        const sx=(img.width-min)/2, sy=(img.height-min)/2;
        ctx.drawImage(img, sx,sy,min,min, 0,0,S,S);
        cb(cv.toDataURL('image/jpeg',0.82));
      };
      img.src=reader.result;
    };
    reader.readAsDataURL(file);
  }

  // downscale a receipt photo keeping aspect ratio (max edge ~1000px) for verification
  function fileToReceipt(file, cb){
    const reader=new FileReader();
    reader.onload=()=>{
      const img=new Image();
      img.onload=()=>{
        const MAX=1000; let w=img.width, h=img.height;
        if(Math.max(w,h)>MAX){ const k=MAX/Math.max(w,h); w=Math.round(w*k); h=Math.round(h*k); }
        const cv=document.createElement('canvas'); cv.width=w; cv.height=h;
        cv.getContext('2d').drawImage(img,0,0,w,h);
        cb(cv.toDataURL('image/jpeg',0.7));
      };
      img.src=reader.result;
    };
    reader.readAsDataURL(file);
  }

  function AvatarPicker({value, onChange}){
    const fileRef=useRef(null);
    const onFile=(e)=>{ const f=e.target.files&&e.target.files[0]; if(f) fileToAvatar(f, onChange); };
    return (
      <div>
        <div className="ava-grid">
          <button type="button" className="ava-upload" onClick={()=>fileRef.current&&fileRef.current.click()} title="העלאת תמונה">📷</button>
          {isPhoto(value) && (
            <button type="button" className={"ava-pick sel"} onClick={()=>fileRef.current&&fileRef.current.click()}>
              <AvatarImg value={value} size={54}/>
            </button>
          )}
          {CHARACTERS.map(c=>(
            <button type="button" key={c.id} className={"ava-pick"+(value===c.id?' sel':'')} onClick={()=>onChange(c.id)}>
              <AvatarImg value={c.id} size={54}/>
            </button>
          ))}
        </div>
        <input ref={fileRef} type="file" accept="image/*" style={{display:'none'}} onChange={onFile}/>
      </div>
    );
  }

  /* ---------- group icon (emoji on green, or uploaded photo) ---------- */
  const GROUP_EMOJIS=['♻️','🏠','🏫','🌳','🌍','⚽','🎯','🏆','🐝','🚲','⭐','🦖','💚','🎒','🏕️','🚀'];

  function GroupIcon({value, size=40, radius}){
    const px=size+'px';
    const r=(radius||Math.round(size*0.28))+'px';
    const style={width:px,height:px,borderRadius:r,flex:'none',display:'grid',placeItems:'center',overflow:'hidden'};
    if(isPhoto(value)){
      return <div style={style}><img src={value} alt="" style={{width:'100%',height:'100%',objectFit:'cover'}}/></div>;
    }
    style.background='linear-gradient(150deg,var(--leaf),var(--leaf-dk))';
    return <div style={style}><span style={{fontSize:Math.round(size*0.52)+'px',lineHeight:1}}>{value||'♻️'}</span></div>;
  }

  function GroupIconPicker({value, onChange}){
    const fileRef=useRef(null);
    const onFile=(e)=>{ const f=e.target.files&&e.target.files[0]; if(f) fileToAvatar(f, onChange); };
    const photo=isPhoto(value);
    return (
      <div>
        <div className="gicon-grid">
          <button type="button" className="gicon-upload" onClick={()=>fileRef.current&&fileRef.current.click()} title="העלאת תמונה">📷</button>
          {photo && (
            <button type="button" className="gicon-pick sel" onClick={()=>fileRef.current&&fileRef.current.click()}>
              <GroupIcon value={value} size={54} radius={16}/>
            </button>
          )}
          {GROUP_EMOJIS.map(em=>(
            <button type="button" key={em} className={"gicon-pick"+(value===em?' sel':'')} onClick={()=>onChange(em)}>
              <GroupIcon value={em} size={54} radius={16}/>
            </button>
          ))}
        </div>
        <input ref={fileRef} type="file" accept="image/*" style={{display:'none'}} onChange={onFile}/>
      </div>
    );
  }

  Object.assign(window, { CHARACTERS, AvatarImg, AvatarPicker, fileToAvatar, fileToReceipt, avatarIsPhoto:isPhoto, GroupIcon, GroupIconPicker, GROUP_EMOJIS });
})();
