/* HQ screens: CoverSheet, Assignment */

// ================= Cover Sheet =================
function groupJobs(jobs, by){
  if (by==='none') return [{ key:'all', label:'รายการทั้งหมด', jobs }];
  const m = new Map();
  jobs.forEach(j=>{
    let key, label;
    if (by==='branch'){ const b=CK.branch(j.branch); key=j.branch; label=`${b?.code} ${b?.name}`; }
    else if (by==='district'){ key=j.district; label=`อ.${j.district}`; }
    else { const t=CK.team(j.team); key=j.team||'none'; label=t?t.name:'ยังไม่มอบหมายช่าง'; }
    if(!m.has(key)) m.set(key,{key,label,jobs:[]});
    m.get(key).jobs.push(j);
  });
  return [...m.values()];
}

function CoverSheetScreen(){
  const { jobs, toast, device } = useCK();
  const isMobile = device==='mobile';
  const [date,setDate] = React.useState(CK.TODAY);
  const [by,setBy] = React.useState('district');
  const dayJobs = sortQueue(jobs.filter(j=>j.date===date && j.status!=='cancelled'));
  const groups = groupJobs(dayJobs, by);
  const s = computeSummary(dayJobs);

  const byOpts = [['district','อำเภอ'],['branch','สาขา'],['team','ทีมช่าง'],['none','ไม่จัดกลุ่ม']];

  return (
    <div className={isMobile?'p-3':'p-6 max-w-[1000px] mx-auto'}>
      <div className="no-print">
        {isMobile ? <h1 className="text-[18px] font-medium text-slate-900 mb-2">ใบปะหน้ารายวัน</h1> :
        <PageHeader icon="FileText" title="ใบปะหน้ารายวัน" sub="สร้างจากคิวงานอัตโนมัติ — ไม่ต้องลอกข้อมูลซ้ำ">
          <Btn variant="outline" size="sm" icon="FileSpreadsheet" onClick={()=>toast('กำลังส่งออก Excel (.xlsx)','success')}>Excel</Btn>
          <Btn variant="outline" size="sm" icon="FileDown" onClick={()=>toast('กำลังส่งออก PDF','success')}>PDF</Btn>
          <Btn variant="primary" size="sm" icon="Printer" onClick={()=>window.print()}>พิมพ์</Btn>
        </PageHeader>}

        <Card className="p-3 mb-4 flex flex-wrap items-center justify-between gap-3">
          <DateStepper date={date} onChange={setDate} />
          <div className="flex items-center gap-2">
            <span className="text-[13px] font-light text-slate-500">จัดกลุ่มตาม</span>
            <div className="flex items-center rounded-xl ring-1 ring-slate-300 bg-white p-0.5">
              {byOpts.map(([k,l])=>(
                <button key={k} onClick={()=>setBy(k)} className={`px-3 py-1.5 rounded-lg text-[13px] transition ${by===k?'bg-brand-600 text-white':'text-slate-600 hover:bg-slate-50'}`}>{l}</button>
              ))}
            </div>
          </div>
        </Card>
      </div>

      {/* PRINT AREA */}
      <div id="print-area" className={`bg-white rounded-2xl ring-1 ring-slate-200 shadow-card ${isMobile?'p-4':'p-7'} print:shadow-none print:ring-0`}>
        <div className="flex items-start justify-between border-b-2 border-slate-800 pb-3 mb-4">
          <div>
            <div className="text-[20px] font-medium text-slate-900">ใบปะหน้างานติดตั้ง / บริการ</div>
            <div className="text-[13px] font-light text-slate-500">บริษัท เจริญกิจ อิเล็คทริค จำกัด · เครื่องใช้ไฟฟ้าและงานบริการ</div>
          </div>
          <div className="text-right">
            <div className="text-[15px] font-medium text-slate-800">{CK.thDate(date,{withDow:true,full:true})}</div>
            <div className="text-[12px] font-light text-slate-400">จัดกลุ่มตาม{byOpts.find(o=>o[0]===by)[1]} · {dayJobs.length} งาน</div>
          </div>
        </div>

        {groups.map(g=>(
          <div key={g.key} className="mb-5 break-inside-avoid">
            <div className="flex items-center gap-2 mb-1.5">
              <span className="text-[14px] font-medium text-brand-700">{g.label}</span>
              <span className="text-[12px] font-light text-slate-400">({g.jobs.length} งาน)</span>
            </div>
            <div className="overflow-x-auto">
            <table className="w-full min-w-[680px] text-[12px] border-collapse">
              <thead>
                <tr className="bg-slate-100 text-slate-600 text-left">
                  <th className="border border-slate-300 px-2 py-1.5 w-8 text-center">#</th>
                  <th className="border border-slate-300 px-2 py-1.5">ลูกค้า / เบอร์โทร</th>
                  <th className="border border-slate-300 px-2 py-1.5">ที่อยู่ / อำเภอ</th>
                  <th className="border border-slate-300 px-2 py-1.5 w-12 text-center">สาขา</th>
                  <th className="border border-slate-300 px-2 py-1.5">สินค้า / รุ่น / BTU</th>
                  <th className="border border-slate-300 px-2 py-1.5 w-10 text-center">จำนวน</th>
                  <th className="border border-slate-300 px-2 py-1.5">หมายเหตุ</th>
                  <th className="border border-slate-300 px-2 py-1.5 w-24">ทีมช่าง</th>
                  <th className="border border-slate-300 px-2 py-1.5 w-14 text-center">จัดของ</th>
                </tr>
              </thead>
              <tbody>
                {g.jobs.map((j,i)=>{ const b=CK.branch(j.branch); const t=CK.team(j.team); const jt=CK.jobType(j.jobType);
                  const qty = j.items.reduce((a,it)=>a+(it.qty||1),0);
                  return (
                    <tr key={j.id} className="align-top">
                      <td className="border border-slate-300 px-2 py-1.5 text-center tnum">{i+1}</td>
                      <td className="border border-slate-300 px-2 py-1.5"><div className="font-normal text-slate-800">{j.customer}</div><div className="text-slate-400">{j.phone}</div></td>
                      <td className="border border-slate-300 px-2 py-1.5 font-light">อ.{j.district}</td>
                      <td className="border border-slate-300 px-2 py-1.5 text-center">{b?.code}</td>
                      <td className="border border-slate-300 px-2 py-1.5 font-light">{jt?.th} · {j.items.map(it=>`${CK.product(it.p)?.th}${it.btu?' '+it.btu:''}${it.model?' '+it.model:''}`).join(', ')}</td>
                      <td className="border border-slate-300 px-2 py-1.5 text-center tnum">{qty}</td>
                      <td className="border border-slate-300 px-2 py-1.5 font-light text-slate-500">{[j.routeNote,j.urgency==='urgent'?'⚡ด่วน':''].filter(Boolean).join(' · ')}</td>
                      <td className="border border-slate-300 px-2 py-1.5 font-light">{t?t.name.split('—')[0].trim():'—'}</td>
                      <td className="border border-slate-300 px-2 py-1.5 text-center">{j.prepared?'☑':'☐'}</td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
            </div>
          </div>
        ))}

        <div className="border-t-2 border-slate-800 pt-3 mt-4 flex flex-wrap items-center gap-x-6 gap-y-1 text-[13px]">
          <span className="font-medium text-slate-800">สรุป:</span>
          {s.lines.map((l,i)=><span key={i} className="font-light text-slate-600">{l.label} <b className="font-medium text-slate-800">{l.qty}</b> {l.unit}</span>)}
          <span className="ml-auto font-medium text-slate-900">รวม {s.totalJobs} งาน</span>
        </div>
        <div className="flex justify-between mt-8 text-[12px] text-slate-500 font-light">
          <div>ผู้จัดคิว ......................................</div>
          <div>ผู้ตรวจสอบ ......................................</div>
          <div>ผู้รับสินค้า ......................................</div>
        </div>
      </div>
    </div>
  );
}

// ================= Assignment =================
function TeamColumn({ team, jobs, onDrop, onUnassign, dragMethod }){
  const [over,setOver] = React.useState(false);
  const load = Math.round(jobs.reduce((s,j)=>s+CK.jobUnits(j),0)*10)/10;
  const pct = Math.min(100, Math.round(load/team.capacity*100));
  const stat = pct>=100?'full':pct>=80?'almost':'open';
  const sc = CK.DAYSTATUS[stat];
  return (
    <div
      onDragOver={dragMethod?e=>{e.preventDefault();setOver(true);}:undefined}
      onDragLeave={dragMethod?()=>setOver(false):undefined}
      onDrop={dragMethod?e=>{e.preventDefault();setOver(false);onDrop(e.dataTransfer.getData('id'));}:undefined}
      className={`rounded-2xl ring-1 transition flex flex-col ${over?'ring-2 ring-brand-500 bg-brand-50/40':'ring-slate-200 bg-white'}`}>
      <div className="p-3 border-b border-slate-100">
        <div className="flex items-center gap-2 mb-2">
          <span className="w-3 h-3 rounded-full" style={{background:team.color}}/>
          <div className="flex-1 min-w-0">
            <div className="text-[14px] font-medium text-slate-800 truncate">{team.name}</div>
            <div className="text-[11px] font-light text-slate-400 flex items-center gap-1"><Icon name="MapPin" size={11}/>{team.zone}</div>
          </div>
          <DayStatusBadge status={stat} />
        </div>
        <div className="flex items-center gap-2">
          <div className="flex-1 h-2 rounded-full bg-slate-200 overflow-hidden"><div className="h-full rounded-full" style={{width:pct+'%',background:sc.bar}}/></div>
          <span className="text-[12px] font-light text-slate-500 tnum">{load}/{team.capacity}</span>
        </div>
      </div>
      <div className="p-2 space-y-2 min-h-[120px] flex-1">
        {jobs.length===0 && <div className="text-center text-[12px] font-light text-slate-300 py-6">{dragMethod?'ลากงานมาวางที่นี่':'ยังไม่มีงาน'}</div>}
        {jobs.map(j=>(
          <div key={j.id} className="rounded-xl bg-slate-50 ring-1 ring-slate-200 p-2.5 flex items-center gap-2">
            <ProductIcon p={j.items[0]?.p} size={15} className="text-slate-400"/>
            <div className="min-w-0 flex-1">
              <div className="text-[13px] text-slate-700 truncate">{j.customer}</div>
              <div className="text-[11px] font-light text-slate-400">อ.{j.district} · {itemsShort(j.items)}</div>
            </div>
            <button onClick={()=>onUnassign(j.id)} className="text-slate-300 hover:text-brand-600"><Icon name="X" size={15}/></button>
          </div>
        ))}
      </div>
    </div>
  );
}

function AssignScreen(){
  const { jobs, assign, updateJob, tweaks, toast, device } = useCK();
  const isMobile = device==='mobile';
  const [date,setDate] = React.useState(CK.TODAY);
  const dragMethod = tweaks.assignMethod==='drag';
  const [sel,setSel] = React.useState(null); // selected pool job (select mode)

  const dayJobs = jobs.filter(j=>j.date===date && j.status!=='cancelled');
  const pool = sortQueue(dayJobs.filter(j=>!j.team));
  const byTeam = id => dayJobs.filter(j=>j.team===id);

  function doAssign(jobId, teamId){ assign(jobId, teamId); setSel(null); toast('มอบหมายงานให้ทีมช่างแล้ว','success'); }
  function unassign(jobId){ updateJob(jobId,{team:null, status:'ready'}); }

  return (
    <div className={isMobile?'p-3':'p-6 max-w-[1200px] mx-auto'}>
      {isMobile ? <h1 className="text-[18px] font-medium text-slate-900 mb-2">มอบหมายงานช่าง</h1>
        : <PageHeader icon="Truck" title="มอบหมายงานให้ทีมช่าง" sub={dragMethod?'ลากงานจากด้านซ้ายไปวางที่ทีม':'เลือกงานแล้วเลือกทีมช่าง'}><DateStepper date={date} onChange={setDate} /></PageHeader>}
      {isMobile && <Card className="p-2 mb-3"><DateStepper date={date} onChange={setDate} compact/></Card>}

      <div className={`grid gap-4 ${isMobile?'grid-cols-1':'lg:grid-cols-[320px_1fr]'}`}>
        {/* Pool */}
        <Card className="p-3 self-start">
          <div className="flex items-center justify-between mb-2 px-1">
            <span className="text-[14px] font-medium text-slate-700 flex items-center gap-1.5"><Icon name="Inbox" size={16} className="text-brand-600"/>งานรอมอบหมาย</span>
            <span className="text-[12px] font-light text-slate-400 bg-slate-100 rounded-full px-2 py-0.5 tnum">{pool.length}</span>
          </div>
          <div className="space-y-2 max-h-[60vh] overflow-auto pr-1">
            {pool.length===0 && <Empty icon="CircleCheck" title="มอบหมายครบแล้ว" />}
            {pool.map(j=>(
              <div key={j.id}
                draggable={dragMethod}
                onDragStart={dragMethod?e=>e.dataTransfer.setData('id',j.id):undefined}
                onClick={!dragMethod?()=>setSel(sel===j.id?null:j.id):undefined}
                className={`rounded-xl p-2.5 ring-1 transition ${dragMethod?'cursor-grab active:cursor-grabbing':'cursor-pointer'} ${sel===j.id?'ring-2 ring-brand-500 bg-brand-50':'ring-slate-200 bg-white hover:ring-brand-300'}`}>
                <div className="flex items-center gap-2">
                  {dragMethod && <Icon name="GripVertical" size={15} className="text-slate-300"/>}
                  <ProductIcon p={j.items[0]?.p} size={15} className="text-brand-500"/>
                  <div className="min-w-0 flex-1">
                    <div className="text-[13px] text-slate-700 truncate flex items-center gap-1">{j.customer}{j.urgency==='urgent'&&<Icon name="Flame" size={12} className="text-brand-600"/>}</div>
                    <div className="text-[11px] font-light text-slate-400">อ.{j.district} · {CK.jobType(j.jobType)?.th} · {itemsShort(j.items)}</div>
                  </div>
                </div>
                {!dragMethod && sel===j.id && (
                  <div className="mt-2 pt-2 border-t border-brand-100 flex flex-wrap gap-1.5">
                    {CK.TEAMS.map(t=>(
                      <button key={t.id} onClick={(e)=>{e.stopPropagation();doAssign(j.id,t.id);}}
                        className="inline-flex items-center gap-1 rounded-lg px-2 py-1 text-[12px] ring-1 ring-slate-300 hover:bg-white bg-white text-slate-600">
                        <span className="w-2 h-2 rounded-full" style={{background:t.color}}/>{t.name.split('—')[0].trim()}
                      </button>
                    ))}
                  </div>
                )}
              </div>
            ))}
          </div>
        </Card>

        {/* Teams */}
        <div className={`grid gap-3 ${isMobile?'grid-cols-1':'sm:grid-cols-2 xl:grid-cols-3'}`}>
          {CK.TEAMS.map(t=>(
            <TeamColumn key={t.id} team={t} jobs={byTeam(t.id)} dragMethod={dragMethod}
              onDrop={(id)=>doAssign(id,t.id)} onUnassign={unassign} />
          ))}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { CoverSheetScreen, AssignScreen, groupJobs });
