/* ============================================================
   Nuad Now — แต่ง avatar หลายช่อง (SVG)  (JSX)
   ช่อง: พื้นหลัง · กรอบ · หมวก · แว่น · ของแต่งหน้า · เอฟเฟกต์ · สีชื่อ · ฉายา
   ภาพไอเท็มวาดเป็น SVG บน "พิกัด 0-100" ที่ครอบวงกลม avatar (ตำแหน่งต่อเพศใน AV_ANCHOR)
   ข้อมูลว่าใครใส่อะไร: NN.looks[employee_id] = { bg, frame, hat, glasses, face, effect, namecolor, title }
   ============================================================ */

/* จุดอ้างอิงบนใบหน้า (พิกัด 0-100 ของวงกลม avatar) — สอบเทียบกับ avatar-male/female.webp */
const AV_ANCHOR = {
  female: { cx:42, eyeY:67.5, eyeL:25.5, eyeR:57.5, topY:23, w:70, mouthY:70.5 },
  male:   { cx:51, eyeY:63.5, eyeL:34.5, eyeR:70,   topY:13, w:82, mouthY:70.5 },
};

/* ช่องทั้งหมดที่ใส่ได้ (เรียงตามที่แสดงในร้าน) */
const AV_SLOTS = [
  { k:'bg',        th:'พื้นหลัง', en:'Backdrop' },
  { k:'frame',     th:'กรอบ',     en:'Frame' },
  { k:'hat',       th:'หมวก',     en:'Hats' },
  { k:'glasses',   th:'แว่น',     en:'Glasses' },
  { k:'face',      th:'ใบหน้า',   en:'Face' },
  { k:'effect',    th:'เอฟเฟกต์', en:'Effects' },
  { k:'namecolor', th:'สีชื่อ',   en:'Name color' },
  { k:'title',     th:'ฉายา',     en:'Titles' },
];

/* พื้นหลัง = CSS background ที่วางหลัง avatar (รูป avatar โปร่งใส) */
const AV_BG = {
  bg_sakura: 'radial-gradient(circle at 22% 24%,#fff 0 2.5px,transparent 3.5px),radial-gradient(circle at 78% 18%,#fff 0 2px,transparent 3px),radial-gradient(circle at 84% 70%,#fff 0 3px,transparent 4px),radial-gradient(circle at 14% 78%,#fff 0 2px,transparent 3px),linear-gradient(160deg,#FFD9E8,#FFB3D1)',
  bg_mint:   'repeating-linear-gradient(135deg,#CBF7E7 0 14%,#A6EAD1 14% 28%)',
  bg_polka:  'radial-gradient(circle,#FFC93C 0 2.2px,transparent 3px) 0 0/22% 22%,#FFF4C2',
  bg_sunset: 'linear-gradient(180deg,#FFD194 0%,#FF8E72 58%,#C86DD7 100%)',
  bg_night:  'radial-gradient(circle at 20% 26%,#fff 0 1.4px,transparent 2.4px),radial-gradient(circle at 76% 20%,#fff 0 1.6px,transparent 2.6px),radial-gradient(circle at 86% 62%,#fff 0 1.2px,transparent 2.2px),radial-gradient(circle at 12% 70%,#fff 0 1.2px,transparent 2.2px),radial-gradient(circle at 60% 10%,#FFE98A 0 1.6px,transparent 2.6px),linear-gradient(180deg,#0F1B5C,#4B3C9E)',
};

/* ── ตัวช่วยวาด ── */
function starPath(R, r){            // ดาว 5 แฉกรอบจุด (0,0)
  let d='';
  for(let i=0;i<10;i++){
    const rad = i%2===0 ? R : r, t = (-90 + i*36) * Math.PI/180;
    d += (i?'L':'M') + (Math.cos(t)*rad).toFixed(2) + ',' + (Math.sin(t)*rad).toFixed(2);
  }
  return d + 'Z';
}
const HEART_D = 'M0,4 C-7,-1 -6,-7 -2.8,-7 C-1.2,-7 0,-5.8 0,-4.6 C0,-5.8 1.2,-7 2.8,-7 C6,-7 7,-1 0,4Z';
const SPARK_D = 'M0,-5 L1.3,-1.3 L5,0 L1.3,1.3 L0,5 L-1.3,1.3 L-5,0 L-1.3,-1.3Z';

function Flower({x,y,r,c}){
  return (
    <g>
      {[0,1,2,3,4].map(i=>{ const t=i*72*Math.PI/180;
        return <circle key={i} cx={x+Math.sin(t)*r} cy={y-Math.cos(t)*r} r={r*0.65} fill={c} stroke="rgba(0,0,0,.12)" strokeWidth=".3"/>; })}
      <circle cx={x} cy={y} r={r*0.5} fill="#FFD54A"/>
    </g>
  );
}

/* ── หมวก / ที่คาดผม — วาดโดยอิงกลางศีรษะ (cx) ยอดศีรษะ (topY) และความกว้างหัว (w) ── */
const AV_ITEMS = {
  hat_catears: a => { const {cx,topY:t,w}=a; return (
    <g>
      <path d={`M${cx-.42*w},${t+.2*w} Q${cx},${t-.12*w} ${cx+.42*w},${t+.2*w}`} fill="none" stroke="#4A3B3B" strokeWidth="2.4" strokeLinecap="round"/>
      <path d={`M${cx-.4*w},${t+.12*w} L${cx-.33*w},${t-.2*w} L${cx-.1*w},${t-.01*w}Z`} fill="#6B5B5B" stroke="#4A3B3B" strokeWidth="1" strokeLinejoin="round"/>
      <path d={`M${cx-.35*w},${t+.07*w} L${cx-.31*w},${t-.12*w} L${cx-.17*w},${t-.02*w}Z`} fill="#FFB3C7"/>
      <path d={`M${cx+.4*w},${t+.12*w} L${cx+.33*w},${t-.2*w} L${cx+.1*w},${t-.01*w}Z`} fill="#6B5B5B" stroke="#4A3B3B" strokeWidth="1" strokeLinejoin="round"/>
      <path d={`M${cx+.35*w},${t+.07*w} L${cx+.31*w},${t-.12*w} L${cx+.17*w},${t-.02*w}Z`} fill="#FFB3C7"/>
    </g>); },
  hat_bunny: a => { const {cx,topY:t,w}=a; return (
    <g>
      <g transform={`rotate(-14 ${cx-.2*w} ${t+.1*w})`}>
        <ellipse cx={cx-.2*w} cy={t-.2*w} rx={.09*w} ry={.3*w} fill="#fff" stroke="#D8C9CF" strokeWidth="1"/>
        <ellipse cx={cx-.2*w} cy={t-.19*w} rx={.045*w} ry={.22*w} fill="#FFC2D4"/>
      </g>
      <g transform={`rotate(14 ${cx+.2*w} ${t+.1*w})`}>
        <ellipse cx={cx+.2*w} cy={t-.2*w} rx={.09*w} ry={.3*w} fill="#fff" stroke="#D8C9CF" strokeWidth="1"/>
        <ellipse cx={cx+.2*w} cy={t-.19*w} rx={.045*w} ry={.22*w} fill="#FFC2D4"/>
      </g>
      <path d={`M${cx-.36*w},${t+.18*w} Q${cx},${t-.02*w} ${cx+.36*w},${t+.18*w}`} fill="none" stroke="#F4A6BF" strokeWidth="2.6" strokeLinecap="round"/>
    </g>); },
  hat_party: a => { const {cx,topY:t,w}=a; const bx=cx+.06*w; return (
    <g transform={`rotate(10 ${bx} ${t+.1*w})`}>
      <path d={`M${bx},${t-.58*w} L${bx-.26*w},${t+.12*w} L${bx+.26*w},${t+.12*w}Z`} fill="#FF7AB6" stroke="#D9508F" strokeWidth="1" strokeLinejoin="round"/>
      <path d={`M${bx-.16*w},${t-.2*w} L${bx+.16*w},${t-.2*w} L${bx+.2*w},${t-.07*w} L${bx-.2*w},${t-.07*w}Z`} fill="#FFE066"/>
      <circle cx={bx-.07*w} cy={t-.34*w} r={.025*w} fill="#fff"/><circle cx={bx+.05*w} cy={t-.4*w} r={.025*w} fill="#fff"/>
      <circle cx={bx-.1*w} cy={t+.03*w} r={.025*w} fill="#fff"/><circle cx={bx+.1*w} cy={t+.04*w} r={.025*w} fill="#fff"/>
      <circle cx={bx} cy={t-.6*w} r={.07*w} fill="#FFE066" stroke="#E0B92E" strokeWidth=".8"/>
    </g>); },
  hat_flower: a => { const {cx,topY:t,w}=a;
    const cols=['#FF8FB8','#FFE066','#fff','#FF8FB8','#FFE066','#fff','#FF8FB8'];
    const pts=cols.map((c,i)=>{ const u=(i/(cols.length-1))*2-1; return {x:cx+u*.42*w, y:t+.14*w-.17*w*(1-u*u)+Math.abs(u)*.05*w, c, r:.062*w}; });
    return (
      <g>
        <path d={`M${cx-.43*w},${t+.19*w} Q${cx},${t-.14*w} ${cx+.43*w},${t+.19*w}`} fill="none" stroke="#5FA85F" strokeWidth="2.4" strokeLinecap="round"/>
        {pts.map((p,i)=><Flower key={i} x={p.x} y={p.y} r={p.r} c={p.c}/>)}
      </g>); },
  hat_beret: a => { const {cx,topY:t,w}=a; return (
    <g transform={`rotate(-9 ${cx} ${t})`}>
      <ellipse cx={cx} cy={t+.01*w} rx={.45*w} ry={.17*w} fill="#C0392B" stroke="#8E2A20" strokeWidth="1"/>
      <path d={`M${cx-.4*w},${t+.07*w} Q${cx},${t+.2*w} ${cx+.4*w},${t+.07*w}`} fill="none" stroke="#8E2A20" strokeWidth="1.4" strokeLinecap="round"/>
      <circle cx={cx+.12*w} cy={t-.15*w} r={.035*w} fill="#8E2A20"/>
    </g>); },
  hat_straw: a => { const {cx,topY:t,w}=a; return (
    <g>
      <path d={`M${cx-.28*w},${t+.14*w} Q${cx-.3*w},${t-.2*w} ${cx},${t-.22*w} Q${cx+.3*w},${t-.2*w} ${cx+.28*w},${t+.14*w}Z`} fill="#F3D78A" stroke="#C99A2E" strokeWidth="1"/>
      <path d={`M${cx-.285*w},${t+.06*w} Q${cx},${t+.1*w} ${cx+.285*w},${t+.06*w} L${cx+.28*w},${t+.14*w} Q${cx},${t+.18*w} ${cx-.28*w},${t+.14*w}Z`} fill="#D64545"/>
      <ellipse cx={cx} cy={t+.15*w} rx={.6*w} ry={.1*w} fill="#E9C46A" stroke="#C99A2E" strokeWidth="1"/>
    </g>); },

  /* ── แว่น — อิงตำแหน่งตา ── */
  glasses_round: a => { const {eyeL:l,eyeR:r,eyeY:y}=a; const R=(r-l)*.25; return (
    <g fill="rgba(255,255,255,.2)" stroke="#3B3B3B" strokeWidth="1.8">
      <circle cx={l} cy={y} r={R}/><circle cx={r} cy={y} r={R}/>
      <path d={`M${l+R},${y} Q${(l+r)/2},${y-R*.5} ${r-R},${y}`} fill="none"/>
      <path d={`M${l-R},${y} L${l-R-4},${y-1}`} fill="none"/><path d={`M${r+R},${y} L${r+R+4},${y-1}`} fill="none"/>
    </g>); },
  glasses_heart: a => { const {eyeL:l,eyeR:r,eyeY:y}=a; const s=(r-l)*.036; return (
    <g fill="rgba(255,105,150,.35)" stroke="#E0457B" strokeWidth="1.6" strokeLinejoin="round">
      <path d={HEART_D} transform={`translate(${l} ${y+.3}) scale(${s*1.15})`} strokeWidth={1.6/(s*1.15)}/>
      <path d={HEART_D} transform={`translate(${r} ${y+.3}) scale(${s*1.15})`} strokeWidth={1.6/(s*1.15)}/>
      <path d={`M${l+(r-l)*.17},${y-1} Q${(l+r)/2},${y-5} ${r-(r-l)*.17},${y-1}`} fill="none"/>
    </g>); },
  glasses_star: a => { const {eyeL:l,eyeR:r,eyeY:y}=a; const R=(r-l)*.3; return (
    <g fill="rgba(255,213,74,.5)" stroke="#D49B0F" strokeWidth="1.5" strokeLinejoin="round">
      <path d={starPath(R,R*.5)} transform={`translate(${l} ${y})`}/><path d={starPath(R,R*.5)} transform={`translate(${r} ${y})`}/>
      <path d={`M${l+R*.55},${y-1} L${r-R*.55},${y-1}`} fill="none"/>
    </g>); },
  glasses_sun: a => { const {eyeL:l,eyeR:r,eyeY:y}=a; const W=(r-l)*.36, H=(r-l)*.27; return (
    <g>
      <rect x={l-W/2} y={y-H/2} width={W} height={H} rx={H*.42} fill="#202020" stroke="#000" strokeWidth="1"/>
      <rect x={r-W/2} y={y-H/2} width={W} height={H} rx={H*.42} fill="#202020" stroke="#000" strokeWidth="1"/>
      <path d={`M${l+W/2},${y-H*.2} L${r-W/2},${y-H*.2}`} stroke="#000" strokeWidth="1.8" fill="none"/>
      <path d={`M${l-W*.3},${y-H*.28} L${l-W*.12},${y-H*.28}`} stroke="rgba(255,255,255,.5)" strokeWidth="1.2" strokeLinecap="round"/>
      <path d={`M${r-W*.3},${y-H*.28} L${r-W*.12},${y-H*.28}`} stroke="rgba(255,255,255,.5)" strokeWidth="1.2" strokeLinecap="round"/>
    </g>); },

  /* ── ของแต่งหน้า ── */
  face_freckles: a => { const {eyeL:l,eyeR:r,eyeY:y}=a; const dots=[[-4,8],[0,10],[4,8],[-2,13],[3,12.5]]; return (
    <g fill="#B5651D" opacity=".75">
      {[l,r].map((x,i)=>dots.map(([dx,dy],j)=><circle key={i+'-'+j} cx={x+dx} cy={y+dy} r=".95"/>))}
    </g>); },
  face_bandaid: a => { const {eyeR:r,eyeY:y}=a; return (
    <g transform={`translate(${r+3} ${y+10}) rotate(-28)`}>
      <rect x="-8" y="-3" width="16" height="6" rx="3" fill="#F6CFA4" stroke="#D9A877" strokeWidth=".8"/>
      <rect x="-3" y="-3" width="6" height="6" fill="#E9B98A"/>
      <circle cx="-5.2" cy="0" r=".5" fill="#D9A877"/><circle cx="5.2" cy="0" r=".5" fill="#D9A877"/>
    </g>); },
  face_whiskers: a => { const {eyeL:l,eyeR:r,eyeY:y}=a; return (
    <g stroke="#444" strokeWidth="1.1" strokeLinecap="round" fill="none">
      {[-4,1,6].map((dy,i)=><path key={'l'+i} d={`M${l+1},${y+7+dy*.5} L${l-11},${y+6+dy}`}/>)}
      {[-4,1,6].map((dy,i)=><path key={'r'+i} d={`M${r-1},${y+7+dy*.5} L${r+11},${y+6+dy}`}/>)}
    </g>); },
  face_mustache: a => { const {eyeL:l,eyeR:r,mouthY:m,w}=a; const x=(l+r)/2, s=w/80; return (
    <path d="M-11,1 Q-9,-5 -3,-2 Q0,-3.5 3,-2 Q9,-5 11,1 Q8,5 3,1.5 Q0,2.5 -3,1.5 Q-8,5 -11,1Z"
      transform={`translate(${x} ${m-3.2}) scale(${s})`} fill="#3A2A22" stroke="#1F1511" strokeWidth=".6"/>); },

  /* ── เอฟเฟกต์ — ครอบทั้งวงกลม มีแอนิเมชัน ── */
  effect_sparkle: () => (
    <g fill="#FFD54A" stroke="#fff" strokeWidth=".5">
      {[[12,24,0],[88,30,.5],[82,80,1],[16,72,1.5],[50,5,.8]].map(([x,y,d],i)=>(
        <path key={i} d={SPARK_D} transform={`translate(${x} ${y})`} className="fx-twinkle" style={{animationDelay:d+'s'}}/>))}
    </g>),
  effect_hearts: () => (
    <g fill="#FF6F91" stroke="#fff" strokeWidth=".5">
      {[[26,60,0],[52,66,.9],[74,58,1.7]].map(([x,y,d],i)=>(
        <path key={i} d={HEART_D} transform={`translate(${x} ${y})`} className="fx-float" style={{animationDelay:d+'s'}}/>))}
    </g>),
  effect_petals: () => (
    <g fill="#FFB3D1" stroke="#FF8FB8" strokeWidth=".4">
      {[[16,-4,0],[36,-4,1.2],[58,-4,.5],[78,-4,1.8],[90,-4,.9]].map(([x,y,d],i)=>(
        <ellipse key={i} cx={x} cy={y} rx="2.6" ry="1.6" className="fx-fall" style={{animationDelay:d+'s'}}/>))}
    </g>),
  effect_notes: () => (
    <g fill="#6C5CE7" fontFamily="sans-serif" fontWeight="700" fontSize="13">
      {[[20,64,0,'♪'],[48,70,1,'♫'],[78,62,1.8,'♪']].map(([x,y,d,ch],i)=>(
        <text key={i} x={x} y={y} className="fx-float" style={{animationDelay:d+'s'}}>{ch}</text>))}
    </g>),
};

/* ลำดับการวาดซ้อนกัน (ล่าง → บน) */
const AV_LAYER_ORDER = ['face','glasses','hat','effect'];

/* ตัว avatar + เลเยอร์ไอเท็ม — gender ต้องเป็น male/female ถึงจะวาดหมวก/แว่น/ของแต่งหน้า */
function AvatarBody({look, ...p}){
  const lk = look || {};
  const size = p.size || 40;
  const a = AV_ANCHOR[p.gender];
  const bg = lk.bg && AV_BG[lk.bg];
  const style = bg ? {...(p.style||{}), background:bg} : p.style;
  const layers = a ? AV_LAYER_ORDER.filter(k=>lk[k] && AV_ITEMS[lk[k]]) : [];
  if(!layers.length) return <AvatarImg {...p} style={style}/>;
  return (
    <span className="av-stack" style={{width:size, height:size}}>
      <AvatarImg {...p} style={style}/>
      <svg className="av-layers" viewBox="0 0 100 100" aria-hidden="true"
        style={{left:2.5, top:2.5, width:size-5, height:size-5}}>
        {layers.map(k=><g key={k}>{AV_ITEMS[lk[k]](a)}</g>)}
      </svg>
    </span>
  );
}

/* ฉายาข้างชื่อ — ข้อความคือชื่อสินค้าฉายา */
function UserTitle({id, look}){
  const lk = look || (id && window.NN && NN.looks && NN.looks[id]);
  const it = lk && lk.title && NN.itemsById && NN.itemsById[lk.title];
  if(!it) return null;
  return <span className="user-title">{window.NN_LANG==='en' ? it.name_en : it.name_th}</span>;
}

Object.assign(window, { AvatarBody, UserTitle, AV_SLOTS, AV_ITEMS, AV_BG, AV_ANCHOR });
