// shift-defs.jsx — 班別與假日 sub-page
// Edit shift times, weekly fixed holidays, special holidays/workdays

function ShiftDefsPage({ state, update, accent }) {
  const { shifts, weeklyHolidays, specialHolidays, specialWorkdays } = state;
  const setShift = (id, patch) => update(s => ({
    ...s, shifts: s.shifts.map(sh => sh.id === id ? { ...sh, ...patch } : sh),
  }));
  const removeShift = (id) => {
    if (!confirm('確定刪除此班別？\n相關週模板、日覆寫中的醫師指派也會一起清除。')) return;
    update(s => {
      const nextTpl = {};
      Object.entries(s.weekTemplate || {}).forEach(([w, m]) => {
        const { [id]: _, ...rest } = m || {}; nextTpl[w] = rest;
      });
      const nextOv = {};
      Object.entries(s.dayOverrides || {}).forEach(([iso, m]) => {
        const { [id]: _, ...rest } = m || {}; nextOv[iso] = rest;
      });
      return { ...s, shifts: s.shifts.filter(sh => sh.id !== id),
        weekTemplate: nextTpl, dayOverrides: nextOv };
    });
  };
  const addShift = () => {
    const palette = ['#f4c97b','#a3c5e0','#b9a1d9','#9ed3a8','#e8a5b8','#d9b285','#88c5c3'];
    update(s => {
      const used = new Set(s.shifts.map(x=>x.accent));
      const accent2 = palette.find(c=>!used.has(c)) || palette[s.shifts.length % palette.length];
      let i = s.shifts.length + 1, id;
      do { id = `s${i++}`; } while (s.shifts.some(x=>x.id===id));
      return { ...s, shifts: [...s.shifts, {
        id, label: `班別 ${s.shifts.length+1}`,
        start: '09:00', end: '12:00', accent: accent2,
      }] };
    });
  };
  const toggleWeekly = (w) => update(s => ({
    ...s, weeklyHolidays: s.weeklyHolidays.includes(w)
      ? s.weeklyHolidays.filter(x => x !== w) : [...s.weeklyHolidays, w],
  }));

  return (
    <div style={{ display:'flex', flexDirection:'column', gap: 28 }}>
      {/* shift times */}
      <section>
        <SectionHeader title="班別時間" hint="自訂每個班別的時段。可加 / 移除班別。" />
        <div style={{
          display:'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12, marginTop: 12,
        }}>
          {shifts.map(sh => (
            <ShiftCard key={sh.id} sh={sh} setShift={setShift} accent={accent} onRemove={()=>removeShift(sh.id)} />
          ))}
          <button onClick={addShift} style={{
            appearance:'none', cursor:'pointer',
            background:'transparent', border:'2px dashed #d9cdb6', borderRadius: 10,
            color:'#86827a', fontSize: 13, fontWeight: 500, minHeight: 140,
            display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center', gap: 4,
            fontFamily:'inherit',
          }}>
            <span style={{ fontSize: 24, lineHeight: 1, color:'#bcb3a3' }}>+</span>
            新增班別
          </button>
        </div>
      </section>

      {/* weekly holidays */}
      <section>
        <SectionHeader title="週固定休" hint="每週固定不營業的日子。" />
        <div style={{ display:'flex', gap: 6, marginTop: 12 }}>
          {['一','二','三','四','五','六','日'].map((label, i) => {
            const on = weeklyHolidays.includes(i);
            return (
              <button key={i} onClick={()=>toggleWeekly(i)} style={{
                width: 56, height: 56, borderRadius: 8,
                border: on ? `1.5px solid ${accent}` : '1px solid #e5dccb',
                background: on ? `${accent}14` : '#fff',
                color: on ? accent : '#3f3a36',
                cursor: 'pointer',
                display:'flex', flexDirection:'column', alignItems:'center',
                justifyContent:'center', gap: 2,
                fontSize: 14, fontWeight: 600,
              }}>
                <span style={{ fontSize: 11, fontWeight: 400, color: on ? accent : '#a09887' }}>週</span>
                {label}
              </button>
            );
          })}
        </div>
      </section>

      {/* special days */}
      <section>
        <SectionHeader title="例外日" hint="覆蓋週固定休：標記額外休假或開診日。" />
        <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap: 16, marginTop: 12 }}>
          <DateListEditor
            label="額外休假日" tone="rest" accent={accent}
            dates={specialHolidays}
            onChange={(arr)=>update(s=>({ ...s, specialHolidays: arr }))}
          />
          <DateListEditor
            label="例外開診日" tone="work" accent={accent}
            dates={specialWorkdays}
            onChange={(arr)=>update(s=>({ ...s, specialWorkdays: arr }))}
          />
        </div>
      </section>
    </div>
  );
}

function ShiftCard({ sh, setShift, accent, onRemove }) {
  const [open, setOpen] = React.useState(false);
  const dayTimes = sh.dayTimes || {};
  const overrideCount = Object.values(dayTimes).filter(v => v && v.start && v.end).length;
  const setDay = (w, patch) => {
    const nextDay = { ...(dayTimes[w] || {}), ...patch };
    const next = { ...dayTimes, [w]: nextDay };
    setShift(sh.id, { dayTimes: next });
  };
  const clearDay = (w) => {
    const next = { ...dayTimes }; delete next[w];
    setShift(sh.id, { dayTimes: next });
  };
  return (
    <div style={{
      background:'#fff', border:'1px solid #ebe4d8', borderRadius: 10,
      padding: 16, display:'flex', flexDirection:'column', gap: 10,
      borderTop: `4px solid ${sh.accent}`,
    }}>
      <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between' }}>
        <input value={sh.label} onChange={e=>setShift(sh.id, { label: e.target.value })}
          style={{
            border:0, background:'transparent', fontSize: 16, fontWeight: 600,
            color:'#29261b', outline:'none', width: 90,
          }} />
        <div style={{ display:'flex', alignItems:'center', gap: 6 }}>
          <span style={{ fontSize: 11, color:'#a09887' }}>{sh.id}</span>
          {onRemove && (
            <button onClick={onRemove} title="刪除班別" style={{
              appearance:'none', border:0, background:'transparent', cursor:'pointer',
              fontSize: 16, color:'#bcb3a3', padding:'2px 4px', lineHeight: 1,
            }}>×</button>
          )}
        </div>
      </div>
      <div style={{ display:'flex', alignItems:'center', gap: 8 }}>
        <TimeInput value={sh.start} onChange={v=>setShift(sh.id, { start: v })} />
        <span style={{ color:'#a09887' }}>—</span>
        <TimeInput value={sh.end}   onChange={v=>setShift(sh.id, { end: v })} />
      </div>
      <div style={{ fontSize: 11, color:'#86827a' }}>
        時長 {durationOf(sh.start, sh.end)} <span style={{ color:'#bcb3a3' }}>· 預設</span>
      </div>
      <button onClick={()=>setOpen(o=>!o)} style={{
        appearance:'none', border:'1px dashed #e5dccb', background:'#faf6ef',
        padding:'6px 10px', borderRadius: 6, fontSize: 12,
        color: overrideCount ? accent : '#86827a', cursor:'pointer',
        textAlign:'left', display:'flex', alignItems:'center', gap: 6,
      }}>
        <span style={{
          display:'inline-block', transition:'transform .15s',
          transform: open ? 'rotate(90deg)' : 'none', fontSize: 10,
        }}>▶</span>
        依星期微調時間
        {overrideCount > 0 && (
          <span style={{
            marginLeft:'auto', background: accent, color:'#fff',
            padding:'1px 7px', borderRadius: 10, fontSize: 10, fontWeight: 600,
          }}>{overrideCount}</span>
        )}
      </button>
      {open && (
        <div style={{
          display:'flex', flexDirection:'column', gap: 4,
          background:'#faf6ef', borderRadius: 6, padding: 8,
        }}>
          {['一','二','三','四','五','六','日'].map((label, w) => {
            const ov = dayTimes[w];
            const has = !!(ov && ov.start && ov.end);
            return (
              <div key={w} style={{
                display:'flex', alignItems:'center', gap: 6, fontSize: 12,
              }}>
                <span style={{
                  width: 22, textAlign:'center', color: has ? accent : '#86827a',
                  fontWeight: has ? 600 : 400,
                }}>{label}</span>
                <TimeInputSm
                  value={ov?.start || sh.start}
                  muted={!has}
                  onChange={v=>setDay(w, { start: v, end: ov?.end || sh.end })}
                />
                <span style={{ color:'#bcb3a3' }}>–</span>
                <TimeInputSm
                  value={ov?.end || sh.end}
                  muted={!has}
                  onChange={v=>setDay(w, { start: ov?.start || sh.start, end: v })}
                />
                {has ? (
                  <button onClick={()=>clearDay(w)} style={{
                    appearance:'none', border:0, background:'transparent', cursor:'pointer',
                    fontSize: 11, color:'#a09887', marginLeft:'auto',
                  }}>還原</button>
                ) : (
                  <span style={{ marginLeft:'auto', fontSize: 10, color:'#bcb3a3' }}>套用預設</span>
                )}
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}

function TimeInputSm({ value, onChange, muted }) {
  return (
    <input type="time" value={value} onChange={e=>onChange(e.target.value)} style={{
      border:'1px solid #e5dccb', borderRadius: 4,
      padding: '2px 4px', fontSize: 12, fontFamily:'ui-monospace, monospace',
      background:'#fff', color: muted ? '#a09887' : '#29261b',
      outline:'none', width: 86,
    }} />
  );
}

function SectionHeader({ title, hint }) {
  return (
    <div>
      <div style={{ fontSize: 14, fontWeight: 600, color:'#29261b', letterSpacing:'.02em' }}>{title}</div>
      {hint && <div style={{ fontSize: 12, color:'#a09887', marginTop: 4 }}>{hint}</div>}
    </div>
  );
}

function TimeInput({ value, onChange }) {
  return (
    <input type="time" value={value} onChange={e=>onChange(e.target.value)} style={{
      border:'1px solid #e5dccb', borderRadius: 6,
      padding: '5px 8px', fontSize: 13, fontFamily:'ui-monospace, monospace',
      background:'#fff', color:'#29261b', outline:'none', width: 100,
    }} />
  );
}

function durationOf(start, end) {
  const [sh,sm] = start.split(':').map(Number);
  const [eh,em] = end.split(':').map(Number);
  const mins = (eh*60+em) - (sh*60+sm);
  const h = Math.floor(mins/60), m = mins%60;
  return m ? `${h}小時${m}分` : `${h}小時`;
}

function DateListEditor({ label, dates, onChange, tone, accent }) {
  const [draft, setDraft] = React.useState('');
  const bg  = tone === 'rest' ? '#fce8d9' : '#daedda';
  const fg  = tone === 'rest' ? '#7a4318' : '#2a5b2e';
  const add = () => { if (draft && !dates.includes(draft)) { onChange([...dates, draft].sort()); setDraft(''); } };
  return (
    <div style={{
      background:'#fff', border:'1px solid #ebe4d8', borderRadius: 10,
      padding: 14, display:'flex', flexDirection:'column', gap: 10,
    }}>
      <div style={{ fontSize: 13, fontWeight: 600, color:'#29261b' }}>{label}</div>
      <div style={{ display:'flex', gap: 6 }}>
        <input type="date" value={draft} onChange={e=>setDraft(e.target.value)} style={{
          flex:1, border:'1px solid #e5dccb', borderRadius: 6,
          padding: '6px 8px', fontSize: 13, color:'#29261b', background:'#fff',
        }} />
        <button onClick={add} style={{
          appearance:'none', border:0, background: accent, color:'#fff',
          padding:'6px 14px', borderRadius: 6, fontSize: 13, cursor:'pointer', fontWeight: 500,
        }}>新增</button>
      </div>
      <div style={{ display:'flex', flexWrap:'wrap', gap: 6, minHeight: 28 }}>
        {dates.length === 0 && <div style={{ fontSize:12, color:'#bcb3a3' }}>— 尚未設定 —</div>}
        {dates.map(d => (
          <span key={d} style={{
            display:'inline-flex', alignItems:'center', gap: 6,
            background: bg, color: fg, padding:'3px 8px', borderRadius: 10, fontSize: 12,
          }}>
            {d}
            <button onClick={()=>onChange(dates.filter(x=>x!==d))} style={{
              appearance:'none', border:0, background:'transparent', cursor:'pointer',
              color: fg, opacity: .55, fontSize: 14, lineHeight: 1, padding: 0,
            }}>×</button>
          </span>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { ShiftDefsPage });
