/* Operations screens: DailyQueue, Calendar, AddJob */

// ============ shared date stepper ============
function DateStepper({ date, onChange, compact }){
  return (
    <div className="flex items-center gap-1">
      <button onClick={()=>onChange(CK.addDays(date,-1))} className="grid place-items-center w-9 h-9 rounded-xl ring-1 ring-slate-300 bg-white hover:bg-slate-50 text-slate-600"><Icon name="ChevronLeft" size={18}/></button>
      <div className={`text-center ${compact?'px-2':'px-3'}`}>
        <div className="text-[15px] font-medium text-slate-800 whitespace-nowrap">{CK.thDate(date,{withDow:true})}</div>
        {!compact && <div className="text-[11px] font-light text-slate-400">{date===CK.TODAY?'วันนี้':''}</div>}
      </div>
      <button onClick={()=>onChange(CK.addDays(date,1))} className="grid place-items-center w-9 h-9 rounded-xl ring-1 ring-slate-300 bg-white hover:bg-slate-50 text-slate-600"><Icon name="ChevronRight" size={18}/></button>
    </div>
  );
}

// ============ capacity bar ============
function CapacityBar({ ds }){
  const d = CK.DAYSTATUS[ds.status];
  return (
    <div className="flex items-center gap-3">
      <DayStatusBadge status={ds.status} size="md" />
      <div className="flex-1 min-w-[120px]">
        <div className="h-2.5 rounded-full bg-slate-200 overflow-hidden">
          <div className="h-full rounded-full transition-all" style={{ width: ds.pct+'%', background: d.bar }} />
        </div>
      </div>
      <div className="text-[13px] font-light text-slate-500 whitespace-nowrap">
        <b className="font-medium text-slate-800 tnum">{ds.used}</b> / {ds.max} unit
      </div>
    </div>
  );
}

function sortQueue(jobs){
  const slotRank = s => ['คิวแรก (09.00)','ช่วงเช้า','ช่วงบ่าย','สะดวกทั้งวัน'].indexOf(s);
  return [...jobs].sort((a,b)=>{
    if (a.urgency!==b.urgency) return a.urgency==='urgent'?-1:1;
    return slotRank(a.slot)-slotRank(b.slot);
  });
}

// ============ Daily Queue ============
function DailyQueueScreen(){
  const { jobs, device, tweaks, nav, navigate } = useCK();
  const [date,setDate] = React.useState(nav.date || CK.TODAY);
  const [filters,setFilters] = React.useState({});
  const [openId,setOpenId] = React.useState(null);
  const [view,setView] = React.useState('day'); // day | week
  React.useEffect(()=>{ if(nav.date){ setDate(nav.date); setView('day'); } }, [nav.date]);

  const ds = computeDayStatus(jobs, date);
  const dayJobs = sortQueue(applyFilters(jobs.filter(j=>j.date===date), filters));
  const isMobile = device==='mobile';
  const useTable = tweaks.queueLayout==='table' && !isMobile;
  const isWeek = view==='week';

  const ViewToggle = () => (
    <div className="flex items-center rounded-xl ring-1 ring-slate-300 bg-white p-0.5">
      {[['day','รายวัน','CalendarDays'],['week','สัปดาห์','Columns3']].map(([k,l,ic])=>(
        <button key={k} onClick={()=>setView(k)} className={`inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-[13px] transition ${view===k?'bg-brand-600 text-white':'text-slate-600 hover:bg-slate-50'}`}>
          <Icon name={ic} size={15}/>{l}
        </button>
      ))}
    </div>
  );

  return (
    <div className={isMobile ? 'p-3 pb-4' : 'p-6 max-w-[1280px] mx-auto'}>
      {isMobile ? (
        <div className="mb-3">
          <div className="flex items-center justify-between mb-2">
            <h1 className="text-[18px] font-medium text-slate-900">คิวรายวัน</h1>
            <ViewToggle />
          </div>
          {!isWeek && <Card className="p-3 mb-3"><DateStepper date={date} onChange={setDate} compact /></Card>}
          {!isWeek && <Card className="p-3"><CapacityBar ds={ds} /></Card>}
        </div>
      ) : (
        <PageHeader icon="ClipboardList" title={isWeek?'กระดานคิวสัปดาห์':'ตารางคิวรายวัน'} sub={isWeek?'ภาพรวมความจุคิว 7 วัน · ทุกสาขา':'งานรวมทุกสาขา · อัปเดต real-time'}>
          <ViewToggle />
          {!isWeek && <DateStepper date={date} onChange={setDate} />}
        </PageHeader>
      )}

      {!isMobile && !isWeek && (
        <Card className="p-4 mb-4 flex flex-wrap items-center justify-between gap-4">
          <div className="flex-1 min-w-[260px]"><CapacityBar ds={ds} /></div>
          <div className="flex items-center gap-2 text-[12px] font-light text-slate-500">
            <span className="inline-flex items-center gap-1"><span className="w-2 h-2 rounded-full bg-brand-600"/>แอร์ {ds.air} ชุด</span>
            <span className="text-slate-300">·</span>
            <span>งานบริการ {ds.service} งาน</span>
          </div>
        </Card>
      )}

      <div className="mb-3">
        <FilterBar value={filters} onChange={setFilters} show={isMobile?['q','district','jobType']:['q','branch','district','jobType','status','team']} />
      </div>

      {isWeek ? (
        <WeekBoard jobs={jobs} filters={filters} isMobile={isMobile}
          onOpenJob={(id)=>setOpenId(id)}
          onOpenDay={(d)=>{ setDate(d); setView('day'); }} />
      ) : (
      <>
      {ds.status==='full' && (
        <div className="mb-3 flex items-start gap-2 rounded-xl bg-brand-50 ring-1 ring-brand-200 p-3 text-[13px] text-brand-700 font-light">
          <Icon name="TriangleAlert" size={16} className="mt-0.5 shrink-0"/> คิววันนี้เต็มแล้ว ({ds.used}/{ds.max} unit) — การรับงานเพิ่มต้องให้สำนักงานใหญ่อนุมัติ
        </div>
      )}

      {dayJobs.length===0 ? (
        <Card className="py-2"><Empty icon="CalendarOff" title="ไม่มีงานในวันนี้" sub="ลองเปลี่ยนวันหรือล้างตัวกรอง" /></Card>
      ) : useTable ? (
        <Card className="overflow-hidden">
          <table className="w-full">
            <thead className="bg-slate-50 border-b border-slate-200">
              <tr className="text-[12px] font-medium text-slate-500 text-left">
                <th className="px-3 py-2.5 text-center w-10">#</th><th className="px-3 py-2.5">ลูกค้า</th>
                <th className="px-3 py-2.5">อำเภอ</th><th className="px-3 py-2.5">สาขา</th>
                <th className="px-3 py-2.5">ประเภท</th><th className="px-3 py-2.5">สินค้า</th>
                <th className="px-3 py-2.5">ช่วงเวลา</th><th className="px-3 py-2.5">สถานะ</th><th className="px-3 py-2.5">ทีมช่าง</th>
              </tr>
            </thead>
            <tbody>{dayJobs.map((j,i)=><JobRow key={j.id} job={j} seq={i+1} onOpen={()=>setOpenId(j.id)} />)}</tbody>
          </table>
        </Card>
      ) : (
        <div className={`grid gap-3 ${isMobile?'grid-cols-1':'sm:grid-cols-2 lg:grid-cols-3'}`}>
          {dayJobs.map((j,i)=><JobCard key={j.id} job={j} seq={i+1} onOpen={()=>setOpenId(j.id)} />)}
        </div>
      )}

      {/* sticky summary */}
      <Card className="mt-4 p-3.5 sticky bottom-3">
        <div className="flex items-center gap-2 mb-2">
          <Icon name="Sigma" size={15} className="text-brand-600"/>
          <span className="text-[13px] font-medium text-slate-700">สรุปงานวันนี้ (อัตโนมัติ)</span>
        </div>
        <SummaryBar jobs={dayJobs} />
      </Card>
      </>
      )}

      {openId && <JobDetailModal jobId={openId} onClose={()=>setOpenId(null)} />}
    </div>
  );
}

// ============ Calendar ============
function CalendarScreen(){
  const { jobs, device, tweaks, navigate } = useCK();
  const base = new Date(CK.TODAY+'T00:00:00');
  const [ym,setYm] = React.useState({ y:base.getFullYear(), m:base.getMonth() });
  const isMobile = device==='mobile';
  const style = tweaks.calendarStyle;

  const first = new Date(ym.y, ym.m, 1);
  const startPad = first.getDay();
  const daysIn = new Date(ym.y, ym.m+1, 0).getDate();
  const cells = [];
  for (let i=0;i<startPad;i++) cells.push(null);
  for (let d=1;d<=daysIn;d++) cells.push(CK.iso(new Date(ym.y, ym.m, d)));

  const maxCount = Math.max(1, ...cells.filter(Boolean).map(d=>computeDayStatus(jobs,d).count));
  function step(n){ let m=ym.m+n, y=ym.y; if(m<0){m=11;y--;} if(m>11){m=0;y++;} setYm({y,m}); }

  const heat = (pct)=>`rgba(220,38,38,${0.08 + pct/100*0.55})`;

  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="CalendarDays" title="ปฏิทินคิวรายเดือน" sub="ดูปริมาณงานและสถานะคิวแต่ละวัน" />}

      <Card className={isMobile?'p-3':'p-5'}>
        <div className="flex items-center justify-between mb-4">
          <button onClick={()=>step(-1)} className="grid place-items-center w-9 h-9 rounded-xl ring-1 ring-slate-300 hover:bg-slate-50 text-slate-600"><Icon name="ChevronLeft" size={18}/></button>
          <div className="text-[17px] font-medium text-slate-800">{CK.TH_MON_FULL[ym.m]} {ym.y+543}</div>
          <button onClick={()=>step(1)} className="grid place-items-center w-9 h-9 rounded-xl ring-1 ring-slate-300 hover:bg-slate-50 text-slate-600"><Icon name="ChevronRight" size={18}/></button>
        </div>

        <div className="grid grid-cols-7 gap-1 mb-1">
          {['อา','จ','อ','พ','พฤ','ศ','ส'].map((d,i)=>(
            <div key={i} className={`text-center text-[12px] font-medium py-1 ${i===0?'text-brand-600':'text-slate-400'}`}>{d}</div>
          ))}
        </div>

        <div className="grid grid-cols-7 gap-1">
          {cells.map((d,i)=>{
            if(!d) return <div key={i} />;
            const day = new Date(d+'T00:00:00').getDate();
            const ds = computeDayStatus(jobs,d);
            const isToday = d===CK.TODAY;
            const empty = ds.count===0 && !ds.closed;
            const sc = CK.DAYSTATUS[ds.status];

            const bg = style==='heat' && !empty ? heat(ds.pct) : undefined;
            return (
              <button key={i} onClick={()=>navigate('queue',{date:d})}
                className={`relative rounded-xl ring-1 transition text-left flex flex-col ${isMobile?'p-1.5 min-h-[60px]':'p-2 min-h-[84px]'} ${isToday?'ring-brand-500 ring-2':'ring-slate-200'} hover:ring-brand-300 ${empty?'bg-slate-50/50':'bg-white'}`}
                style={bg?{background:bg, borderColor:'transparent'}:undefined}>
                <div className="flex items-center justify-between">
                  <span className={`text-[13px] tnum ${isToday?'font-medium text-brand-700':'text-slate-600'} ${style==='heat'&&!empty&&ds.pct>60?'text-white':''}`}>{day}</span>
                  {!empty && style==='dot' && <span className="w-2 h-2 rounded-full" style={{background:sc.bar}}/>}
                </div>

                {!empty && (
                  <div className="mt-auto">
                    {style==='badge' && (
                      <>
                        <div className={`text-[10px] leading-tight ${isMobile?'':'mb-1'}`}>
                          <span className="font-medium text-slate-700">{ds.count}</span>
                          <span className="font-light text-slate-400"> งาน · </span>
                          <span className="font-light text-brand-600">แอร์ {ds.air}</span>
                        </div>
                        {!isMobile && <span className={`inline-block text-[9px] px-1.5 py-0.5 rounded-md ring-1 ${sc.cls}`}>{sc.th}</span>}
                      </>
                    )}
                    {style==='dot' && (
                      <div className="text-[10px] font-light text-slate-500">{ds.count} งาน</div>
                    )}
                    {style==='heat' && (
                      <div className={`text-[10px] ${ds.pct>60?'text-white':'text-slate-600'}`}>{ds.count} งาน</div>
                    )}
                  </div>
                )}
                {ds.closed && <span className="absolute inset-x-1 bottom-1 text-[9px] text-center text-slate-400">งดรับงาน</span>}
              </button>
            );
          })}
        </div>

        {/* legend */}
        <div className="flex flex-wrap items-center gap-3 mt-4 pt-3 border-t border-slate-100">
          {Object.values(CK.DAYSTATUS).map(s=>(
            <span key={s.key} className="inline-flex items-center gap-1.5 text-[12px] font-light text-slate-500">
              <span className="w-3 h-3 rounded-full" style={{background:s.bar}}/>{s.th}
            </span>
          ))}
        </div>
      </Card>
    </div>
  );
}

Object.assign(window, { DailyQueueScreen, CalendarScreen, DateStepper, CapacityBar, sortQueue });
