// Announcements (admin-pinned notices on calendar dates)

window.getAnnouncementsForDate = function(date, data) {
  if (!data.announcements || !data.announcements.length) return [];
  const iso = window.APP_HELPERS.fmtISO(date);
  return data.announcements.filter(a => iso >= a.from && iso <= (a.to || a.from));
};

const ANN_COLORS = [
  { v: '#dc2626', label: 'แดง' },
  { v: '#ea580c', label: 'ส้ม' },
  { v: '#ca8a04', label: 'เหลือง' },
  { v: '#16a34a', label: 'เขียว' },
  { v: '#2563eb', label: 'น้ำเงิน' },
  { v: '#7c3aed', label: 'ม่วง' },
  { v: '#475569', label: 'เทา' },
];
const ANN_ICONS = ['megaphone','star','flag','info','sparkle','alert','bell','calendar'];

const AnnouncementModal = ({ onClose, date, edit, refresh }) => {
  const helpers = window.APP_HELPERS;
  const defaultDate = edit?.from || (date ? helpers.fmtISO(date) : helpers.fmtISO(new Date()));
  const [from, setFrom] = React.useState(defaultDate);
  const [to, setTo]     = React.useState(edit?.to || defaultDate);
  const [title, setTitle] = React.useState(edit?.title || '');
  const [body, setBody]   = React.useState(edit?.body || '');
  const [color, setColor] = React.useState(edit?.color || '#dc2626');
  const [icon, setIcon]   = React.useState(edit?.icon || 'megaphone');
  const [busy, setBusy]   = React.useState(false);
  const [err, setErr]     = React.useState(null);

  const canSave = title.trim() && from && (!to || to >= from);

  const save = async () => {
    setErr(null); setBusy(true);
    try {
      const payload = { from, to: to || from, title: title.trim(), body, color, icon };
      if (edit) await window.API.updateAnnouncement(edit.id, payload);
      else      await window.API.createAnnouncement(payload);
      if (refresh) await refresh();
      onClose();
    } catch (e) { setErr(e.message); setBusy(false); }
  };

  const doDelete = async () => {
    if (!confirm(`ลบประกาศ "${edit.title}" ?`)) return;
    setBusy(true);
    try {
      await window.API.deleteAnnouncement(edit.id);
      if (refresh) await refresh();
      onClose();
    } catch (e) { setErr(e.message); setBusy(false); }
  };

  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">{edit ? 'แก้ไขประกาศ' : 'เพิ่มประกาศพิเศษ'}</div>
            <div className="text-xs muted mt-2">ติดประกาศบนปฏิทินสำหรับวันใดวันหนึ่ง หรือช่วงวันที่กำหนด</div>
          </div>
          <button className="icon-btn" onClick={onClose}><Icon name="x"/></button>
        </div>
        <div className="modal-body">
          {/* Preview */}
          <div className="row" style={{ gap:10, padding:'10px 12px', background:'var(--ink-50)', borderRadius:8, marginBottom:14 }}>
            <span style={{ width:32, height:32, borderRadius:8, background:color, color:'white', display:'inline-grid', placeItems:'center', flexShrink:0 }}>
              <Icon name={icon} size={16}/>
            </span>
            <div style={{ flex:1, minWidth:0 }}>
              <div style={{ fontWeight:600, fontSize:14 }}>{title || 'หัวข้อประกาศ'}</div>
              <div className="text-xs muted" style={{ marginTop:2 }}>
                {helpers.fmtThaiDate(from, { shortMonth:true })}
                {to && to !== from && ` – ${helpers.fmtThaiDate(to, { shortMonth:true })}`}
              </div>
              {body && <div className="text-xs muted mt-2" style={{ whiteSpace:'pre-wrap' }}>{body}</div>}
            </div>
          </div>

          <div className="field-row">
            <div className="field">
              <label>ตั้งแต่วันที่</label>
              <input type="date" value={from} onChange={e => { setFrom(e.target.value); if (to < e.target.value) setTo(e.target.value); }}/>
            </div>
            <div className="field">
              <label>ถึงวันที่ (เว้นว่าง = วันเดียว)</label>
              <input type="date" value={to} onChange={e => setTo(e.target.value)}/>
            </div>
          </div>

          <div className="field">
            <label>หัวข้อประกาศ</label>
            <input type="text" value={title} onChange={e => setTitle(e.target.value)} placeholder="เช่น ประชุมทีม, โปรโมชั่นใหญ่, วันรับสินค้า" maxLength={80}/>
          </div>

          <div className="field">
            <label>รายละเอียด (ไม่บังคับ)</label>
            <textarea value={body} onChange={e => setBody(e.target.value)} placeholder="ระบุรายละเอียดเพิ่มเติม ทุกคนจะเห็นบนปฏิทิน" style={{ minHeight: 70 }}/>
          </div>

          <div className="field">
            <label>สี</label>
            <div className="row" style={{ flexWrap:'wrap', gap:6 }}>
              {ANN_COLORS.map(c => (
                <button key={c.v} type="button" onClick={() => setColor(c.v)} title={c.label}
                  style={{
                    width:28, height:28, borderRadius:'50%', background:c.v,
                    border: color === c.v ? '3px solid var(--ink-900)' : '2px solid white',
                    boxShadow: color === c.v ? '0 0 0 1px var(--ink-300)' : '0 1px 3px rgba(0,0,0,.1)',
                    cursor:'pointer',
                  }}/>
              ))}
            </div>
          </div>

          <div className="field">
            <label>ไอคอน</label>
            <div className="row" style={{ flexWrap:'wrap', gap:6 }}>
              {ANN_ICONS.map(ic => (
                <button key={ic} type="button" onClick={() => setIcon(ic)}
                  style={{
                    width:36, height:36, borderRadius:8,
                    background: icon === ic ? 'var(--brand-50)' : 'var(--paper)',
                    border: icon === ic ? '2px solid var(--brand-600)' : '1px solid var(--ink-200)',
                    color: icon === ic ? 'var(--brand-700)' : 'var(--ink-600)',
                    cursor:'pointer', display:'inline-grid', placeItems:'center',
                  }}>
                  <Icon name={ic} size={16}/>
                </button>
              ))}
            </div>
          </div>

          {err && <div style={{ background:'#fef2f2', color:'#b91c1c', padding:'8px 12px', borderRadius:8, fontSize:12 }}>{err}</div>}
        </div>
        <div className="modal-footer">
          {edit && (
            <button className="btn btn-danger btn-sm" style={{ marginRight:'auto' }} onClick={doDelete} disabled={busy}>
              <Icon name="trash" size={13}/> ลบประกาศ
            </button>
          )}
          <button className="btn btn-ghost" onClick={onClose} disabled={busy}>ยกเลิก</button>
          <button className="btn btn-primary" disabled={!canSave || busy} onClick={save}>
            <Icon name="check" size={14}/> {busy ? 'กำลังบันทึก…' : (edit ? 'บันทึก' : 'เพิ่มประกาศ')}
          </button>
        </div>
      </div>
    </div>
  );
};

window.AnnouncementModal = AnnouncementModal;
