/* Week Board (Kanban) view for Daily Queue — 7 day columns with capacity headers */

// ---- helpers ----
function weekStart(isoStr){
  // Monday-start week containing the date
  const d = new Date(isoStr+'T00:00:00');
  const dow = (d.getDay()+6)%7; // 0=Mon
  d.setDate(d.getDate()-dow);
  return CK.iso(d);
}
function statusBigColor(status){
  return { open:'#16a34a', almost:'#d97706', full:'#dc2626', closed:'#64748b' }[status] || '#64748b';
}

// ===== compact job card (board) =====
function BoardJobCard({ job, seq, onOpen }){
  const b = CK.branch(job.branch); const jt = CK.jobType(job.jobType); const it = job.items[0];
  const firstSlot = (job.slot||'').startsWith('คิวแรก');
  const prod = CK.product(it?.p);
  return (
    <button onClick={onOpen} className="w-full text-left bg-white rounded-xl ring-1 ring-slate-200 hover:ring-brand-300 hover:shadow-card transition p-2.5 group">
      <div className="flex items-center gap-2">
        <span className="grid place-items-center w-6 h-6 rounded-md bg-slate-900 text-white text-[12px] font-medium tnum shrink-0">{seq}</span>
        {firstSlot ? (
          <span className="inline-flex items-center gap-1 text-[11px] font-normal text-slate-700 bg-slate-100 ring-1 ring-slate-200 rounded-md px-1.5 py-0.5"><Icon name="Clock" size={11}/>คิวแรก 09:00</span>
        ) : (
          <span className="inline-flex items-center gap-1 text-[12px] font-light text-slate-500"><Icon name="MapPin" size={12}/>อ.{job.district}</span>
        )}
        {job.urgency==='urgent' && <span className="ml-auto text-brand-600"><Icon name="Flame" size={13}/></span>}
      </div>

      {firstSlot && <div className="mt-1.5 flex items-center gap-1 text-[12px] font-light text-slate-500"><Icon name="MapPin" size={12}/>อ.{job.district}</div>}

      <div className="mt-1.5 text-[13px] font-medium text-slate-800 leading-tight truncate">{job.customer}</div>
      <div className="text-[11px] font-light text-slate-400 font-mono">{job.phone}</div>

      <div className="mt-1.5 inline-flex items-center gap-1 text-[11px] font-normal text-slate-600">
        <Icon name={jt?jt.icon:'Wrench'} size={12} className="text-slate-400"/>{jt?.th}
      </div>

      <div className="mt-2 pt-2 border-t border-dashed border-slate-200 flex items-center justify-between gap-2">
        <span className="text-[12px] font-light text-slate-600 truncate">
          {prod?.th} {it?.btu?`${Number(it.btu).toLocaleString()} BTU`:''}{it?.model?` · ${it.model}`:''}
        </span>
        <span className="shrink-0 text-[10px] font-normal text-brand-700 ring-1 ring-brand-200 rounded px-1.5 py-0.5">{b?.code}</span>
      </div>
    </button>
  );
}

// ===== capacity headers (4 styles) =====
function MeterHeader({ d, date, isToday, onToggleClosed, onOpenDay }){
  const color = statusBigColor(d.status);
  const segs = 12; const filled = Math.round(d.pct/100*segs);
  return (
    <div className="rounded-2xl ring-1 ring-slate-200 bg-white p-3">
      <button onClick={onOpenDay} className="w-full flex items-start justify-between mb-2 text-left">
        <div className="flex items-baseline gap-1.5">
          <span className="text-[20px] font-medium text-slate-900">{CK.TH_DOW[new Date(date+'T00:00:00').getDay()].slice(0,2)}. {Number(date.slice(8,10))}</span>
          <span className="text-[12px] font-light text-slate-400">{CK.TH_MON[new Date(date+'T00:00:00').getMonth()]}</span>
        </div>
        {isToday && <span className="text-[11px] font-normal text-white bg-brand-600 rounded-md px-2 py-0.5">วันนี้</span>}
      </button>
      <div className="flex items-center justify-between mb-1.5">
        <span className="inline-flex items-center gap-1.5 text-[13px] font-normal" style={{color}}>
          <span className="w-2 h-2 rounded-full" style={{background:color}}/>{CK.DAYSTATUS[d.status].th}
        </span>
        <span className="text-[20px] font-medium tnum" style={{color}}>{d.pct}%</span>
      </div>
      <div className="flex items-center gap-0.5 mb-1.5">
        {Array.from({length:segs}).map((_,i)=>(
          <span key={i} className="flex-1 h-2.5 rounded-sm transition-colors" style={{background: i<filled?color:'#e2e8f0'}}/>
        ))}
      </div>
      <div className="flex items-center justify-between text-[11px] font-light text-slate-400 mb-2.5">
        <span>ใช้ไป {d.used} คิว</span><span>เต็มที่ {d.max}</span>
      </div>
      <button onClick={onToggleClosed} className={`w-full inline-flex items-center justify-center gap-1.5 rounded-lg py-1.5 text-[12px] ring-1 transition ${d.closed?'bg-slate-100 text-slate-600 ring-slate-300':'bg-white text-slate-500 ring-slate-300 hover:bg-slate-50'}`}>
        <Icon name="Power" size={13}/>{d.closed?'เปิดรับงาน':'ปิดรับงานวันนี้'}
      </button>
    </div>
  );
}

function GaugeHeader({ d, date, isToday, onToggleClosed, onOpenDay }){
  const color = statusBigColor(d.status);
  const r=40, c=Math.PI*r, off=c*(1-Math.min(100,d.pct)/100);
  return (
    <div className="rounded-2xl ring-1 ring-slate-200 bg-white p-3">
      <button onClick={onOpenDay} className="w-full flex items-start justify-between mb-1 text-left">
        <span className="text-[18px] font-medium text-slate-900">{CK.TH_DOW[new Date(date+'T00:00:00').getDay()].slice(0,2)}. {Number(date.slice(8,10))} <span className="text-[12px] font-light text-slate-400">{CK.TH_MON[new Date(date+'T00:00:00').getMonth()]}</span></span>
        {isToday && <span className="text-[11px] font-normal text-white bg-brand-600 rounded-md px-2 py-0.5">วันนี้</span>}
      </button>
      <div className="relative mx-auto" style={{width:120,height:66}}>
        <svg viewBox="0 0 100 56" className="w-full">
          <path d="M10 52 A40 40 0 0 1 90 52" fill="none" stroke="#e2e8f0" strokeWidth="9" strokeLinecap="round"/>
          <path d="M10 52 A40 40 0 0 1 90 52" fill="none" stroke={color} strokeWidth="9" strokeLinecap="round" strokeDasharray={c} strokeDashoffset={off}/>
        </svg>
        <div className="absolute inset-x-0 bottom-0 text-center">
          <div className="text-[20px] font-medium tnum leading-none" style={{color}}>{d.pct}%</div>
        </div>
      </div>
      <div className="flex items-center justify-center gap-1.5 text-[12px] font-normal mt-1 mb-2" style={{color}}>
        <span className="w-2 h-2 rounded-full" style={{background:color}}/>{CK.DAYSTATUS[d.status].th}
        <span className="text-slate-400 font-light">· {d.used}/{d.max} คิว</span>
      </div>
      <button onClick={onToggleClosed} className={`w-full inline-flex items-center justify-center gap-1.5 rounded-lg py-1.5 text-[12px] ring-1 transition ${d.closed?'bg-slate-100 text-slate-600 ring-slate-300':'bg-white text-slate-500 ring-slate-300 hover:bg-slate-50'}`}>
        <Icon name="Power" size={13}/>{d.closed?'เปิดรับงาน':'ปิดรับงานวันนี้'}
      </button>
    </div>
  );
}

function BlueprintHeader({ d, date, isToday, onToggleClosed, onOpenDay }){
  const color = statusBigColor(d.status);
  const ticks=20; const filled=Math.round(d.pct/100*ticks);
  return (
    <div className="rounded-2xl ring-1 ring-slate-300 bg-slate-50 p-3 font-mono"
      style={{backgroundImage:'linear-gradient(#e2e8f0 1px,transparent 1px),linear-gradient(90deg,#e2e8f0 1px,transparent 1px)',backgroundSize:'14px 14px'}}>
      <button onClick={onOpenDay} className="w-full flex items-center justify-between mb-2 text-left">
        <span className="text-[15px] font-medium text-slate-800 tracking-tight">{CK.TH_DOW[new Date(date+'T00:00:00').getDay()].slice(0,2)}.{Number(date.slice(8,10))}/{new Date(date+'T00:00:00').getMonth()+1}</span>
        {isToday && <span className="text-[10px] font-normal text-white bg-brand-600 rounded px-1.5 py-0.5">NOW</span>}
      </button>
      <div className="flex items-center justify-between text-[11px] text-slate-500 mb-1">
        <span>USED {d.used.toFixed(1)}</span><span>CAP {d.max.toFixed(1)}</span>
      </div>
      <div className="flex items-center gap-px mb-1.5">
        {Array.from({length:ticks}).map((_,i)=>(
          <span key={i} className="flex-1" style={{height:i%5===0?14:9, background:i<filled?color:'#cbd5e1'}}/>
        ))}
      </div>
      <div className="flex items-center justify-between text-[12px] mb-2.5">
        <span className="uppercase tracking-wide" style={{color}}>{ {open:'OPEN',almost:'NEAR',full:'FULL',closed:'CLOSED'}[d.status] }</span>
        <span className="font-medium tnum" style={{color}}>{d.pct}%</span>
      </div>
      <button onClick={onToggleClosed} className={`w-full inline-flex items-center justify-center gap-1.5 rounded py-1.5 text-[11px] ring-1 transition uppercase tracking-wide ${d.closed?'bg-slate-200 text-slate-600 ring-slate-400':'bg-white/70 text-slate-500 ring-slate-400 hover:bg-white'}`}>
        <Icon name="Power" size={12}/>{d.closed?'reopen':'close day'}
      </button>
    </div>
  );
}

function CompactHeader({ d, date, isToday, onToggleClosed, onOpenDay }){
  const color = statusBigColor(d.status);
  return (
    <div className="rounded-xl ring-1 ring-slate-200 bg-white p-2.5">
      <button onClick={onOpenDay} className="w-full flex items-center gap-2 text-left">
        <span className="text-[15px] font-medium text-slate-900 whitespace-nowrap">{CK.TH_DOW[new Date(date+'T00:00:00').getDay()].slice(0,2)}. {Number(date.slice(8,10))}</span>
        {isToday && <span className="text-[10px] font-normal text-white bg-brand-600 rounded px-1.5 py-0.5">วันนี้</span>}
        <span className="ml-auto text-[14px] font-medium tnum" style={{color}}>{d.pct}%</span>
        <span className="w-2 h-2 rounded-full shrink-0" style={{background:color}}/>
      </button>
      <div className="mt-1.5 h-1.5 rounded-full bg-slate-200 overflow-hidden">
        <div className="h-full rounded-full" style={{width:Math.min(100,d.pct)+'%', background:color}}/>
      </div>
    </div>
  );
}

const CAP_HEADERS = { meter:MeterHeader, gauge:GaugeHeader, blueprint:BlueprintHeader, compact:CompactHeader };

// ===== Week Board =====
function WeekBoard({ jobs, filters, onOpenJob, onOpenDay, isMobile }){
  const [start,setStart] = React.useState(CK.TODAY);
  const [capStyle,setCapStyle] = React.useState('meter');
  const [, force] = React.useReducer(x=>x+1,0);

  const days = Array.from({length:7},(_,i)=>CK.addDays(start,i));
  const Header = CAP_HEADERS[capStyle];

  // week stats
  const weekJobs = jobs.filter(j=>days.includes(j.date) && j.status!=='cancelled');
  const filteredAll = applyFilters(weekJobs, {...filters, date:undefined});
  const fullDays = days.filter(d=>computeDayStatus(jobs,d).status==='full').length;
  const freeUnits = Math.round(days.reduce((s,d)=>{ const x=computeDayStatus(jobs,d); return s+Math.max(0,x.max-x.used); },0)*10)/10;

  function toggleClosed(d){ const c=CK.CAPACITY[d]||{max:10,closed:false}; CK.CAPACITY[d]={...c,closed:!c.closed}; force(); }
  const capOpts = [['meter','เมเตอร์'],['gauge','เกจ'],['blueprint','บลูพรินต์'],['compact','กระชับ']];
  const VISIBLE = 4;

  return (
    <div>
      {/* board controls */}
      <div className="flex flex-wrap items-center justify-between gap-3 mb-3">
        <div className="flex items-center gap-2">
          <button onClick={()=>setStart(CK.addDays(start,-7))} 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>
          <button onClick={()=>setStart(CK.TODAY)} className={`px-3 h-9 rounded-xl text-[13px] ring-1 transition ${start===CK.TODAY?'bg-slate-900 text-white ring-slate-900':'bg-white text-slate-600 ring-slate-300 hover:bg-slate-50'}`}>จากวันนี้</button>
          <button onClick={()=>setStart(CK.addDays(start,7))} 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>
          <span className="text-[13px] font-light text-slate-500 ml-1 hidden sm:inline">{CK.thDate(days[0])} – {CK.thDate(days[6])}</span>
        </div>
        <div className="flex items-center gap-2">
          <span className="text-[12px] font-light text-slate-400 hidden sm:inline">มุมมอง</span>
          <div className="flex items-center rounded-xl ring-1 ring-slate-300 bg-white p-0.5">
            {capOpts.map(([k,l])=>(
              <button key={k} onClick={()=>setCapStyle(k)} className={`px-2.5 py-1.5 rounded-lg text-[12px] transition ${capStyle===k?'bg-slate-900 text-white':'text-slate-600 hover:bg-slate-50'}`}>{l}</button>
            ))}
          </div>
        </div>
      </div>

      {/* legend + week stats */}
      <div className="flex flex-wrap items-center justify-between gap-3 mb-3">
        <div className="flex flex-wrap items-center gap-3">
          {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-2.5 h-2.5 rounded-full" style={{background:s.bar}}/>{s.th}</span>
          ))}
        </div>
        <div className="flex items-center gap-4">
          <div className="text-right"><div className="text-[11px] font-light text-slate-400">งานสัปดาห์นี้</div><div className="text-[16px] font-medium text-slate-800 tnum leading-none">{filteredAll.length}</div></div>
          <div className="text-right"><div className="text-[11px] font-light text-slate-400">คิวที่เต็ม</div><div className="text-[16px] font-medium text-brand-700 tnum leading-none">{fullDays} วัน</div></div>
          <div className="text-right"><div className="text-[11px] font-light text-slate-400">ว่างรับเพิ่ม</div><div className="text-[16px] font-medium text-green-600 tnum leading-none">{freeUnits} คิว</div></div>
        </div>
      </div>

      {/* columns */}
      <div className="overflow-x-auto -mx-1 px-1 pb-2">
        <div className="flex gap-3" style={{minWidth: isMobile?'auto':'max-content'}}>
          {days.map(d=>{
            const ds = computeDayStatus(jobs,d);
            const isToday = d===CK.TODAY;
            const colJobs = sortQueue(applyFilters(jobs.filter(j=>j.date===d && j.status!=='cancelled'), {...filters, date:undefined}));
            const shown = colJobs.slice(0,VISIBLE);
            const extra = colJobs.length - shown.length;
            return (
              <div key={d} className="shrink-0 flex flex-col gap-2.5" style={{width: isMobile?260:248}}>
                <Header d={ds} date={d} isToday={isToday} onToggleClosed={()=>toggleClosed(d)} onOpenDay={()=>onOpenDay(d)} />
                {colJobs.length===0 ? (
                  <div className="rounded-xl ring-1 ring-dashed ring-slate-200 py-6 text-center text-[12px] font-light text-slate-300">ไม่มีงาน</div>
                ) : (
                  <>
                    {shown.map((j,i)=><BoardJobCard key={j.id} job={j} seq={i+1} onOpen={()=>onOpenJob(j.id)} />)}
                    {extra>0 && <button onClick={()=>onOpenDay(d)} className="text-center text-[12px] font-light text-slate-400 hover:text-brand-700 py-1">+{extra} งาน</button>}
                  </>
                )}
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { WeekBoard, weekStart });
