/* Manager screens: Dashboard, Management */

// ---------- mini charts ----------
function BarH({ data, color='#dc2626', unit='งาน', money }){
  const max = Math.max(1, ...data.map(d=>d.value));
  return (
    <div className="space-y-2.5">
      {data.map((d,i)=>(
        <div key={i} className="flex items-center gap-3">
          <div className="w-24 shrink-0 text-[12px] font-light text-slate-500 truncate text-right">{d.label}</div>
          <div className="flex-1 h-5 rounded-md bg-slate-100 overflow-hidden">
            <div className="h-full rounded-md flex items-center justify-end pr-1.5 transition-all" style={{width:Math.max(8,d.value/max*100)+'%', background:d.color||color}}>
              <span className="text-[11px] font-medium text-white tnum">{d.value}</span>
            </div>
          </div>
        </div>
      ))}
    </div>
  );
}

function Donut({ data, size=140 }){
  const total = data.reduce((s,d)=>s+d.value,0) || 1;
  let acc = 0;
  const stops = data.map(d=>{ const start=acc/total*360; acc+=d.value; const end=acc/total*360; return `${d.color} ${start}deg ${end}deg`; }).join(',');
  return (
    <div className="flex items-center gap-4">
      <div className="rounded-full shrink-0 grid place-items-center" style={{width:size,height:size,background:`conic-gradient(${stops})`}}>
        <div className="rounded-full bg-white grid place-items-center" style={{width:size*0.62,height:size*0.62}}>
          <div className="text-center"><div className="text-[22px] font-medium text-slate-800 tnum leading-none">{total}</div><div className="text-[10px] font-light text-slate-400">งาน</div></div>
        </div>
      </div>
      <div className="space-y-1.5">
        {data.filter(d=>d.value>0).map((d,i)=>(
          <div key={i} className="flex items-center gap-2 text-[12px]">
            <span className="w-2.5 h-2.5 rounded-sm" style={{background:d.color}}/>
            <span className="font-light text-slate-500">{d.label}</span>
            <span className="font-medium text-slate-700 tnum ml-auto">{d.value}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

function ChartCard({ icon, title, children, className='' }){
  return (
    <Card className={`p-4 ${className}`}>
      <div className="flex items-center gap-2 mb-4"><Icon name={icon} size={16} className="text-brand-600"/><h3 className="text-[14px] font-medium text-slate-700">{title}</h3></div>
      {children}
    </Card>
  );
}

function DashboardScreen(){
  const { jobs, tweaks, navigate, device } = useCK();
  const isMobile = device==='mobile';
  const today = CK.TODAY, tomo = CK.addDays(CK.TODAY,1);
  const month = CK.TODAY.slice(0,7);
  const inMonth = jobs.filter(j=>j.date.slice(0,7)===month);
  const cnt = s => jobs.filter(j=>j.status===s).length;
  const todayJobs = jobs.filter(j=>j.date===today);

  const stats = [
    {icon:'CalendarDays', label:'งานวันนี้', value:todayJobs.length, tone:'red', sub:CK.thDate(today)},
    {icon:'CalendarPlus', label:'งานพรุ่งนี้', value:jobs.filter(j=>j.date===tomo).length, tone:'slate'},
    {icon:'CalendarRange', label:'งานเดือนนี้', value:inMonth.length, tone:'blue'},
    {icon:'Clock', label:'รอติดตั้ง', value:jobs.filter(j=>['confirmed','preparing','ready','assigned'].includes(j.status)).length, tone:'amber'},
    {icon:'CircleCheck', label:'เสร็จแล้ว', value:cnt('completed'), tone:'green'},
    {icon:'TriangleAlert', label:'ติดปัญหา', value:cnt('issue'), tone:'red'},
    {icon:'CalendarClock', label:'เลื่อนนัด', value:cnt('postponed'), tone:'amber'},
    {icon:'CalendarX', label:'วันคิวเต็ม (เดือนนี้)', value:Object.keys(CK.CAPACITY).filter(d=>d.slice(0,7)===month && computeDayStatus(jobs,d).status==='full').length, tone:'red'},
  ];

  const byBranch = CK.BRANCHES.map(b=>({label:b.code, value:jobs.filter(j=>j.branch===b.id).length, color:'#dc2626'}));
  const byType = CK.JOB_TYPES.map(t=>({label:t.th, value:jobs.filter(j=>j.jobType===t.id).length})).filter(d=>d.value>0).sort((a,b)=>b.value-a.value);
  const byDistrict = CK.DISTRICTS.map(d=>({label:'อ.'+d, value:jobs.filter(j=>j.district===d).length})).filter(d=>d.value>0).sort((a,b)=>b.value-a.value);
  const statusData = Object.values(CK.STATUS).map(s=>({label:s.th, value:cnt(s.key), color:s.dot})).filter(d=>d.value>0);
  const teamLoad = CK.TEAMS.map(t=>({label:t.name.split('—')[0].trim(), value:Math.round(jobs.filter(j=>j.team===t.id&&j.date===today).reduce((s,j)=>s+CK.jobUnits(j),0)*10)/10, color:t.color}));
  const next7 = Array.from({length:7},(_,i)=>{ const d=CK.addDays(today,i); return {label:CK.thDate(d), value:jobs.filter(j=>j.date===d).length, color:i===0?'#dc2626':'#fca5a5'}; });

  const chartsMode = tweaks.dashboardStyle==='charts';

  return (
    <div className={isMobile?'p-3':'p-6 max-w-[1200px] mx-auto'}>
      {isMobile ? <h1 className="text-[18px] font-medium text-slate-900 mb-3">ภาพรวมผู้บริหาร</h1>
        : <PageHeader icon="LayoutDashboard" title="Dashboard ภาพรวม" sub="ข้อมูลทุกสาขาแบบ real-time" >
            <span className="inline-flex items-center gap-1.5 text-[12px] font-light text-green-600 bg-green-50 ring-1 ring-green-200 rounded-full px-3 py-1.5"><span className="w-2 h-2 rounded-full bg-green-500 animate-pulse"/>เชื่อมต่อ real-time</span>
          </PageHeader>}

      <div className={`grid gap-3 mb-4 ${isMobile?'grid-cols-2':'grid-cols-2 md:grid-cols-4'}`}>
        {stats.map((s,i)=><StatCard key={i} {...s} onClick={s.label==='งานวันนี้'?()=>navigate('queue',{date:today}):undefined}/>)}
      </div>

      {chartsMode ? (
        <div className={`grid gap-3 ${isMobile?'grid-cols-1':'grid-cols-1 lg:grid-cols-3'}`}>
          <ChartCard icon="ChartColumn" title="งานแยกตามวัน (7 วัน)" className={isMobile?'':'lg:col-span-2'}><BarH data={next7}/></ChartCard>
          <ChartCard icon="ChartPie" title="สัดส่วนสถานะงาน"><Donut data={statusData}/></ChartCard>
          <ChartCard icon="Store" title="งานแยกตามสาขา"><BarH data={byBranch}/></ChartCard>
          <ChartCard icon="Wrench" title="งานแยกตามประเภทงาน"><BarH data={byType} color="#0f172a"/></ChartCard>
          <ChartCard icon="Truck" title="โหลดทีมช่างวันนี้ (unit)"><BarH data={teamLoad} unit="unit"/></ChartCard>
          <ChartCard icon="MapPin" title="งานแยกตามอำเภอ" className={isMobile?'':'lg:col-span-3'}><BarH data={byDistrict} color="#ea580c"/></ChartCard>
        </div>
      ) : (
        <div className={`grid gap-3 ${isMobile?'grid-cols-1':'grid-cols-1 lg:grid-cols-2'}`}>
          <ChartCard icon="ChartPie" title="สัดส่วนสถานะงาน"><Donut data={statusData} size={150}/></ChartCard>
          <ChartCard icon="Store" title="งานแยกตามสาขา"><BarH data={byBranch}/></ChartCard>
          <Card className={`p-4 ${isMobile?'':'lg:col-span-2'}`}>
            <div className="flex items-center gap-2 mb-3"><Icon name="ListTree" size={16} className="text-brand-600"/><h3 className="text-[14px] font-medium text-slate-700">สรุปงานวันนี้</h3></div>
            <SummaryBar jobs={todayJobs}/>
          </Card>
        </div>
      )}
    </div>
  );
}

// ================= Management =================
function ManageScreen(){
  const { toast, device } = useCK();
  const isMobile = device==='mobile';
  const [tab,setTab] = React.useState('branches');
  const [cap,setCap] = React.useState(()=>JSON.parse(JSON.stringify(CK.CAPACITY)));
  const tabs = [['branches','สาขา','Building2'],['users','ผู้ใช้','Users'],['jobtypes','ประเภทงาน','Wrench'],['capacity','ความจุคิว','GaugeCircle']];
  const th = 'text-left text-[12px] font-medium text-slate-500 px-3 py-2.5';
  const td = 'px-3 py-3 text-[13px] text-slate-700 border-t border-slate-100';

  return (
    <div className={isMobile?'p-3':'p-6 max-w-[1100px] mx-auto'}>
      {isMobile ? <h1 className="text-[18px] font-medium text-slate-900 mb-3">จัดการระบบ</h1>
        : <PageHeader icon="Settings" title="จัดการระบบ" sub="ตั้งค่าสาขา ผู้ใช้ ประเภทงาน และความจุคิว" />}
      <div className="flex items-center gap-1 mb-4 bg-white rounded-xl ring-1 ring-slate-200 p-1 w-full sm:w-fit overflow-x-auto no-scrollbar">
        {tabs.map(([k,l,ic])=>(
          <button key={k} onClick={()=>setTab(k)} className={`inline-flex items-center gap-1.5 px-3.5 py-2 rounded-lg text-[13px] whitespace-nowrap transition ${tab===k?'bg-brand-600 text-white':'text-slate-600 hover:bg-slate-50'}`}>
            <Icon name={ic} size={15}/>{l}
          </button>
        ))}
      </div>

      {tab==='branches' && (
        <Card className="overflow-hidden">
          <div className="flex items-center justify-between p-3 border-b border-slate-100">
            <span className="text-[14px] font-medium text-slate-700">สาขาทั้งหมด ({CK.BRANCHES.length})</span>
            <Btn size="sm" icon="Plus" onClick={()=>toast('เปิดฟอร์มเพิ่มสาขา')}>เพิ่มสาขา</Btn>
          </div>
          <div className="overflow-x-auto">
          <table className="w-full min-w-[640px]">
            <thead className="bg-slate-50"><tr><th className={th}>รหัส</th><th className={th}>ชื่อสาขา</th><th className={th}>เบอร์โทร</th><th className={th}>ที่อยู่</th><th className={th}>สถานะ</th><th className={th}></th></tr></thead>
            <tbody>{CK.BRANCHES.map(b=>(
              <tr key={b.id}>
                <td className={td}><span className="font-medium">{b.code}</span></td>
                <td className={td}>{b.name}</td>
                <td className={td+' font-light text-slate-500'}>{b.phone}</td>
                <td className={td+' font-light text-slate-500 max-w-[260px] truncate'}>{b.addr}</td>
                <td className={td}>{b.active?<span className="inline-flex items-center gap-1 text-[12px] text-green-700 bg-green-50 ring-1 ring-green-200 rounded-full px-2 py-0.5"><span className="w-1.5 h-1.5 rounded-full bg-green-500"/>เปิดใช้งาน</span>:<span className="text-[12px] text-slate-400 bg-slate-100 rounded-full px-2 py-0.5">ปิด</span>}</td>
                <td className={td}><button className="text-slate-400 hover:text-brand-600"><Icon name="Pencil" size={15}/></button></td>
              </tr>
            ))}</tbody>
          </table>
          </div>
        </Card>
      )}

      {tab==='users' && (
        <Card className="overflow-hidden">
          <div className="flex items-center justify-between p-3 border-b border-slate-100">
            <span className="text-[14px] font-medium text-slate-700">ผู้ใช้งาน ({CK.USERS.length})</span>
            <Btn size="sm" icon="UserPlus" onClick={()=>toast('เปิดฟอร์มเพิ่มผู้ใช้')}>เพิ่มผู้ใช้</Btn>
          </div>
          <div className="overflow-x-auto">
          <table className="w-full min-w-[640px]">
            <thead className="bg-slate-50"><tr><th className={th}>ชื่อ</th><th className={th}>สิทธิ์</th><th className={th}>สาขา</th><th className={th}>เบอร์โทร</th><th className={th}>สถานะ</th><th className={th}></th></tr></thead>
            <tbody>{CK.USERS.map(u=>{ const b=CK.branch(u.branch);
              return (
              <tr key={u.id}>
                <td className={td}><div className="flex items-center gap-2"><Avatar name={u.name} color="#0f172a" size={28}/>{u.name}</div></td>
                <td className={td+' font-light'}>{CK.ROLES[u.role].label}</td>
                <td className={td+' font-light text-slate-500'}>{b?b.code:'—'}</td>
                <td className={td+' font-light text-slate-500'}>{u.phone}</td>
                <td className={td}>{u.active?<span className="text-[12px] text-green-700 bg-green-50 ring-1 ring-green-200 rounded-full px-2 py-0.5">active</span>:<span className="text-[12px] text-slate-400 bg-slate-100 rounded-full px-2 py-0.5">inactive</span>}</td>
                <td className={td}><button className="text-slate-400 hover:text-brand-600"><Icon name="Pencil" size={15}/></button></td>
              </tr>);
            })}</tbody>
          </table>
          </div>
        </Card>
      )}

      {tab==='jobtypes' && (
        <div className={`grid gap-3 ${isMobile?'grid-cols-1':'sm:grid-cols-2 lg:grid-cols-3'}`}>
          {CK.JOB_TYPES.map(t=>(
            <Card key={t.id} className="p-4 flex items-center gap-3">
              <span className="grid place-items-center w-11 h-11 rounded-xl bg-brand-50 text-brand-600"><Icon name={t.icon} size={20}/></span>
              <div className="flex-1"><div className="text-[15px] font-medium text-slate-800">{t.th}</div><div className="text-[12px] font-light text-slate-400">น้ำหนักคิว {t.unit} unit/ชิ้น</div></div>
              <button className="text-slate-300 hover:text-brand-600"><Icon name="Pencil" size={16}/></button>
            </Card>
          ))}
          <Card as="button" onClick={()=>toast('เพิ่มประเภทงาน')} className="p-4 flex items-center justify-center gap-2 text-slate-400 hover:text-brand-600 hover:ring-brand-300 ring-dashed"><Icon name="Plus" size={18}/>เพิ่มประเภทงาน</Card>
        </div>
      )}

      {tab==='capacity' && (
        <Card className="p-4">
          <div className="flex items-center gap-2 mb-3"><Icon name="GaugeCircle" size={16} className="text-brand-600"/><h3 className="text-[14px] font-medium text-slate-700">ตั้งค่าความจุงานรายวัน</h3></div>
          <div className="text-[12px] font-light text-slate-500 mb-4 bg-slate-50 rounded-xl p-3">
            น้ำหนักงาน: ติดตั้งแอร์ = 1 unit · แอร์ 4 ทิศทาง = 2 unit · ล้างแอร์ = 0.5 unit · ถอดแอร์ = 0.5 unit · งานต่างอำเภอไกล +0.5 unit
          </div>
          <div className="space-y-2 max-h-[55vh] overflow-auto">
            {Object.keys(cap).filter(d=>d>=CK.TODAY).slice(0,14).map(d=>{
              const c = cap[d];
              return (
                <div key={d} className="flex flex-wrap items-center gap-3 rounded-xl ring-1 ring-slate-200 p-2.5">
                  <div className="w-32 text-[13px] text-slate-700">{CK.thDate(d,{withDow:true})}</div>
                  <div className="flex items-center gap-2">
                    <span className="text-[12px] font-light text-slate-500">รับสูงสุด</span>
                    <div className="flex items-center rounded-lg ring-1 ring-slate-300">
                      <button onClick={()=>setCap(p=>({...p,[d]:{...c,max:Math.max(1,c.max-1)}}))} className="w-8 h-8 grid place-items-center text-slate-500"><Icon name="Minus" size={14}/></button>
                      <span className="w-9 text-center text-[14px] font-medium tnum">{c.max}</span>
                      <button onClick={()=>setCap(p=>({...p,[d]:{...c,max:c.max+1}}))} className="w-8 h-8 grid place-items-center text-slate-500"><Icon name="Plus" size={14}/></button>
                    </div>
                    <span className="text-[12px] font-light text-slate-400">unit</span>
                  </div>
                  <button onClick={()=>setCap(p=>({...p,[d]:{...c,closed:!c.closed}}))} className={`ml-auto inline-flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-[12px] ring-1 transition ${c.closed?'bg-slate-200 text-slate-600 ring-slate-300':'bg-green-50 text-green-700 ring-green-200'}`}>
                    <Icon name={c.closed?'CircleSlash':'CircleCheck'} size={14}/>{c.closed?'งดรับงาน':'เปิดรับงาน'}
                  </button>
                </div>
              );
            })}
          </div>
          <div className="flex justify-end mt-3"><Btn icon="Save" onClick={()=>{ Object.assign(CK.CAPACITY,cap); toast('บันทึกความจุคิวแล้ว','success'); }}>บันทึก</Btn></div>
        </Card>
      )}
    </div>
  );
}

Object.assign(window, { DashboardScreen, ManageScreen, BarH, Donut });
