/* ============================================================
   VLF 2026 · OPS TASK REPORT — deadline · focus · báo cáo ảnh
   DeadlinePill  — chip hạn chót + đếm ngược / trễ bao lâu
   TaskFocus     — banner "việc cần làm bây giờ" khi mở nhiệm vụ
   DoneStamp     — mốc thời gian hoàn thành
   TaskReport    — cập nhật tiến độ + chụp/đính nhiều ảnh báo cáo
   Xuất: DeadlinePill, TaskFocus, DoneStamp, TaskReport
   ============================================================ */

/* ---- chip hạn chót: Trễ hạn · Sắp tới hạn · Trong hạn · Cả ngày ---- */
function DeadlinePill({ task, big }) {
  const lang = useLang();
  const O = window.VLF.ops;
  const info = O.deadlineInfo(task);
  const m = O.deadlineMeta[info.state];
  const ic = info.state === 'overdue' ? 'bell' : info.state === 'done' ? 'check' : 'clock';
  return (
    <span className={'ops-dl' + (big ? ' big' : '') + (info.state === 'overdue' ? ' pulse' : '')} style={{ color: m.c, background: m.bg }}>
      <Icon name={ic} size={big ? 14 : 12} sw={2.1} />
      {info.endLabel ? <b>{info.endLabel}</b> : <b>{trL(lang, O.deadlineMeta.allday)}</b>}
      <span className="ops-dl-left">· {O.leftLabel(info, lang)}</span>
    </span>);
}

/* ---- mốc hoàn thành ---- */
function DoneStamp({ task, store }) {
  const lang = useLang();
  const at = store.doneAt[task.id];
  if (task.status !== 'done' || !at) return null;
  return (
    <div className="ops-doneStamp">
      <Icon name="check" size={16} sw={2.6} />
      <span>{trL(lang, { vi: 'Hoàn thành lúc', en: 'Completed at' })} <b>{at}</b></span>
    </div>);
}

/* ---- banner: mở ra biết focus làm gì ---- */
function TaskFocus({ task, store, onJumpReport }) {
  const lang = useLang();
  const O = window.VLF.ops;
  const info = O.deadlineInfo(task);
  if (task.status === 'done') {
    return (
      <div className="ops-focus done">
        <div className="ops-focus-ic"><Icon name="check" size={18} sw={2.6} /></div>
        <div className="ops-focus-b">
          <div className="lbl">{trL(lang, { vi: 'Nhiệm vụ đã hoàn thành', en: 'Task completed' })}</div>
          <div className="now">{store.doneAt[task.id] ? trL(lang, { vi: 'Đã đánh dấu xong lúc ' + store.doneAt[task.id], en: 'Marked done at ' + store.doneAt[task.id] }) : trL(lang, { vi: 'Tất cả việc con đã xong', en: 'All sub-tasks done' })}</div>
        </div>
      </div>);
  }
  const nextIdx = task.steps.findIndex((s) => !s.done);
  const next = nextIdx >= 0 ? task.steps[nextIdx] : null;
  const m = O.deadlineMeta[info.state];
  return (
    <div className={'ops-focus ' + info.state}>
      <div className="ops-focus-ic" style={{ color: m.c, background: m.bg }}><Icon name={info.state === 'overdue' ? 'bell' : 'check'} size={18} sw={2.1} /></div>
      <div className="ops-focus-b">
        <div className="lbl">{trL(lang, { vi: 'Việc cần làm tiếp', en: 'Do next' })}</div>
        <div className="now">{next ? trL(lang, next.t) : trL(lang, { vi: 'Việc con đã xong — đánh dấu “Xong” hoặc gửi báo cáo ảnh.', en: 'Sub-tasks done — mark “Done” or post a photo report.' })}</div>
      </div>
      {next
        ? <button className="ops-focus-go" onClick={() => store.toggleStep(task.id, nextIdx)}>{trL(lang, { vi: 'Xong việc này', en: 'Done' })}</button>
        : <button className="ops-focus-go" onClick={onJumpReport}>{trL(lang, { vi: 'Báo cáo', en: 'Report' })}</button>}
    </div>);
}

/* ---- xem ảnh phóng to ---- */
function PhotoLightbox({ src, onClose }) {
  if (!src) return null;
  return ReactDOM.createPortal(
    <div className="ops-lightbox" onClick={onClose}>
      <button className="ops-lightbox-x" onClick={onClose} aria-label="close"><Icon name="x" size={22} sw={2.2} /></button>
      <img src={src} alt="report" />
    </div>, document.querySelector('.za-screen') || document.body);
}

/* ---- CẬP NHẬT TIẾN ĐỘ + ẢNH BÁO CÁO (nhiều ảnh) ---- */
function TaskReport({ taskId, store, team }) {
  const lang = useLang();
  const O = window.VLF.ops;
  const me = window.VLF.staffRoleById(store.meRole).me;
  const reports = store.reports[taskId] || [];
  const [note, setNote] = useState('');
  const [photos, setPhotos] = useState([]); // [{id, src}]
  const [zoom, setZoom] = useState(null);
  const fileRef = React.useRef(null);

  function addFiles(fileList) {
    const files = Array.from(fileList || []).filter((f) => f.type.startsWith('image/')).slice(0, 8);
    files.forEach((f) => {
      const rd = new FileReader();
      rd.onload = () => setPhotos((s) => [...s, { id: 'p' + Date.now() + Math.random().toString(36).slice(2, 6), src: rd.result }]);
      rd.readAsDataURL(f);
    });
  }
  function removePhoto(id) { setPhotos((s) => s.filter((p) => p.id !== id)); }
  function submit() {
    if (!note.trim() && photos.length === 0) return;
    store.addReport(taskId, {
      id: 'rp' + Date.now(), by: me, team: team.id, at: window.OPS_NOW,
      note: note.trim(), photos: photos.map((p) => p.src),
    });
    setNote(''); setPhotos([]);
  }

  return (
    <>
      <SectionHead title={trL(lang, { vi: 'Cập nhật & ảnh báo cáo', en: 'Updates & photo report' })} right={reports.length ? <span className="v-muted" style={{ fontSize: 12 }}>{reports.length} {trL(lang, { vi: 'lần', en: 'updates' })}</span> : null} />

      {/* compose */}
      <div className="v-card ops-report-compose">
        <textarea className="ops-input ops-report-note" rows={2} value={note} onChange={(e) => setNote(e.target.value)}
          placeholder={trL(lang, { vi: 'Cập nhật tiến độ / tình trạng tại hiện trường…', en: 'Update progress / on-site status…' })} />

        {photos.length > 0 && (
          <div className="ops-report-thumbs">
            {photos.map((p) => (
              <span className="ops-report-thumb" key={p.id}>
                <img src={p.src} alt="" onClick={() => setZoom(p.src)} />
                <button className="rm" onClick={() => removePhoto(p.id)} aria-label="remove"><Icon name="x" size={12} sw={2.6} /></button>
              </span>
            ))}
          </div>
        )}

        <div className="ops-report-actions">
          <input ref={fileRef} type="file" accept="image/*" multiple capture="environment" style={{ display: 'none' }} onChange={(e) => { addFiles(e.target.files); e.target.value = ''; }} />
          <button className="ops-report-attach" onClick={() => fileRef.current && fileRef.current.click()}>
            <Icon name="qr" size={17} sw={1.9} />{trL(lang, { vi: 'Chụp / thêm ảnh', en: 'Photo / attach' })}{photos.length > 0 ? ' · ' + photos.length : ''}
          </button>
          <button className={'ops-report-send' + (!note.trim() && photos.length === 0 ? ' off' : '')} onClick={submit}>
            <Icon name="check" size={16} sw={2.4} />{trL(lang, { vi: 'Gửi báo cáo', en: 'Post' })}
          </button>
        </div>
      </div>

      {/* lịch sử báo cáo */}
      {reports.length > 0 && (
        <div className="v-card ops-report-log">
          {reports.map((r) => (
            <div className="ops-report-item" key={r.id}>
              <OpsAva name={r.by} size={30} />
              <div className="ops-report-body">
                <div className="ops-report-head"><b>{r.by}</b>{r.team && <TeamChip id={r.team} lang={lang} small />}<span className="at">{r.at}</span></div>
                {r.note && <div className="ops-report-tx">{r.note}</div>}
                {r.photos && r.photos.length > 0 && (
                  <div className="ops-report-grid">
                    {r.photos.map((src, i) => <button className="ops-report-cell" key={i} onClick={() => setZoom(src)}><img src={src} alt="" /></button>)}
                  </div>
                )}
              </div>
            </div>
          ))}
        </div>
      )}

      <PhotoLightbox src={zoom} onClose={() => setZoom(null)} />
    </>);
}

Object.assign(window, { DeadlinePill, DoneStamp, TaskFocus, TaskReport });
