// Project Update Center — the primary admin workflow & single source of truth.
// Creating/editing an update drives Activity, Dashboard & Reporting.
(function () {
  window.SCREENS = window.SCREENS || {};
  const { useState, useRef } = React;
  const IC = window.IC, D = window.DATA;
  const selStyle = { border:0, background:"none", outline:"none", font:"inherit", fontSize:13.5, flex:1, color:"var(--ink)" };
  const TH_FULL = ["มกราคม","กุมภาพันธ์","มีนาคม","เมษายน","พฤษภาคม","มิถุนายน","กรกฎาคม","สิงหาคม","กันยายน","ตุลาคม","พฤศจิกายน","ธันวาคม"];
  const TH_ABBR = ["ม.ค.","ก.พ.","มี.ค.","เม.ย.","พ.ค.","มิ.ย.","ก.ค.","ส.ค.","ก.ย.","ต.ค.","พ.ย.","ธ.ค."];

  function todayISO() { const d = new Date(); return d.getFullYear() + "-" + String(d.getMonth()+1).padStart(2,"0") + "-" + String(d.getDate()).padStart(2,"0"); }
  // ISO → "04 มิถุนายน 2569" (Buddhist Era, zero-padded day, full Thai month)
  function isoToBE(iso) { if (!iso) return ""; const d = new Date(iso + "T00:00:00"); if (isNaN(d)) return iso; return String(d.getDate()).padStart(2,"0") + " " + TH_FULL[d.getMonth()] + " " + (d.getFullYear() + 543); }

  function typeMeta(t) { return D.updateTypes[t] || D.updateTypes.general; }
  function phaseNameOf(u) { const det = D.detail[u.projectId]; if (!det || !u.phaseId) return ""; const ph = det.phases.find((p) => p.id === u.phaseId); return ph ? ph.name : ""; }

  // Hoisted to module scope so inputs keep focus across re-renders.
  function Field({ label, children }) {
    return (<label className="login-field"><span>{label}</span><div className="login-input">{children}</div></label>);
  }

  // ── Reusable Update card (full record display, no progress) ─
  function UpdateCard({ u, showProject, onEdit }) {
    const m = typeMeta(u.type);
    const phName = phaseNameOf(u);
    const boxDay = u.dateISO ? String(new Date(u.dateISO + "T00:00:00").getDate()).padStart(2,"0") : (u.date || "").split(" ")[0];
    const boxMon = u.dateISO ? TH_ABBR[new Date(u.dateISO + "T00:00:00").getMonth()] : (u.date || "").split(" ")[1];
    return (
      <div className="meet-card" style={{ cursor: "default" }}>
        <div className="meet-h" style={{ cursor: "default" }}>
          <div className="meet-cal" style={{ background: "var(--raised2)" }}><b className="tnum">{boxDay}</b><span>{boxMon}</span></div>
          <div className="meet-info">
            <div className="meet-title" style={{ wordBreak:"break-word", overflowWrap:"anywhere" }}>{u.title}</div>
            {u.detail && <div className="meet-meta" style={{ whiteSpace: "normal" }}><window.ExpandableText text={u.detail} lines={3} title={u.title} /></div>}
            <div className="meet-meta" style={{ marginTop: 2 }}>{IC.cal} {u.date}{u.assignee ? <> · {IC.user} ผู้รับเรื่อง: <b style={{ color: "var(--ink2)" }}>{u.assignee}</b></> : null}</div>
            <div className="meet-tags">
              <span className={"pill " + m.tone}><i />{m.th}</span>
              {showProject && u.project && <span className="pill neutral"><i />{u.project}</span>}
              {phName && <span className="pill neutral"><i />{phName}</span>}
              {u.impact && <span className="pill warn"><i />{u.impact}</span>}
              {u.attachment && (/^https?:\/\//.test(u.attachment)
                ? <a className="pill neutral" href={u.attachment} target="_blank" rel="noopener" onClick={(e) => e.stopPropagation()}><i />{IC.doc} เปิดไฟล์แนบ</a>
                : <span className="pill neutral"><i />{IC.doc} {u.attachment}</span>)}
            </div>
          </div>
          {onEdit && <button className="icon-btn" title="แก้ไขอัปเดต" onClick={() => onEdit(u)} style={{ width: 32, height: 32, alignSelf: "flex-start" }}>{IC.settings}</button>}
        </div>
      </div>
    );
  }
  window.UpdateCard = UpdateCard;

  // ── Reusable Update modal (create + edit) ─────────────────
  function UpdateModal({ edit, fixedProjectId, onClose, onDone }) {
    const isEdit = !!edit;
    const initPid = isEdit ? edit.projectId : (fixedProjectId || (D.projects[0] || {}).id || "");
    const [f, setF, safeClose, restoredDraft] = window.useDirty({
      projectId: initPid,
      dateISO: isEdit ? (edit.dateISO || todayISO()) : todayISO(),
      type: isEdit ? edit.type : "progress",
      title: isEdit ? edit.title : "",
      detail: isEdit ? (edit.detail || "") : "",
      impact: isEdit ? (edit.impact || "") : "",
      phaseId: isEdit ? (edit.phaseId || "") : "",
      assignee: isEdit ? (edit.assignee || "") : "",
      attachment: isEdit ? (edit.attachment || "") : "",
    }, onClose, isEdit ? null : { draftKey: "update-create-" + initPid });
    const [saving, setSaving] = useState(false);
    const fileRef = useRef(null);
    const fileBlobRef = useRef(null);
    const set = (k) => (e) => setF((p) => ({ ...p, [k]: e.target.value }));
    const det = D.detail[f.projectId];
    const phases = (det && det.phases) || [];
    const showProjectSelect = !fixedProjectId && !isEdit;
    const submit = async (e) => {
      e.preventDefault(); if (!f.title.trim()) return;
      setSaving(true);
      let attachment = f.attachment;
      if (fileBlobRef.current && window.Files) {
        const up = await window.Files.safeUpload(fileBlobRef.current, { projectId: f.projectId, kind: "updates" });
        attachment = up.url || up.name || attachment;
      }
      const payload = { ...f, date: isoToBE(f.dateISO), attachment };
      if (isEdit) await window.DB.updateUpdate(edit.id, payload);
      else { await window.DB.createUpdate(payload); window.clearDraft("update-create-" + f.projectId); }
      setSaving(false);
      window.toast(isEdit ? "แก้ไขอัปเดตแล้ว" : "บันทึกอัปเดตโครงการแล้ว");
      onDone && onDone(); onClose();
    };
    return (
      <div className="login-overlay" onClick={window.NOOP}>
        <form className="login-card" style={{ maxWidth:540, width:"94vw", maxHeight:"92vh", overflowY:"auto" }} onClick={(e) => e.stopPropagation()} onSubmit={submit}>
          <button type="button" className="login-x icon-btn" onClick={safeClose}>{IC.x}</button>
          <div className="login-badge">{IC.trend}</div>
          <h2>{isEdit ? "แก้ไขอัปเดตโครงการ" : "อัปเดตโครงการ"}</h2>
          <p style={{ marginTop:-4 }}>การอัปเดตจะเชื่อมเข้าสู่ความเคลื่อนไหว, Dashboard และรายงานโดยอัตโนมัติ</p>
          {!isEdit && restoredDraft && <div className="pill warn wrappable" style={{ marginTop: 8 }}><i />กู้คืนแบบร่างที่บันทึกไว้</div>}
          <div style={{ display:"grid", gap:11, marginTop:4 }}>
            {showProjectSelect && <Field label="โครงการ"><select value={f.projectId} onChange={(e) => setF((p) => ({ ...p, projectId: e.target.value, phaseId: "" }))} style={selStyle}>{D.projects.map((p) => <option key={p.id} value={p.id}>{p.name}</option>)}</select></Field>}
            <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:10 }}>
              <label className="login-field"><span>วันที่</span>
                <div className="login-input"><input type="date" lang="th" value={f.dateISO} onChange={set("dateISO")} style={selStyle} /></div>
                <span style={{ fontSize:12, color:"var(--muted)", marginTop:4 }}>{isoToBE(f.dateISO)}</span>
              </label>
              <Field label="ประเภทการอัปเดต"><select value={f.type} onChange={set("type")} style={selStyle}>{Object.keys(D.updateTypes).map((k) => <option key={k} value={k}>{D.updateTypes[k].th}</option>)}</select></Field>
            </div>
            <Field label="หัวข้อ *"><input value={f.title} onChange={set("title")} placeholder="เช่น เริ่มงานฐานราก / ได้รับ BOQ ใหม่" required /></Field>
            <label className="login-field"><span>รายละเอียด</span><div className="login-input" style={{ alignItems:"flex-start" }}><window.AutoTextarea value={f.detail} onChange={set("detail")} rows={3} placeholder="รายละเอียดของการอัปเดต" /></div></label>
            <Field label="ผลกระทบ"><input value={f.impact} onChange={set("impact")} placeholder="เช่น อาจกระทบ timeline 1 สัปดาห์ / เป็นไปตามแผน" /></Field>
            <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:10 }}>
              <Field label="Phase ที่เกี่ยวข้อง"><select value={f.phaseId} onChange={set("phaseId")} style={selStyle}><option value="">— ไม่ระบุ —</option>{phases.map((ph) => <option key={ph.id} value={ph.id}>{ph.name}</option>)}</select></Field>
              <Field label="ผู้รับเรื่อง">
                <input list="assignee-opts" value={f.assignee} onChange={set("assignee")} placeholder="พิมพ์หรือเลือก…" autoComplete="off" />
                <datalist id="assignee-opts">{(D.assignees || []).map((a) => <option key={a} value={a} />)}</datalist>
              </Field>
            </div>
            <input ref={fileRef} type="file" onChange={(e) => { const fl = e.target.files && e.target.files[0]; if (!fl) return; if (window.Files && fl.size > window.Files.MAX_BYTES) { window.toast("ไฟล์ใหญ่เกิน 100 MB"); return; } fileBlobRef.current = fl; setF((p) => ({ ...p, attachment: fl.name })); }} style={{ display:"none" }} />
            <button type="button" className="btn" style={{ width:"100%", justifyContent:"center", borderStyle:"dashed", padding:"11px" }} onClick={() => fileRef.current && fileRef.current.click()}>
              {IC.upload} {f.attachment ? f.attachment : "แนบไฟล์ (ถ้ามี)…"}
            </button>
          </div>
          <div className="login-acts" style={{ marginTop:16 }}>
            <button type="button" className="btn" onClick={safeClose}>ยกเลิก</button>
            <button type="submit" className="btn pri" disabled={saving}>{saving ? "กำลังบันทึก…" : (isEdit ? "บันทึกการแก้ไข" : "บันทึกอัปเดต")}</button>
          </div>
        </form>
      </div>
    );
  }
  window.UpdateModal = UpdateModal;

  // ── Global Updates screen ─────────────────────────────────
  window.SCREENS.updates = function UpdatesScreen() {
    const [, bump] = useState(0);
    const refresh = () => bump((n) => n + 1);
    const [show, setShow] = useState(false);
    const [editing, setEditing] = useState(null);
    const [proj, setProj] = useState("ทั้งหมด");
    const [type, setType] = useState("ทั้งหมด");
    const canEdit = window.can("edit");
    const projects = ["ทั้งหมด", ...Array.from(new Set(D.updates.map((u) => u.project)))];
    let list = D.updates.slice();
    if (proj !== "ทั้งหมด") list = list.filter((u) => u.project === proj);
    if (type !== "ทั้งหมด") list = list.filter((u) => u.type === type);

    return (
      <div className="page wide" style={{ maxWidth: 920 }}>
        <header>
          <div className="eyebrow">Update Center</div>
          <h1 className="page-title">อัปเดตโครงการ</h1>
          <p className="page-sub">ศูนย์กลางการอัปเดตของทุกโครงการ — ทุกอัปเดตเชื่อมเข้าสู่ความเคลื่อนไหว, Dashboard และรายงานโดยอัตโนมัติ</p>
        </header>

        <div className="toolbar" style={{ overflowX: "auto" }}>
          {canEdit
            ? <button className="btn pri" onClick={() => setShow(true)} style={{ whiteSpace: "nowrap" }}>{IC.plus} อัปเดตโครงการ</button>
            : <span className="pill neutral" style={{ padding:"8px 13px" }}>{IC.eye}<span style={{ marginLeft:2 }}>อ่านอย่างเดียว</span></span>}
          <div className="spacer" />
          {projects.length > 2 && projects.map((p) => <button key={p} className={"chip" + (proj === p ? " act" : "")} onClick={() => setProj(p)} style={{ whiteSpace: "nowrap" }}>{p}</button>)}
        </div>
        <div className="toolbar" style={{ overflowX: "auto", marginTop: 2 }}>
          <button className={"chip" + (type === "ทั้งหมด" ? " act" : "")} onClick={() => setType("ทั้งหมด")}>ทุกประเภท</button>
          {Object.keys(D.updateTypes).map((k) => <button key={k} className={"chip" + (type === k ? " act" : "")} onClick={() => setType(k)} style={{ whiteSpace: "nowrap" }}><i style={{ width:7, height:7, borderRadius:"50%", background:"var(--" + D.updateTypes[k].tone + ")" }} />{D.updateTypes[k].th}</button>)}
        </div>

        {list.length === 0
          ? <window.EmptyState icon="trend" title="ยังไม่มีการอัปเดต" sub="เริ่มต้นบันทึกความเคลื่อนไหวของโครงการ เช่น เริ่มงานฐานราก, ได้รับ BOQ ใหม่, รออนุมัติงบ" ctaLabel={canEdit ? "บันทึกอัปเดตแรก" : undefined} onCta={canEdit ? () => setShow(true) : undefined} />
          : <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>{list.map((u) => <UpdateCard key={u.id} u={u} showProject={true} onEdit={canEdit ? setEditing : null} />)}</div>}

        {show && <UpdateModal onClose={() => setShow(false)} onDone={refresh} />}
        {editing && <UpdateModal edit={editing} onClose={() => setEditing(null)} onDone={refresh} />}
      </div>
    );
  };
})();
