// ============================================================
// ui.jsx — ส่วนประกอบ UI ที่ใช้ร่วมกัน
// ============================================================
const { useState } = React;

function useMobile(bp=640){
  const [mob,setMob]=useState(()=>window.innerWidth<bp);
  React.useEffect(()=>{
    const fn=()=>setMob(window.innerWidth<bp);
    window.addEventListener('resize',fn);
    return ()=>window.removeEventListener('resize',fn);
  },[bp]);
  return mob;
}

// ---------- Avatar วงกลมอักษรย่อ ----------
function Avatar({ staff, size=26 }){
  return (
    <span style={{
      width:size, height:size, borderRadius:'50%', flex:'0 0 auto',
      display:'inline-flex', alignItems:'center', justifyContent:'center',
      background: staffColor(staff,'tint'), color: staffColor(staff,'text'),
      fontWeight:700, fontSize:size*0.42, fontFamily:'Anuphan, sans-serif',
      border:`1.5px solid ${staffColor(staff,'solid')}`,
    }}>{staff.nick.slice(0,1)}</span>
  );
}

// ---------- ชิปชื่อพนักงาน ----------
function NameChip({ staff, branch, onClick }){
  const b = BRANCHES[branch];
  return (
    <button onClick={onClick} style={{
      display:'inline-flex', alignItems:'center', gap:5, padding:'2px 8px 2px 3px',
      borderRadius:999, border:`1px solid ${b.solid}33`, background:'#fff',
      cursor:'pointer', fontFamily:'inherit', maxWidth:'100%',
    }}>
      <span style={{width:14,height:14,borderRadius:'50%',background:staffColor(staff,'solid'),flex:'0 0 auto'}}></span>
      <span style={{fontSize:12.5, fontWeight:600, color:'#2b2f3a', whiteSpace:'nowrap'}}>{staff.nick}</span>
    </button>
  );
}

// ---------- การ์ดสรุปด้านบน ----------
function StatCard({ value, label, theme }){
  const themes = {
    dark:  { bg:'linear-gradient(135deg,#2b2950,#1c1b38)', fg:'#fff', sub:'#c5c2e8' },
    b1:    { bg:'linear-gradient(135deg,#28b0a0,#15897a)', fg:'#fff', sub:'#d6f4ef' },
    b2:    { bg:'linear-gradient(135deg,#ef8466,#d65f44)', fg:'#fff', sub:'#fde3d9' },
    off:   { bg:'linear-gradient(135deg,#9aa3b6,#7a8497)', fg:'#fff', sub:'#eceef3' },
  };
  const t = themes[theme] || themes.dark;
  return (
    <div style={{
      flex:'1 1 0', minWidth:120, borderRadius:16, padding:'16px 18px',
      background:t.bg, color:t.fg, position:'relative', overflow:'hidden',
      boxShadow:'0 6px 18px -10px rgba(20,20,50,.5)',
    }}>
      <div style={{position:'absolute',right:-18,top:-18,width:70,height:70,borderRadius:'50%',background:'rgba(255,255,255,.10)'}}></div>
      <div style={{fontSize:30, fontWeight:800, fontFamily:'Anuphan, sans-serif', lineHeight:1}}>{value}</div>
      <div style={{fontSize:13, marginTop:6, color:t.sub, fontWeight:500}}>{label}</div>
    </div>
  );
}

// ---------- ปุ่มสลับ (segmented) ----------
function Segmented({ options, value, onChange, accent='#2b2950' }){
  return (
    <div style={{display:'inline-flex', background:'#eef0f5', borderRadius:999, padding:3, gap:2}}>
      {options.map(o => {
        const active = o.value === value;
        return (
          <button key={o.value} onClick={()=>onChange(o.value)} style={{
            display:'inline-flex', alignItems:'center', gap:6, padding:'7px 16px', borderRadius:999,
            border:'none', cursor:'pointer', fontFamily:'inherit', fontSize:13.5, fontWeight:600,
            background: active ? '#fff' : 'transparent',
            color: active ? accent : '#7b8194',
            boxShadow: active ? '0 2px 8px -3px rgba(0,0,0,.2)' : 'none',
            transition:'all .15s',
          }}>
            {o.icon && <span style={{fontSize:14}}>{o.icon}</span>}
            {o.label}
          </button>
        );
      })}
    </div>
  );
}

// ---------- กล่องคำอธิบายสี (legend) ----------
function Legend(){
  return (
    <div style={{background:'#fff',border:'1px solid #eceef3',borderRadius:14,padding:'12px 18px',
      display:'flex',flexWrap:'wrap',gap:'10px 22px',alignItems:'center'}}>
      <span style={{fontSize:12.5,fontWeight:700,color:'#9aa1b0'}}>สาขา</span>
      {['b1','b2'].map(k=>{
        const b = BRANCHES[k];
        return (
          <span key={k} style={{display:'inline-flex',alignItems:'center',gap:7,fontSize:13,color:'#3a3f4c',fontWeight:600}}>
            <span style={{width:14,height:14,borderRadius:5,background:b.solid}}></span>{b.name}
          </span>
        );
      })}
      <span style={{width:1,height:20,background:'#e9ebf0'}}></span>
      <span style={{fontSize:12.5,fontWeight:700,color:'#9aa1b0'}}>กะ</span>
      {['m','a'].map(k=>{
        const s = SHIFTS[k];
        return (
          <span key={k} style={{display:'inline-flex',alignItems:'center',gap:7,fontSize:13,color:'#3a3f4c',fontWeight:500}}>
            <span style={{width:18,height:18,borderRadius:5,background:s.tint,color:s.text,fontSize:11,fontWeight:800,
              display:'inline-flex',alignItems:'center',justifyContent:'center'}}>{s.char}</span>
            {s.label} <span style={{color:'#9aa1b0'}}>{s.time}</span>
          </span>
        );
      })}
      <span style={{fontSize:12,color:'#b4bac6',marginLeft:'auto'}}>เวียนสลับสาขา/กะ ทุกสัปดาห์</span>
    </div>
  );
}

// ---------- Top navigation ----------
function TopNav({ scope, onScope, monthDate, onMonthMove, onLogout, headerBg, badge, onBell, isAdmin, onAdmin, currentStaff }){
  const y = monthDate.getFullYear(), m = monthDate.getMonth();
  const mob = useMobile();

  const logoEl = (
    <div style={{display:'flex',alignItems:'center',gap:10}}>
      <div style={{
        width:mob?36:42,height:mob?36:42,borderRadius:mob?11:13,flex:'0 0 auto',
        background:'radial-gradient(120% 120% at 30% 18%, #2d2d2d 0%, #141414 55%, #050505 100%)',
        border:'1px solid rgba(255,255,255,.16)',
        boxShadow:'0 3px 10px rgba(0,0,0,.32), inset 0 1px 0 rgba(255,255,255,.07)',
        display:'flex',alignItems:'center',justifyContent:'center'}}>
        <img src="assets/logo-mark.png" alt="หมื่นเจริญ"
          style={{width:'70%',height:'70%',objectFit:'contain',display:'block'}}/>
      </div>
      {!mob && <div style={{lineHeight:1.12}}>
        <div style={{fontWeight:700,fontSize:16,fontFamily:'Anuphan'}}>หมื่นเจริญ</div>
        <div style={{fontSize:9.5,letterSpacing:1.8,color:'rgba(255,255,255,.78)'}}>MUEN&nbsp;CHAROEN</div>
      </div>}
    </div>
  );

  const monthNavEl = (
    <div style={{display:'flex',alignItems:'center',gap:mob?4:8,background:'rgba(255,255,255,.12)',
      borderRadius:999,padding:mob?'4px 6px':'5px 8px'}}>
      <button onClick={()=>onMonthMove(-1)} style={mob?navArrow:navArrowLg}>‹</button>
      <span style={{fontSize:mob?14:18,fontWeight:700,minWidth:mob?130:170,textAlign:'center',fontFamily:'Anuphan'}}>
        {MONTHS_TH[m]} {thaiYear(y)}
      </span>
      <button onClick={()=>onMonthMove(1)} style={mob?navArrow:navArrowLg}>›</button>
    </div>
  );

  const scopeEl = (
    <div style={{display:'inline-flex',background:'rgba(255,255,255,.10)',borderRadius:999,padding:3}}>
      {[['all','ทุกคน','👥'],['mine','ของฉัน','🙂'],['report','รายงาน','📊']].map(([v,l,ic])=>{
        const a = scope===v;
        return <button key={v} onClick={()=>onScope(v)} style={{
          border:'none',cursor:'pointer',fontFamily:'inherit',fontSize:mob?11.5:13,fontWeight:600,
          padding:mob?'5px 10px':'6px 15px',borderRadius:999,whiteSpace:'nowrap',
          background:a?'#fff':'transparent',color:a?'#2b2950':'#d9d5f3',
        }}>{ic} {l}</button>;
      })}
    </div>
  );

  const userEl = (
    <div style={{display:'flex',alignItems:'center',gap:mob?5:8}}>
      {isAdmin && <button onClick={onAdmin} title="แผงจัดการ" style={{...navArrow,background:'rgba(255,255,255,.12)',fontSize:15}}>⚙</button>}
      <div style={{position:'relative'}}>
        <button onClick={onBell} title="การแจ้งเตือน" style={{...navArrow,background:'rgba(255,255,255,.12)',fontSize:15}}>🔔</button>
        {badge>0 && <span style={{position:'absolute',top:-4,right:-4,width:17,height:17,borderRadius:'50%',
          background:'#e8745a',color:'#fff',fontSize:9,fontWeight:800,display:'flex',alignItems:'center',justifyContent:'center',
          pointerEvents:'none'}}>{badge}</span>}
      </div>
      {!mob && <div style={{display:'flex',alignItems:'center',gap:8,background:'rgba(255,255,255,.10)',borderRadius:999,padding:'4px 10px 4px 4px'}}>
        <span style={{width:28,height:28,borderRadius:'50%',background:'#fff',color:'#9a7616',
          display:'flex',alignItems:'center',justifyContent:'center',fontWeight:800,fontSize:13,fontFamily:'Anuphan'}}>
          {currentStaff ? currentStaff.nick.slice(0,1) : 'เ'}</span>
        <span style={{fontSize:13,fontWeight:500}}>{currentStaff ? currentStaff.nick : ''}</span>
      </div>}
      {mob && <span style={{width:28,height:28,borderRadius:'50%',background:'rgba(255,255,255,.18)',
        display:'flex',alignItems:'center',justifyContent:'center',fontWeight:800,fontSize:13,fontFamily:'Anuphan'}}>
        {currentStaff ? currentStaff.nick.slice(0,1) : 'เ'}</span>}
      <button onClick={onLogout} title="ออกจากระบบ" style={{...navArrow,background:'rgba(255,120,120,.18)',fontSize:14}}>⎋</button>
    </div>
  );

  if(mob) return (
    <header style={{background:headerBg||'linear-gradient(100deg,#7a5d12,#a8821c 52%,#caa531)',color:'#fff',padding:'10px 14px 9px'}}>
      <div style={{display:'flex',alignItems:'center',justifyContent:'space-between',marginBottom:8}}>
        {logoEl}
        {userEl}
      </div>
      <div style={{display:'flex',alignItems:'center',justifyContent:'space-between',gap:8}}>
        {monthNavEl}
        {scopeEl}
      </div>
    </header>
  );

  return (
    <header style={{
      background: headerBg || 'linear-gradient(100deg,#7a5d12,#a8821c 52%,#caa531)', color:'#fff',
      padding:'0 22px', height:62, display:'flex', alignItems:'center', gap:16,
    }}>
      {logoEl}
      <div style={{display:'flex',alignItems:'center',gap:8,background:'rgba(255,255,255,.12)',
        borderRadius:999,padding:'5px 8px',margin:'0 auto'}}>
        <button onClick={()=>onMonthMove(-1)} style={navArrowLg}>‹</button>
        <span style={{fontSize:18,fontWeight:700,minWidth:170,textAlign:'center',fontFamily:'Anuphan'}}>{MONTHS_TH[m]} {thaiYear(y)}</span>
        <button onClick={()=>onMonthMove(1)} style={navArrowLg}>›</button>
      </div>
      {scopeEl}
      {userEl}
    </header>
  );
}

const navArrow = {
  width:30, height:30, borderRadius:'50%', border:'none', cursor:'pointer',
  background:'rgba(255,255,255,.10)', color:'#fff', fontSize:18, lineHeight:1,
  display:'flex', alignItems:'center', justifyContent:'center', fontFamily:'inherit',
};
const navArrowLg = {
  width:38, height:38, borderRadius:'50%', border:'none', cursor:'pointer',
  background:'rgba(255,255,255,.16)', color:'#fff', fontSize:24, lineHeight:1,
  display:'flex', alignItems:'center', justifyContent:'center', fontFamily:'inherit',
};

Object.assign(window, { Avatar, NameChip, StatCard, Segmented, Legend, TopNav, useMobile });
