// week-template.jsx — 排班模板（支援多種 pattern type）

function WeekTemplatePage({ state, update, accent, doctorDisplay }) {
  return (
    <div>
      <SectionHeader title="週模板" hint="這是每週重複的基底班表。月份預設套用這份；單日可在月份頁覆寫。" />
      <div style={{ marginTop: 18, display:'flex', gap: 16, alignItems:'flex-start' }}>
        <div style={{ flex: 1, minWidth: 0 }}>
          <WeeklyEditor state={state} update={update} accent={accent} doctorDisplay={doctorDisplay} />
        </div>
        <DoctorPalette doctors={state.doctors} />
      </div>
    </div>
  );
}

function DoctorPalette({ doctors }) {
  return (
    <aside style={{
      width: 200, flexShrink: 0,
      background:'#fff', border:'1px solid #ebe4d8', borderRadius: 10, padding: 12,
      position:'sticky', top: 12,
    }}>
      <div style={{ fontSize: 13, fontWeight: 600, color:'#29261b', marginBottom: 4 }}>醫師清單</div>
      <div style={{ fontSize: 11, color:'#a09887', marginBottom: 10 }}>拖到班別格 · 或點格子勾選</div>
      <div style={{ display:'flex', flexDirection:'column', gap: 6 }}>
        {doctors.map(d => <DraggableDoctor key={d.id} doctor={d} />)}
      </div>
    </aside>
  );
}

// ── Shift × Day grid (reused by weekly / biweekly / cycle) ──────────────────
function ShiftDayGrid({ state, update, accent, doctorDisplay,
                       cols, restCol, getIds, setIds, container }) {
  // cols: [{ key, label, sub?, rest? }]
  // restCol: function(colKey) => true if column is rest
  const { shifts, doctors } = state;
  const [editing, setEditing] = React.useState(null); // { col, shiftId }

  return (
    <>
      <div style={{
        display:'grid',
        gridTemplateColumns: `90px repeat(${cols.length}, 1fr)`,
        background:'#fff', border:'1px solid #ebe4d8', borderRadius: 10, overflow:'hidden',
        fontSize: 12,
      }}>
        <div style={hdrCellStyle}></div>
        {cols.map(c => {
          const off = c.rest;
          return (
            <div key={c.key} style={{ ...hdrCellStyle,
              color: off ? '#b48a52' : '#29261b',
              background: off ? '#f7ede0' : '#faf6ef',
            }}>
              {c.label}
              {c.sub && <div style={{ fontSize: 9, color:'#a09887', fontWeight: 400, marginTop: 1 }}>{c.sub}</div>}
              {off && <span style={{ fontSize: 10, marginLeft: 6, color:'#b48a52' }}>休</span>}
            </div>
          );
        })}
        {shifts.map(sh => (
          <React.Fragment key={sh.id}>
            <div style={{ ...cellStyle, background:'#faf6ef', padding:'12px 10px' }}>
              <div style={{ display:'flex', alignItems:'center', gap: 6, fontWeight: 600, color:'#29261b' }}>
                <span style={{ width:8, height:8, borderRadius:2, background: sh.accent }} />
                {sh.label}
              </div>
              <div style={{ fontSize: 11, color:'#a09887', fontFamily:'ui-monospace, monospace' }}>
                {sh.start}–{sh.end}
              </div>
            </div>
            {cols.map(c => {
              const off = c.rest;
              const ids = getIds(c.key, sh.id);
              const isEditing = editing && editing.col === c.key && editing.shiftId === sh.id;
              return (
                <div key={c.key} onClick={()=>!off && setEditing({col: c.key, shiftId: sh.id})}
                  onDragOver={(e)=>{ if(!off){ e.preventDefault(); e.currentTarget.style.background = `${accent}10`; } }}
                  onDragLeave={(e)=>{ e.currentTarget.style.background = off ? '#f7ede0' : ''; }}
                  onDrop={(e)=>{
                    if(off) return; e.preventDefault();
                    e.currentTarget.style.background = '';
                    const id = e.dataTransfer.getData('text/doctor-id');
                    if (id && !ids.includes(id)) setIds(c.key, sh.id, [...ids, id]);
                  }}
                  style={{
                    ...cellStyle, minHeight: 88, padding: 8,
                    background: off ? '#f7ede0' : (isEditing ? `${accent}10` : '#fff'),
                    cursor: off ? 'default' : 'pointer', position:'relative',
                    outline: isEditing ? `1.5px solid ${accent}` : 'none', outlineOffset: -2,
                  }}>
                  {off ? (
                    <div style={{ color:'#b48a52', fontSize: 13, opacity: .65,
                      height:'100%', display:'grid', placeItems:'center' }}>休</div>
                  ) : (
                    <div style={{ display:'flex', flexWrap:'wrap', gap: 3, alignItems:'flex-start' }}>
                      {ids.map(id => {
                        const d = docById(doctors, id);
                        return d && <DocPill key={id} doctor={d} mode={doctorDisplay} size="xs"
                                 onRemove={()=>setIds(c.key, sh.id, ids.filter(x=>x!==id))} />;
                      })}
                      {ids.length === 0 && <span style={{ fontSize: 11, color:'#bcb3a3' }}>＋ 加入醫師</span>}
                    </div>
                  )}
                </div>
              );
            })}
          </React.Fragment>
        ))}
      </div>

      {editing && (
        <div style={{ marginTop: 12, background:'#fff', border:`1.5px solid ${accent}`,
          borderRadius: 10, padding: 14 }}>
          <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom: 8 }}>
            <div style={{ fontSize: 13, fontWeight: 600, color:'#29261b' }}>
              編輯 — {cols.find(c=>c.key===editing.col).label} ·{' '}
              {state.shifts.find(s=>s.id===editing.shiftId).label}
            </div>
            <button onClick={()=>setEditing(null)} style={closeStyle}>完成</button>
          </div>
          <DoctorMultiSelect
            doctors={state.doctors}
            selectedIds={getIds(editing.col, editing.shiftId)}
            onChange={ids => setIds(editing.col, editing.shiftId, ids)}
          />
        </div>
      )}
    </>
  );
}

// ── Weekly ─────────────────────────────────────────────────────────────
function WeeklyEditor({ state, update, accent, doctorDisplay }) {
  const cols = WEEKDAYS_ZH.map((w, i) => ({
    key: i, label: `週${w}`,
    rest: state.weeklyHolidays.includes(i),
  }));
  return <ShiftDayGrid state={state} update={update} accent={accent} doctorDisplay={doctorDisplay}
    cols={cols}
    getIds={(k, sh) => state.weekTemplate[k]?.[sh] || []}
    setIds={(k, sh, ids) => update(s => ({ ...s, weekTemplate: {
      ...s.weekTemplate, [k]: { ...s.weekTemplate[k], [sh]: ids },
    }}))}
  />;
}

// ── Biweekly ───────────────────────────────────────────────────────────
function BiweeklyEditor({ state, update, accent, doctorDisplay }) {
  const items = state.biweeklyConfig.items;
  const setItem = (k, sh, ids) => update(s => ({ ...s, biweeklyConfig: {
    ...s.biweeklyConfig, items: { ...s.biweeklyConfig.items,
      [k]: { ...s.biweeklyConfig.items[k], [sh]: ids } },
  }}));
  return (
    <div style={{ display:'flex', flexDirection:'column', gap: 14 }}>
      <div style={{ fontSize:12, color:'#86827a' }}>
        A 週起算日 (anchor)：
        <input type="date" value={state.biweeklyConfig.anchor}
          onChange={e=>update(s=>({ ...s, biweeklyConfig: {...s.biweeklyConfig, anchor: e.target.value} }))}
          style={{ marginLeft:8, border:'1px solid #e5dccb', borderRadius: 4, padding:'3px 6px' }} />
      </div>
      <div>
        <div style={{ fontSize: 12, fontWeight: 600, color: accent, marginBottom: 6 }}>A 週</div>
        <ShiftDayGrid state={state} update={update} accent={accent} doctorDisplay={doctorDisplay}
          cols={WEEKDAYS_ZH.map((w,i)=>({ key: i, label:`週${w}`, rest: state.weeklyHolidays.includes(i) }))}
          getIds={(k, sh)=> items[k]?.[sh] || []}
          setIds={setItem} />
      </div>
      <div>
        <div style={{ fontSize: 12, fontWeight: 600, color: accent, marginBottom: 6 }}>B 週</div>
        <ShiftDayGrid state={state} update={update} accent={accent} doctorDisplay={doctorDisplay}
          cols={WEEKDAYS_ZH.map((w,i)=>({ key: i+7, label:`週${w}`, rest: state.weeklyHolidays.includes(i) }))}
          getIds={(k, sh)=> items[k]?.[sh] || []}
          setIds={setItem} />
      </div>
    </div>
  );
}

// ── N-day cycle ────────────────────────────────────────────────────────
function CycleEditor({ state, update, accent, doctorDisplay }) {
  const cfg = state.cycleConfig;
  const setLen = (n) => update(s => {
    const items = { ...s.cycleConfig.items };
    for (let i = 0; i < n; i++) if (!items[i]) items[i] = { early:[], mid:[], late:[] };
    Object.keys(items).forEach(k => { if (+k >= n) delete items[k]; });
    return { ...s, cycleConfig: { ...s.cycleConfig, length: n, items } };
  });
  const cols = Array.from({length: cfg.length}, (_, i) => ({
    key: i, label: `第 ${i+1} 天`,
    sub: dateForCycleDay(cfg.anchor, i),
  }));
  return (
    <div style={{ display:'flex', flexDirection:'column', gap: 14 }}>
      <div style={{ display:'flex', alignItems:'center', gap: 16, fontSize: 12, color:'#86827a' }}>
        <label>
          循環長度
          <input type="number" min="2" max="14" value={cfg.length}
            onChange={e=>setLen(Math.max(2, Math.min(14, +e.target.value || 2)))}
            style={{ marginLeft:6, width: 50, border:'1px solid #e5dccb', borderRadius: 4, padding:'3px 6px' }} />
          <span style={{ marginLeft: 4 }}>天</span>
        </label>
        <label>
          起算日 (anchor)
          <input type="date" value={cfg.anchor}
            onChange={e=>update(s=>({ ...s, cycleConfig: { ...s.cycleConfig, anchor: e.target.value } }))}
            style={{ marginLeft:6, border:'1px solid #e5dccb', borderRadius: 4, padding:'3px 6px' }} />
        </label>
      </div>
      <ShiftDayGrid state={state} update={update} accent={accent} doctorDisplay={doctorDisplay}
        cols={cols}
        getIds={(k, sh)=> cfg.items[k]?.[sh] || []}
        setIds={(k, sh, ids)=> update(s => ({ ...s, cycleConfig: { ...s.cycleConfig,
          items: { ...s.cycleConfig.items, [k]: { ...s.cycleConfig.items[k], [sh]: ids } } } }))}
      />
    </div>
  );
}

function dateForCycleDay(anchor, i) {
  if (!anchor) return '';
  const d = parseDate(anchor);
  d.setDate(d.getDate() + i);
  return `從 ${d.getMonth()+1}/${d.getDate()} 起`;
}

// ── Monthly by date ────────────────────────────────────────────────────
function MonthlyDateEditor({ state, update, accent, doctorDisplay }) {
  const cfg = state.monthlyDateConfig;
  const activeDays = Object.keys(cfg.items).map(Number).sort((a,b)=>a-b);
  const [newDay, setNewDay] = React.useState('');

  const addDay = () => {
    const n = +newDay;
    if (n >= 1 && n <= 31 && !cfg.items[n]) {
      update(s => ({ ...s, monthlyDateConfig: { items: { ...s.monthlyDateConfig.items,
        [n]: { early:[], mid:[], late:[] } } } }));
      setNewDay('');
    }
  };
  const removeDay = (n) => {
    update(s => {
      const items = { ...s.monthlyDateConfig.items };
      delete items[n];
      return { ...s, monthlyDateConfig: { items } };
    });
  };

  return (
    <div style={{ display:'flex', flexDirection:'column', gap: 14 }}>
      <div style={{ fontSize: 12, color:'#86827a', display:'flex', gap: 10, alignItems:'center' }}>
        新增日期：
        <input type="number" min="1" max="31" value={newDay}
          placeholder="1-31" onChange={e=>setNewDay(e.target.value)}
          style={{ width: 70, border:'1px solid #e5dccb', borderRadius: 4, padding:'4px 8px' }} />
        <button onClick={addDay} style={{
          appearance:'none', border:0, background: accent, color:'#fff',
          padding:'4px 12px', borderRadius: 4, fontSize: 12, cursor:'pointer',
        }}>新增日期</button>
        <span style={{ color:'#bcb3a3', marginLeft: 8 }}>
          ※ 未列出的日期會套用週固定休或休息
        </span>
      </div>
      {activeDays.length === 0 && (
        <div style={{ padding: 30, textAlign:'center', color:'#bcb3a3', fontSize: 12,
          background:'#fff', border:'1px dashed #e5dccb', borderRadius: 8 }}>
          尚未設定任何日期。例如：每月 1、15、28 號 早班 王醫師
        </div>
      )}
      <ShiftDayGrid state={state} update={update} accent={accent} doctorDisplay={doctorDisplay}
        cols={activeDays.map(d => ({
          key: d, label: `${d} 號`,
        }))}
        getIds={(k, sh)=> cfg.items[k]?.[sh] || []}
        setIds={(k, sh, ids)=> update(s => ({ ...s, monthlyDateConfig: { items: {
          ...s.monthlyDateConfig.items, [k]: { ...s.monthlyDateConfig.items[k], [sh]: ids } } } }))}
      />
      {activeDays.length > 0 && (
        <div style={{ display:'flex', flexWrap:'wrap', gap: 6 }}>
          {activeDays.map(d => (
            <span key={d} style={{
              background:'#faf6ef', padding:'3px 8px', borderRadius: 10, fontSize: 12,
              display:'inline-flex', alignItems:'center', gap: 4,
            }}>
              {d} 號
              <button onClick={()=>removeDay(d)} style={{
                appearance:'none', border:0, background:'transparent', cursor:'pointer',
                color:'rgba(0,0,0,.4)', fontSize: 13, padding: 0,
              }}>×</button>
            </span>
          ))}
        </div>
      )}
    </div>
  );
}

const hdrCellStyle = {
  padding: '10px 8px', fontSize: 12, fontWeight: 600,
  borderBottom: '1px solid #ebe4d8', textAlign: 'center', background:'#faf6ef',
};
const cellStyle = { borderBottom:'1px solid #ebe4d8', borderRight:'1px solid #ebe4d8' };
const closeStyle = {
  appearance:'none', border:'1px solid #e5dccb', background:'#fff',
  padding:'4px 12px', borderRadius: 6, fontSize: 12, cursor:'pointer', color:'#29261b',
};

Object.assign(window, { WeekTemplatePage });
