// Employee "My Quota" page

const MyQuotaPage = ({ data, currentUser, openModal }) => {
  const empLeaves = data.leaves.filter(l => l.empId === currentUser.id);
  const used = {
    vacation: empLeaves.filter(l => l.type === 'vacation' && l.status === 'approved').reduce((s,l) => s+l.days, 0),
    personal: empLeaves.filter(l => l.type === 'personal' && l.status === 'approved').reduce((s,l) => s+l.days, 0),
    sick: empLeaves.filter(l => l.type === 'sick' && l.status === 'approved').reduce((s,l) => s+l.days, 0),
  };
  const quota = data.settings.leaveQuota;
  const otHours = data.otRequests.filter(o => o.empId === currentUser.id && o.status === 'approved').reduce((s,o) => s+o.hours, 0);

  // Special offs used this month
  const today = new Date();
  const specialUsed = data.specialOffs.filter(s => {
    const d = new Date(s.date);
    return s.empId === currentUser.id && d.getMonth() === today.getMonth();
  });
  const myQuota = data.settings.perEmployeeSpecial?.[currentUser.id] ?? currentUser.specialOffMonthly ?? data.settings.specialOffPerMonth;

  return (
    <div data-screen-label="My Quota">
      <div className="row between mb-3">
        <div>
          <div style={{ fontSize: 20, fontWeight: 700, letterSpacing: '-.02em' }}>โควต้าวันลาของฉัน</div>
          <div className="text-sm muted">{currentUser.name} · ปี 2569</div>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 14, marginBottom: 18 }}>
        <BigQuotaCard cls="vac" icon="vacationV" label="พักร้อน (Vacation)" used={used.vacation} quota={quota.vacation}/>
        <BigQuotaCard cls="pers" icon="coffee" label="ลากิจ (Personal)" used={used.personal} quota={quota.personal}/>
        <BigQuotaCard cls="sick" icon="pill" label="ลาป่วย (Sick)" used={used.sick} quota={quota.sick}/>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20 }}>
        <div className="card">
          <div className="card-header">
            <div>
              <div className="card-title">วันหยุดพิเศษเดือนนี้</div>
              <div className="card-sub">เลือกได้ {myQuota} วัน/เดือน · เปลี่ยนได้ตลอด</div>
            </div>
            <button className="btn btn-primary btn-sm" disabled={specialUsed.length >= myQuota} onClick={() => openModal && openModal({ type: 'special-form' })}>
              <Icon name="plus" size={13}/> เลือกวันใหม่
            </button>
          </div>
          <div>
            {specialUsed.map((s, i) => (
              <div key={i} className="row" style={{ padding: '12px 18px', borderBottom: '1px solid var(--ink-100)', gap: 10 }}>
                <div className="type-icon special"><Icon name="star" size={14}/></div>
                <div className="flex-1">
                  <div style={{ fontWeight: 500 }}>{window.APP_HELPERS.fmtThaiDate(s.date, { full: true })}</div>
                  <div className="emp-meta">{s.note}</div>
                </div>
                <button className="icon-btn" style={{ width: 28, height: 28 }}><Icon name="edit" size={13}/></button>
                <button className="icon-btn" style={{ width: 28, height: 28, color: 'var(--sick)' }}><Icon name="trash" size={13}/></button>
              </div>
            ))}
            {specialUsed.length === 0 && myQuota > 0 && <div className="empty">ยังไม่ได้เลือกวันหยุดพิเศษเดือนนี้</div>}
            {myQuota === 0 && <div className="empty">ไม่มีสิทธิ์เลือกวันหยุดพิเศษ (โควต้า 0 วัน)</div>}
            {specialUsed.length < myQuota && myQuota > 0 && (
              <div style={{ padding: 14, background: 'var(--special-bg)', color: '#92400e', fontSize: 12, textAlign: 'center' }}>
                เลือกได้อีก {myQuota - specialUsed.length} วัน
              </div>
            )}
          </div>
        </div>

        <div className="card">
          <div className="card-header">
            <div>
              <div className="card-title">สรุปการทำงานของคุณ</div>
              <div className="card-sub">ปี 2569</div>
            </div>
          </div>
          <div className="card-body">
            <SummaryRow icon="sparkle" cls="ot"   label="ทำงาน OT" value={`${(otHours / 8).toFixed(otHours % 8 === 0 ? 0 : 1)} วัน`} sub={`= ${otHours} ชม. (8 ชม./วัน)`}/>
            <SummaryRow icon="swap"    cls="swap" label="สลับวันหยุด" value={`${data.swapRequests.filter(s => s.empId === currentUser.id && s.status === 'approved').length} ครั้ง`}/>
            <SummaryRow icon="vacationV" cls="vac"  label="ใช้พักร้อน" value={`${used.vacation}/${quota.vacation} วัน`} sub={`เหลือ ${quota.vacation - used.vacation} วัน`}/>
            <SummaryRow icon="coffee"  cls="pers" label="ใช้ลากิจ" value={`${used.personal}/${quota.personal} วัน`} sub={`เหลือ ${quota.personal - used.personal} วัน`}/>
            <SummaryRow icon="pill"    cls="sick" label="ใช้ลาป่วย" value={`${used.sick}/${quota.sick} วัน`} sub={`เหลือ ${quota.sick - used.sick} วัน`}/>
          </div>
        </div>
      </div>

      <div className="card mt-4">
        <div className="card-header">
          <div>
            <div className="card-title">ประวัติการลาทั้งหมด</div>
          </div>
        </div>
        <table className="t">
          <thead>
            <tr>
              <th>ประเภท</th>
              <th>วันที่</th>
              <th className="num">วัน</th>
              <th>เหตุผล</th>
              <th>สถานะ</th>
            </tr>
          </thead>
          <tbody>
            {empLeaves.map(l => {
              const meta = window.TYPE_LABEL[l.type];
              return (
                <tr key={l.id}>
                  <td><span className={`chip chip-${meta.cls}`}><Icon name={meta.icon} size={11}/>{meta.th}</span></td>
                  <td className="text-sm num">
                    {window.APP_HELPERS.fmtThaiDate(l.from, {shortMonth:true})}
                    {l.from !== l.to && ` – ${window.APP_HELPERS.fmtThaiDate(l.to, {shortMonth:true})}`}
                  </td>
                  <td className="num">{l.days}</td>
                  <td className="text-sm muted">{l.reason}</td>
                  <td><span className={`chip chip-${l.status === 'approved' ? 'approved' : 'pending'}`}><span className="chip-dot"/>{l.status === 'approved' ? 'อนุมัติ' : 'รออนุมัติ'}</span></td>
                </tr>
              );
            })}
            {empLeaves.length === 0 && <tr><td colSpan="5" className="empty">ยังไม่มีประวัติการลา</td></tr>}
          </tbody>
        </table>
      </div>
    </div>
  );
};

const BigQuotaCard = ({ cls, icon, label, used, quota }) => {
  const pct = Math.min(100, (used / quota) * 100);
  return (
    <div className="card" style={{ padding: 20 }}>
      <div className="row between mb-3">
        <div className={`type-icon ${cls}`} style={{ width: 36, height: 36 }}>
          <Icon name={icon} size={16}/>
        </div>
        <div className="text-xs muted">โควต้าประจำปี</div>
      </div>
      <div className="text-sm muted mb-2">{label}</div>
      <div style={{ fontSize: 30, fontWeight: 700, fontFamily: 'var(--font-en)', letterSpacing: '-.02em' }}>
        {quota - used}<span style={{ fontSize: 14, color: 'var(--ink-400)', fontWeight: 500 }}> / {quota} วัน</span>
      </div>
      <div className="text-xs muted mt-2 mb-2">ใช้ไปแล้ว {used} วัน</div>
      <div className="bar"><span style={{ width: `${pct}%`, background: `var(--${cls === 'vac' ? 'vac' : cls === 'pers' ? 'pers' : 'sick'})` }}/></div>
    </div>
  );
};

const SummaryRow = ({ icon, cls, label, value, sub }) => (
  <div className="row" style={{ padding: '10px 0', borderBottom: '1px dashed var(--ink-100)', gap: 12 }}>
    <div className={`type-icon ${cls}`}><Icon name={icon} size={14}/></div>
    <div className="flex-1 text-sm">{label}</div>
    <div style={{ textAlign: 'right' }}>
      <div style={{ fontWeight: 600 }}>{value}</div>
      {sub && <div className="text-xs muted">{sub}</div>}
    </div>
  </div>
);

// ───── Special Off Request Modal ─────
const SpecialOffModal = ({ onClose, currentUser, data, refresh }) => {
  const [busy, setBusy] = React.useState(false);
  const submit = async () => {
    setBusy(true);
    try {
      await window.API.createSpecialOff({ date, note });
      if (refresh) await refresh();
      onClose();
    } catch (e) { alert(e.message); setBusy(false); }
  };
  const helpers = window.APP_HELPERS;

  // Default: pick next allowed day (in specialOffAllowedDays) from today
  const allowedDays = data.settings.specialOffAllowedDays || [6];
  const findNextAllowedDay = () => {
    const today = new Date(2026, 4, 22);
    for (let i = 1; i <= 60; i++) {
      const d = new Date(today.getTime() + i * 86400000);
      const isHol = helpers.isHoliday(d, data.holidays);
      if (data.settings.workDays.includes(d.getDay()) && !isHol && allowedDays.includes(d.getDay())) {
        return helpers.fmtISO(d);
      }
    }
    return helpers.fmtISO(today);
  };

  const [date, setDate] = React.useState(findNextAllowedDay());
  const [note, setNote] = React.useState('');

  const d = helpers.parseISO(date);
  const isHol = helpers.isHoliday(d, data.holidays);
  const isWorkDay = data.settings.workDays.includes(d.getDay()) && !isHol;
  const isAllowedDay = allowedDays.includes(d.getDay());
  const DAYS_LONG = ['อาทิตย์','จันทร์','อังคาร','พุธ','พฤหัสบดี','ศุกร์','เสาร์'];

  // Check headcount
  const head = window.getHeadcount(d, data);
  const minStaff = data.settings.minStaffPerDay;
  const headOk = head.working - 1 >= minStaff;

  // Quota check
  const myQuota = data.settings.perEmployeeSpecial?.[currentUser.id] ?? currentUser.specialOffMonthly ?? data.settings.specialOffPerMonth;
  const usedThisMonth = data.specialOffs.filter(s => {
    const sd = helpers.parseISO(s.date);
    return s.empId === currentUser.id && sd.getMonth() === d.getMonth() && sd.getFullYear() === d.getFullYear();
  }).length;
  const quotaOk = usedThisMonth < myQuota;

  // Check if employee already has special-off in target month
  const monthLabel = helpers.TH_MONTHS[d.getMonth()];
  const canSubmit = isWorkDay && isAllowedDay && headOk && quotaOk;

  // Suggested next allowed days (in specialOffAllowedDays only)
  const suggestions = [];
  let cursor = new Date(2026, 4, 22);
  let safety = 0;
  while (suggestions.length < 5 && safety < 90) {
    safety++;
    cursor = new Date(cursor.getTime() + 86400000);
    const isH = helpers.isHoliday(cursor, data.holidays);
    if (data.settings.workDays.includes(cursor.getDay()) && !isH && allowedDays.includes(cursor.getDay())) {
      const cHead = window.getHeadcount(cursor, data);
      suggestions.push({ date: helpers.fmtISO(cursor), staff: cHead.working });
    }
  }

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()} style={{ maxWidth: 560 }}>
        <div className="modal-header">
          <div>
            <div className="modal-title">ขอวันหยุดพิเศษส่วนตัว</div>
            <div className="text-xs muted mt-2">{currentUser.name} · {currentUser.role}</div>
          </div>
          <button className="icon-btn" onClick={onClose}><Icon name="x"/></button>
        </div>
        <div className="modal-body">
          <div className="row" style={{ background: 'var(--special-bg)', padding: 12, borderRadius: 8, gap: 10, marginBottom: 16 }}>
            <Icon name="star" size={16} style={{ color: 'var(--special)' }}/>
            <div className="text-sm" style={{ color: '#92400e' }}>
              ได้ <strong>{myQuota} วัน/เดือน</strong> · เดือน{monthLabel}ใช้ไปแล้ว <strong>{usedThisMonth}/{myQuota}</strong> วัน · อนุญาตเฉพาะวัน<strong>{allowedDays.map(i => DAYS_LONG[i]).join(', ')}</strong>
            </div>
          </div>

          <div className="field">
            <label>เลือกวันหยุด (ต้องเป็นวัน{allowedDays.map(i => DAYS_LONG[i]).join('/')})</label>
            <input type="date" value={date} onChange={e => setDate(e.target.value)}/>
            <div className="field-help">
              {window.APP_HELPERS.fmtThaiDate(date, { full: true })}
            </div>
          </div>

          <div className="day-section-title" style={{ marginTop: 4 }}>วันแนะนำ</div>
          <div className="row" style={{ flexWrap: 'wrap', gap: 6, marginBottom: 14 }}>
            {suggestions.map(s => {
              const sd = helpers.parseISO(s.date);
              const active = s.date === date;
              return (
                <button
                  key={s.date}
                  onClick={() => setDate(s.date)}
                  style={{
                    padding: '8px 12px',
                    borderRadius: 8,
                    border: active ? '2px solid var(--brand-600)' : '1px solid var(--ink-200)',
                    background: active ? 'var(--brand-50)' : 'var(--paper)',
                    color: active ? 'var(--brand-700)' : 'var(--ink-700)',
                    fontSize: 12,
                    fontWeight: 500,
                  }}
                >
                  <div className="num" style={{ fontWeight: 700 }}>{sd.getDate()} {helpers.TH_MONTHS_SHORT[sd.getMonth()]}</div>
                  <div className="text-xs muted" style={{ marginTop: 2 }}>คนเข้างาน {s.staff}</div>
                </button>
              );
            })}
          </div>

          <div className="day-section-title">ตรวจสอบเงื่อนไข</div>
          <ConditionRow ok={isAllowedDay} label={isAllowedDay ? `เป็นวัน${DAYS_LONG[d.getDay()]} — อยู่ในวันที่อนุญาต ✓` : `ผู้ดูแลระบบอนุญาตให้ใช้หยุดพิเศษเฉพาะวัน${allowedDays.map(i => DAYS_LONG[i]).join('/')} — วัน${DAYS_LONG[d.getDay()]}ใช้ไม่ได้`}/>
          <ConditionRow ok={isWorkDay} label={isWorkDay ? 'เป็นวันทำงานปกติ ✓' : (isHol ? `เป็นวันนักขัตฤกษ์ (${isHol.name}) — ใช้วันหยุดพิเศษไม่ได้` : 'เป็นวันหยุดประจำสัปดาห์ — ใช้วันหยุดพิเศษไม่ได้')}/>
          <ConditionRow ok={quotaOk} label={quotaOk ? `โควต้าเดือน${monthLabel}เหลือ ${myQuota - usedThisMonth} วัน ✓` : `เกินโควต้าเดือน${monthLabel} (${usedThisMonth}/${myQuota} วัน)`}/>
          <ConditionRow ok={headOk} label={headOk ? `จะเหลือพนักงานเข้างาน ${head.working - 1} คน (ขั้นต่ำ ${minStaff}) ✓` : `จะเหลือพนักงานเข้างานต่ำกว่า ${minStaff} คน — ไม่อนุญาต`}/>

          <div className="field mt-4">
            <label>หมายเหตุ (ถ้ามี)</label>
            <textarea value={note} onChange={e => setNote(e.target.value)} placeholder="เช่น วันเกิด, พาแม่ไปหาหมอ, ธุระส่วนตัว..."/>
          </div>

          <div className="text-xs muted">
            <Icon name="info" size={12}/> วันหยุดพิเศษจะแสดงในปฏิทินทีมทันทีหลังบันทึก · เปลี่ยน/ยกเลิกได้ก่อนถึงวันจริง
          </div>
        </div>
        <div className="modal-footer">
          <button className="btn btn-ghost" onClick={onClose} disabled={busy}>ยกเลิก</button>
          <button className="btn btn-primary" disabled={!canSubmit || busy} onClick={submit}>
            <Icon name="check" size={14}/> {busy ? 'กำลังบันทึก…' : 'ยืนยันเลือกวันหยุด'}
          </button>
        </div>
      </div>
    </div>
  );
};

const ConditionRow = ({ ok, label }) => (
  <div className="row" style={{ padding: '7px 10px', gap: 10, borderRadius: 7, background: ok ? 'var(--swap-bg)' : 'var(--sick-bg)', marginBottom: 6 }}>
    <Icon name={ok ? 'check' : 'alert'} size={14} style={{ color: ok ? 'var(--swap)' : 'var(--sick)' }}/>
    <span className="text-sm" style={{ color: ok ? 'var(--swap)' : 'var(--sick)' }}>{label}</span>
  </div>
);

window.MyQuotaPage = MyQuotaPage;
window.SpecialOffModal = SpecialOffModal;
