/* ============================================================
   Transmittals — digital transmittal register + detail drawer
   (stub — to be implemented)
   ============================================================ */
window.Transmittals = function Transmittals() { return null; };
/* ============================================================
   Transmittals – Thư chuyển giao (ISO 19650)
   ============================================================ */

const TR_STATUS = {
  sent:        { label:"Đã gửi",       cls:"idle", icon:"send" },
  viewed:      { label:"Đã xem",       cls:"warn", icon:"eye" },
  downloaded:  { label:"Đã tải",       cls:"ok",   icon:"download" },
};

const TRANSMITTALS = [
  {
    id:"TR-051",
    title:"Phát hành thi công kết cấu ga C",
    to:"Nhà thầu CIENCO4",
    from:"Phạm Tuấn",
    disc:"str",
    date:"07/06 · 10:20",
    status:"viewed",
    docs:[
      {name:"STR-Frame-Station-C", rev:"C01"},
      {name:"STR-Column-Schedule", rev:"C02"},
      {name:"STR-Beam-Detail-B04", rev:"P02"},
      {name:"STR-Platform-Slab",   rev:"P02"},
    ],
  },
  {
    id:"TR-050",
    title:"Hồ sơ phối hợp MEP tuần 23",
    to:"BQLDA Metro L3",
    from:"Trần Đức",
    disc:"mep",
    date:"06/06 · 16:05",
    status:"downloaded",
    docs:[
      {name:"MEP-HVAC-B2",        rev:"P02"},
      {name:"MEP-Electrical-L2",  rev:"P03"},
    ],
  },
  {
    id:"TR-049",
    title:"Bản vẽ kiến trúc mặt đứng ga C",
    to:"TVGS Apave",
    from:"Vũ Lan",
    disc:"arc",
    date:"05/06 · 09:30",
    status:"sent",
    docs:[
      {name:"ARC-Facade-GaC",     rev:"C03"},
      {name:"ARC-Door-Schedule",  rev:"C01"},
      {name:"ARC-Interior-Concept",rev:"P01"},
    ],
  },
  {
    id:"TR-048",
    title:"Mô hình hạ tầng thoát nước L3",
    to:"Nhà thầu CIENCO4",
    from:"Nguyễn Minh",
    disc:"inf",
    date:"04/06 · 14:00",
    status:"downloaded",
    docs:[
      {name:"INF-Drainage-L3",          rev:"C02"},
      {name:"INF-Tunnel-TBM-L3",        rev:"C01"},
      {name:"INF-Coordination-Report",  rev:"C01"},
    ],
  },
  {
    id:"TR-047",
    title:"Báo cáo va chạm tổ hợp tuần 22",
    to:"BQLDA Metro L3",
    from:"Trần Đức",
    disc:"inf",
    date:"03/06 · 11:15",
    status:"viewed",
    docs:[
      {name:"FED-Metro-L3-v41", rev:"C01"},
    ],
  },
];

/* ── Drawer ──────────────────────────────────────────────── */
function TransmittalDrawer({ tr, onClose }) {
  const {useState}=React;
  const statusInfo = TR_STATUS[tr.status];

  /* helper: timeline items based on status order */
  const timelineItems = [
    { text:"Đã nhận transmittal",          time: tr.date },
    { text:"Đã mở xem trực tuyến",         time: "+2h" },
    { text:"Đã tải bản sao",               time: "+1d" },
  ];
  const timelineCount =
    tr.status === "sent"        ? 1 :
    tr.status === "viewed"      ? 2 :
    tr.status === "downloaded"  ? 3 : 0;

  return (
    <div style={{
      width:420,
      flex:"none",
      borderLeft:"1px solid var(--line)",
      background:"var(--surface)",
      display:"flex",
      flexDirection:"column",
      position:"absolute",
      top:0,
      right:0,
      bottom:0,
      zIndex:20,
      boxShadow:"var(--shadow-lg)",
    }}>
      {/* ── Header ── */}
      <div style={{
        padding:"16px 18px",
        borderBottom:"1px solid var(--line)",
        display:"flex",
        alignItems:"flex-start",
        gap:12,
      }}>
        <div style={{
          width:38,
          height:38,
          borderRadius:8,
          background:"var(--accent-soft)",
          color:"var(--accent)",
          display:"flex",
          alignItems:"center",
          justifyContent:"center",
          flexShrink:0,
        }}>
          <Icon.send size={18} />
        </div>
        <div style={{flex:1, minWidth:0}}>
          <div className="tag-mono">{tr.id}</div>
          <div className="t-strong" style={{fontSize:14, marginTop:4}}>{tr.title}</div>
        </div>
        <button className="icon-btn" onClick={onClose} style={{flexShrink:0}}>
          ✕
        </button>
      </div>

      {/* ── Body ── */}
      <div style={{flex:1, overflowY:"auto", padding:18}}>
        {/* meta rows */}
        {[
          {label:"Người gửi",       value: tr.from},
          {label:"Người nhận",      value: tr.to},
          {label:"Bộ môn",          value: <span className={`chip ${tr.disc}`}>{DISC_NAME[tr.disc]}</span>},
          {label:"Ngày phát hành",  value: tr.date},
          {label:"Trạng thái",      value: <span className={`chip ${statusInfo.cls}`}>{statusInfo.label}</span>},
        ].map((row,i)=>(
          <div key={i} style={{
            display:"flex",
            justifyContent:"space-between",
            alignItems:"center",
            padding:"11px 0",
            borderBottom:"1px solid var(--line-soft)",
          }}>
            <span style={{color:"var(--ink-3)", fontSize:12.5}}>{row.label}</span>
            <span style={{fontWeight:700, fontSize:12.5}}>{row.value}</span>
          </div>
        ))}

        {/* ── TÀI LIỆU ĐÍNH KÈM ── */}
        <div style={{
          fontSize:11,
          fontWeight:700,
          letterSpacing:".06em",
          color:"var(--ink-4)",
          margin:"18px 0 10px",
        }}>
          TÀI LIỆU ĐÍNH KÈM
        </div>
        {tr.docs.map((d,i)=>(
          <div key={i} style={{
            display:"flex",
            alignItems:"center",
            gap:10,
            padding:"9px 0",
            borderTop: i ? "1px solid var(--line-soft)" : "none",
          }}>
            <Icon.doc size={16} color="var(--ink-3)" />
            <span className="mono" style={{fontSize:12.5, flex:1}}>{d.name}</span>
            <span className="chip tag-mono">REV {d.rev}</span>
            <button className="btn sm"><Icon.download /></button>
          </div>
        ))}

        {/* ── Cover letter card ── */}
        <div style={{
          background:"var(--sunken)",
          borderRadius:12,
          padding:14,
          marginTop:16,
        }}>
          <div style={{display:"flex", alignItems:"center", gap:6, marginBottom:6}}>
            <Icon.checkCircle size={14} color="var(--ok)" />
            <span style={{fontWeight:"bold", fontSize:12.5}}>Cover letter · Record copy</span>
          </div>
          <div style={{fontSize:12.5, color:"var(--ink-2)", lineHeight:1.5}}>
            {"Thư chuyển giao "+tr.id+" gồm "+tr.docs.length+" tài liệu, phát hành "+tr.date+". Bản record copy PDF bất biến đã được lưu phục vụ kiểm toán."}
          </div>
        </div>

        {/* ── NHẬT KÝ NGƯỜI NHẬN ── */}
        <div style={{
          fontSize:11,
          fontWeight:700,
          letterSpacing:".06em",
          color:"var(--ink-4)",
          margin:"18px 0 10px",
        }}>
          NHẬT KÝ NGƯỜI NHẬN
        </div>
        {timelineItems.slice(0,timelineCount).map((item,i)=>(
          <div key={i} style={{display:"flex", alignItems:"center", gap:8, padding:"6px 0"}}>
            <div style={{
              width:8,
              height:8,
              borderRadius:"50%",
              background:"var(--accent)",
              flexShrink:0,
            }} />
            <span style={{fontSize:12.5, flex:1}}>{item.text}</span>
            <span style={{fontSize:11, color:"var(--ink-3)"}}>{item.time}</span>
          </div>
        ))}
      </div>

      {/* ── Footer ── */}
      <div style={{
        padding:14,
        borderTop:"1px solid var(--line)",
        display:"flex",
        gap:8,
      }}>
        <button className="btn sm" style={{flex:1}}>
          <Icon.download /> Tải gói
        </button>
        <button className="btn sm primary" style={{flex:1}}>
          <Icon.send /> Gửi lại
        </button>
      </div>
    </div>
  );
}

/* ── Main screen ─────────────────────────────────────────── */
function Transmittals() {
  const {useState}=React;
  const auth = (typeof useAuthCtx === "function") ? useAuthCtx() : null;
  const live = !!(auth && auth.user && window.CDE_READY);
  const actor = (auth && auth.profile && auth.profile.full_name) || "Bạn";
  const [items, setItems] = useState(TRANSMITTALS);
  const [sel, setSel] = useState(null);
  const [creating, setCreating] = useState(false);
  const reload = React.useCallback(async () => {
    const d = live ? await cdeData.transmittals().catch(e => { console.warn("transmittals live:", e.message); return TRANSMITTALS; }) : TRANSMITTALS;
    setItems(d);
    setSel(prev => prev ? (d.find(x => x.id === prev.id) || prev) : prev);
  }, [live]);
  React.useEffect(() => { reload(); }, [reload]);

  return (
    <div className="content flush" style={{
      display:"flex",
      height:"100%",
      minHeight:0,
      position:"relative",
    }}>
      {/* left column */}
      <div style={{flex:1, display:"flex", flexDirection:"column", minWidth:0}}>
        {/* PageHead */}
        <div style={{padding:"22px 22px 0"}}>
          <PageHead
            title="Thư chuyển giao (Transmittals)"
            sub="Phát hành & theo dõi hồ sơ giữa các bên · ISO 19650"
          >
            <button className="btn sm"><Icon.filter size={14} /> Lọc</button>
            <button className="btn sm primary" onClick={() => setCreating(true)}><Icon.plus size={14} /> Tạo transmittal</button>
          </PageHead>
        </div>

        {/* table area */}
        <div style={{padding:"0 22px 22px", flex:1, overflowY:"auto"}}>
          <div className="card" style={{padding:"8px 10px"}}>
            <table className="tbl">
              <thead>
                <tr>
                  <th>Mã</th>
                  <th>Tiêu đề</th>
                  <th>Người nhận</th>
                  <th>Tài liệu</th>
                  <th>Ngày</th>
                  <th>Trạng thái</th>
                  <th></th>
                </tr>
              </thead>
              <tbody>
                {items.map((tr)=>{
                  const IconComp = Icon[TR_STATUS[tr.status].icon];
                  return (
                    <tr
                      key={tr.id}
                      onClick={()=>setSel(tr)}
                      style={{
                        cursor:"pointer",
                        background: sel?.id===tr.id ? "var(--accent-soft)" : undefined,
                      }}
                    >
                      <td><span className="tag-mono">{tr.id}</span></td>
                      <td><span className="t-strong">{tr.title}</span></td>
                      <td>{tr.to}</td>
                      <td><span className="chip">{tr.docs.length} tệp</span></td>
                      <td style={{fontVariantNumeric:"tabular-nums"}}>{tr.date}</td>
                      <td>
                        <span className={`chip ${TR_STATUS[tr.status].cls}`}>
                          <IconComp size={12} />{" "}
                          {TR_STATUS[tr.status].label}
                        </span>
                      </td>
                      <td>
                        <button className="icon-btn">›</button>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </div>
      </div>

      {/* drawer */}
      {sel && <TransmittalDrawer tr={sel} onClose={()=>setSel(null)} />}
      {creating && <CreateTransmittalModal live={live} actor={actor} onClose={()=>setCreating(false)} onCreated={reload} />}
    </div>
  );
}

/* ---------- create transmittal modal ---------- */
function CreateTransmittalModal({ live, actor, onClose, onCreated }) {
  const { useState } = React;
  const [f, setF] = useState({ title: "", to: "", disc: "str", docs: "" });
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState("");
  const set = (k, v) => setF(s => ({ ...s, [k]: v }));
  const parseDocs = (s) => (s || "").split(/\n+/).map(l => l.trim()).filter(Boolean)
    .map(l => { const m = l.split(/\s+/); return { name: m[0], rev: m[1] || "C01" }; });
  const submit = async () => {
    if (!f.title.trim() || !f.to.trim()) { setErr("Nhập tiêu đề và người nhận"); return; }
    if (!live) { onClose(); return; }
    setBusy(true); setErr("");
    try { await cdeData.createTransmittal({ title: f.title, to: f.to, from: actor, disc: f.disc }, parseDocs(f.docs)); onCreated && onCreated(); onClose(); }
    catch (e) { setErr(e.message || "Tạo transmittal thất bại"); }
    finally { setBusy(false); }
  };
  const inp = { width: "100%", height: 38, padding: "0 12px", borderRadius: 10, border: "1px solid var(--line)", background: "var(--surface)", color: "var(--ink)", font: "inherit", fontSize: 13.5, fontWeight: 600, outline: "none", marginTop: 6 };
  const lb = { display: "block", fontSize: 11.5, fontWeight: 700, color: "var(--ink-3)", marginTop: 13 };
  return (
    <div onClick={onClose} style={{ position: "fixed", inset: 0, zIndex: 55, background: "rgba(8,19,23,.5)", backdropFilter: "blur(3px)", display: "grid", placeItems: "center" }}>
      <div onClick={(e) => e.stopPropagation()} className="card" style={{ width: 460, padding: 24, boxShadow: "var(--shadow-lg)" }}>
        <div style={{ fontWeight: 800, fontSize: 16, marginBottom: 2 }}>Tạo transmittal</div>
        <div style={{ fontSize: 12.5, color: "var(--ink-3)", fontWeight: 500 }}>{live ? "Phát hành & lưu record copy" : "Chế độ demo — chưa đăng nhập"}</div>
        <label style={lb}>Tiêu đề</label>
        <input style={inp} value={f.title} onChange={(e) => set("title", e.target.value)} placeholder="VD: Phát hành thi công kết cấu ga C" />
        <div style={{ display: "flex", gap: 12 }}>
          <div style={{ flex: 2 }}><label style={lb}>Người nhận</label><input style={inp} value={f.to} onChange={(e) => set("to", e.target.value)} placeholder="Nhà thầu CIENCO4" /></div>
          <div style={{ flex: 1 }}><label style={lb}>Bộ môn</label>
            <select style={inp} value={f.disc} onChange={(e) => set("disc", e.target.value)}>{Object.entries(DISC_NAME).map(([k, v]) => <option key={k} value={k}>{v}</option>)}</select></div>
        </div>
        <label style={lb}>Tài liệu đính kèm (mỗi dòng: MÃ REV)</label>
        <textarea style={{ ...inp, height: 84, padding: "8px 12px", fontFamily: "var(--mono)", fontSize: 12.5 }}
          value={f.docs} onChange={(e) => set("docs", e.target.value)} placeholder={"STR-Frame-Station-C C01\nSTR-Column-Schedule C02"} />
        {err && <div style={{ marginTop: 12, fontSize: 12.5, color: "var(--danger)", fontWeight: 600 }}>{err}</div>}
        <div style={{ display: "flex", gap: 10, justifyContent: "flex-end", marginTop: 18 }}>
          <button className="btn" onClick={onClose}>Huỷ</button>
          <button className="btn primary" disabled={busy} onClick={submit} style={{ opacity: busy ? .6 : 1 }}><Icon.send size={14} /> {busy ? "Đang gửi…" : "Gửi transmittal"}</button>
        </div>
      </div>
    </div>
  );
}

window.Transmittals = Transmittals;
