// Decision Log — full CRUD (Add/Edit/Delete) + project filter.
(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)" };
  // Hoisted 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>);
  }

  // 6-field Decision modal (Add/Edit). Long-form textareas, calendar date, file attach, safe close.
  function DecisionModal({ edit, fixedProjectId, onClose, onDone }) {
    const isEdit = !!edit;
    const initPid = fixedProjectId || (isEdit ? edit.projectId : (D.projects[0] || {}).id) || "";
    const [f, setF, safeClose, restoredDraft] = window.useDirty({
      projectId: initPid,
      dateISO: isEdit ? (edit.dateISO || window.todayISO()) : window.todayISO(),
      change: isEdit ? (edit.change || "") : "",
      reason: isEdit ? (edit.reason || "") : "",
      impact: isEdit ? (edit.impact || "") : "",
      by:     isEdit ? (edit.by || "") : "ธนา",
      attachment: isEdit ? (edit.attachment || "") : "",
    }, onClose, isEdit ? null : { draftKey: "decision-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 submit = async (e) => {
      e.preventDefault(); if (!f.change.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: "decisions" });
        attachment = up.url || up.name || attachment;
      }
      const payload = { ...f, date: window.isoToBE(f.dateISO), attachment };
      if (isEdit) await window.DB.updateDecision(edit.id, payload);
      else { await window.DB.createDecision(payload); window.clearDraft("decision-create-" + f.projectId); }
      setSaving(false); window.toast(isEdit ? "บันทึก Decision แล้ว" : "บันทึก Decision ใหม่แล้ว"); onDone && onDone(); onClose();
    };
    return (
      <div className="login-overlay" onClick={window.NOOP}>
        <form className="login-card" style={{ maxWidth:560, 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.dec}</div>
          <h2>{isEdit ? "แก้ไข Decision" : "บันทึก Decision"}</h2>
          {!isEdit && restoredDraft && <div className="pill warn wrappable" style={{ marginTop: 8 }}><i />กู้คืนแบบร่างที่บันทึกไว้</div>}
          <div style={{ display:"grid", gap:11, marginTop:4 }}>
            {!fixedProjectId && !isEdit && <Field label="โครงการ"><select value={f.projectId} onChange={set("projectId")} style={selStyle}>{D.projects.map((p) => <option key={p.id} value={p.id}>{p.name}</option>)}</select></Field>}
            <window.DateField label="วันที่" value={f.dateISO} onChange={(v) => setF((p) => ({ ...p, dateISO: v }))} />
            <label className="login-field"><span>หัวข้อการตัดสินใจ *</span><div className="login-input" style={{ alignItems:"flex-start" }}><window.AutoTextarea value={f.change} onChange={set("change")} rows={2} placeholder="เช่น เปลี่ยนวัสดุผนังภายนอก / อนุมัติงบเพิ่มเติม" required /></div></label>
            <label className="login-field"><span>เหตุผล / รายละเอียด</span><div className="login-input" style={{ alignItems:"flex-start" }}><window.AutoTextarea value={f.reason} onChange={set("reason")} rows={5} placeholder="อธิบายเหตุผลในการตัดสินใจอย่างละเอียด" /></div></label>
            <label className="login-field"><span>ผลกระทบ</span><div className="login-input" style={{ alignItems:"flex-start" }}><window.AutoTextarea value={f.impact} onChange={set("impact")} rows={2} placeholder="ผลกระทบที่เกิดจากการตัดสินใจ เช่น -฿2.5M, Timeline +1 สัปดาห์" /></div></label>
            <Field label="ผู้ตัดสินใจ"><input value={f.by} onChange={set("by")} placeholder="ชื่อผู้ตัดสินใจ" /></Field>
            <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 ? "บันทึกการแก้ไข" : "บันทึก Decision")}</button>
          </div>
        </form>
      </div>
    );
  }
  window.DecisionModal = DecisionModal;

  window.SCREENS.decisions = function DecisionLog() {
    const [, bump] = useState(0);
    const refresh = () => bump((n) => n + 1);
    const [show, setShow] = useState(false);
    const [editing, setEditing] = useState(null);
    const projects = ["ทั้งหมด", ...Array.from(new Set(D.decisionLog.map((d) => d.project)))];
    const [filter, setFilter] = useState("ทั้งหมด");
    const list = D.decisionLog.filter((d) => filter === "ทั้งหมด" || d.project === filter);
    const canEdit = window.can("edit");
    const onDelete = async (d) => { if (!confirm("ลบบันทึก Decision นี้?\n\"" + d.change + "\"")) return; await window.DB.deleteDecision(d.id); window.toast("ลบ Decision แล้ว"); refresh(); };

    return (
      <div className="page wide" style={{ maxWidth: 880 }}>
        <header>
          <div className="eyebrow">Governance</div>
          <h1 className="page-title">Decision Log</h1>
          <p className="page-sub">ประวัติการตัดสินใจทั้งหมด — บันทึก แก้ไข และจัดการได้ในที่เดียว</p>
        </header>

        <div className="toolbar" style={{ overflowX: "auto" }}>
          {projects.map((pr) => (
            <button key={pr} className={"chip" + (filter === pr ? " act" : "")} onClick={() => setFilter(pr)} style={{ whiteSpace: "nowrap" }}>{pr}</button>
          ))}
          <div className="spacer" />
          {canEdit && <button className="btn pri" onClick={() => setShow(true)} style={{ whiteSpace: "nowrap" }}>{IC.plus} สร้างบันทึก Decision</button>}
        </div>

        {list.length === 0 ?
          <window.EmptyState icon="dec" title="ยังไม่มีบันทึกการตัดสินใจ" sub="ยังไม่มี Decision สำหรับตัวกรองนี้ เมื่อมีการบันทึกการตัดสินใจจะแสดงที่นี่" ctaLabel={canEdit ? "สร้างบันทึก Decision" : undefined} onCta={canEdit ? () => setShow(true) : undefined} />
          :
        <div className="dlog">
          {list.map((d) => (
            <div className="dlog-item" key={d.id}>
              <div className="dlog-card">
                <div className="dlog-top">
                  <span className="dlog-date">{d.date}</span>
                  <div style={{ display: "flex", gap: 7, flexWrap: "wrap", alignItems: "center" }}>
                    <span className="pill neutral"><i />{d.project}</span>
                    {canEdit && <>
                      <button className="icon-btn" title="แก้ไข" onClick={() => setEditing(d)} style={{ width:30, height:30 }}>{IC.settings}</button>
                      <button className="icon-btn" title="ลบ" onClick={() => onDelete(d)} style={{ width:30, height:30, color:"var(--danger)" }}>{IC.x}</button>
                    </>}
                  </div>
                </div>
                <div className="dlog-change" style={{ wordBreak:"break-word", overflowWrap:"anywhere" }}><window.ExpandableText text={d.change} lines={2} title="หัวข้อการตัดสินใจ" /></div>
                {d.reason && <div className="dlog-reason"><window.ExpandableText text={d.reason} lines={3} title="เหตุผล / รายละเอียด" /></div>}
                <div className="dlog-foot">
                  {d.by && <span className="fitem">{IC.user}<b style={{ wordBreak:"break-word" }}>{d.by}</b></span>}
                  {d.impact && <span className="fitem" style={{ minWidth:0, flex:"1 1 200px" }}>{IC.target}ผลกระทบ: <span style={{ wordBreak:"break-word", overflowWrap:"anywhere" }}><b>{d.impact}</b></span></span>}
                  {d.attachment && <span className="fitem" style={{ wordBreak:"break-all" }}>{IC.doc} {d.attachment}</span>}
                </div>
              </div>
            </div>
          ))}
        </div>
        }

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