/* ============================================================
   Ventus CDE — Document Management (Autodesk Docs–style)
   Folder tree · file list · versions · review workflow
   ============================================================ */
const { useState: useStateF, useRef: useRefF, useEffect: useEffectF, useMemo: useMemoF } = React;

/* ---------- Folder tree (flat, with parent) ---------- */
const FOLDERS = [
  { id: "root", name: "Project Files", parent: null, root: true },
  { id: "wip",    name: "01 · Đang thực hiện", parent: "root", tag: "WIP" },
  { id: "shared", name: "02 · Chia sẻ phối hợp", parent: "root", tag: "Shared" },
  { id: "pub",    name: "03 · Phát hành thi công", parent: "root", tag: "Published" },
  { id: "arch",   name: "04 · Lưu trữ", parent: "root", tag: "Archived" },
  // disciplines
  { id: "wip-inf", name: "Hạ tầng", parent: "wip", disc: "inf" },
  { id: "wip-str", name: "Kết cấu", parent: "wip", disc: "str" },
  { id: "wip-arc", name: "Kiến trúc", parent: "wip", disc: "arc" },
  { id: "wip-mep", name: "MEP", parent: "wip", disc: "mep" },
  { id: "shared-inf", name: "Hạ tầng", parent: "shared", disc: "inf" },
  { id: "shared-str", name: "Kết cấu", parent: "shared", disc: "str" },
  { id: "shared-mep", name: "MEP", parent: "shared", disc: "mep" },
  { id: "pub-str", name: "Kết cấu", parent: "pub", disc: "str" },
  { id: "pub-arc", name: "Kiến trúc", parent: "pub", disc: "arc" },
];

const STATUS = {
  wip:       { label: "WIP", cls: "idle", icon: "clock", suit: "S0" },
  review:    { label: "Đang duyệt", cls: "warn", icon: "clock", suit: "S3" },
  shared:    { label: "Đã chia sẻ", cls: "str", icon: "link", suit: "S2" },
  approved:  { label: "Đã duyệt", cls: "ok", icon: "checkCircle", suit: "A1" },
  changes:   { label: "Cần sửa", cls: "danger", icon: "alert", suit: "S0" },
  published: { label: "Phát hành", cls: "inf", icon: "check", suit: "A1" },
};

/* ISO 19650 suitability codes (configurable per project) */
const SUITABILITY = {
  S0: "S0 · Chưa phù hợp để dùng",
  S1: "S1 · Phù hợp để phối hợp",
  S2: "S2 · Phù hợp để tham khảo",
  S3: "S3 · Phù hợp để đánh giá",
  A1: "A1 · Đã duyệt để thi công",
};

const TYPE_META = {
  DWG:  { color: "#3b82f6", kind: "drawing" },
  IFC:  { color: "#14b8a6", kind: "model" },
  NWC:  { color: "#0ea5a3", kind: "model" },
  RVT:  { color: "#a78bfa", kind: "model" },
  PDF:  { color: "#ef4444", kind: "doc" },
  DOCX: { color: "#2563eb", kind: "doc" },
  XLSX: { color: "#16a34a", kind: "sheet" },
};

let UID = 100;
const v = (rev, date, by, status, note) => ({ rev, date, by, status, note });

/* ---------- File dataset ---------- */
const FILES0 = [
  { id: UID++, folder: "shared-inf", name: "INF-Drainage-L3", type: "IFC", disc: "inf", status: "approved",
    size: "84 MB", date: "07/06 · 09:42", by: "Nguyễn Minh", rev: "C02", desc: "Hệ thoát nước ga L3",
    versions: [ v("C02","07/06 09:42","Nguyễn Minh","approved","Cập nhật cao độ hố ga"), v("C01","02/06 14:10","Nguyễn Minh","shared","Phát hành phối hợp"), v("P02","28/05 11:05","Đỗ Hải","review",""), v("P01","20/05 08:30","Nguyễn Minh","wip","Khởi tạo") ] },
  { id: UID++, folder: "shared-str", name: "STR-Frame-Station-C", type: "NWC", disc: "str", status: "shared",
    size: "126 MB", date: "07/06 · 08:10", by: "Lê Hồng", rev: "C01", desc: "Khung kết cấu ga C",
    versions: [ v("C01","07/06 08:10","Lê Hồng","shared","Xuất NWC từ Tekla"), v("P03","04/06 16:20","Lê Hồng","review",""), v("P02","30/05 10:00","Lê Hồng","wip","") ] },
  { id: UID++, folder: "wip-mep", name: "MEP-HVAC-B2", type: "DWG", disc: "mep", status: "review",
    size: "44 MB", date: "07/06 · 11:28", by: "Trần Đức", rev: "P02", desc: "Điều hoà tầng B2 — thiếu NWC",
    versions: [ v("P02","07/06 11:28","Trần Đức","review","Chờ xuất Navisworks"), v("P01","05/06 09:15","Trần Đức","wip","") ] },
  { id: UID++, folder: "pub-arc", name: "ARC-Facade-GaC", type: "RVT", disc: "arc", status: "published",
    size: "212 MB", date: "06/06 · 17:50", by: "Vũ Lan", rev: "C03", desc: "Mặt đứng kiến trúc ga C",
    versions: [ v("C03","06/06 17:50","Vũ Lan","published","Phát hành thi công"), v("C02","01/06 13:00","Vũ Lan","approved",""), v("C01","25/05 09:40","Vũ Lan","shared","") ] },
  { id: UID++, folder: "shared-inf", name: "INF-Tunnel-TBM-L3", type: "IFC", disc: "inf", status: "approved",
    size: "168 MB", date: "06/06 · 15:30", by: "Đỗ Hải", rev: "C01", desc: "Vỏ hầm TBM đoạn L3",
    versions: [ v("C01","06/06 15:30","Đỗ Hải","approved","Chốt thiết kế"), v("P02","02/06 10:20","Đỗ Hải","review",""), v("P01","27/05 14:00","Đỗ Hải","wip","") ] },
  { id: UID++, folder: "wip-str", name: "STR-Platform-Slab", type: "NWC", disc: "str", status: "wip",
    size: "97 MB", date: "06/06 · 10:05", by: "Lê Hồng", rev: "P02", desc: "Sàn ke ga — đang dựng",
    versions: [ v("P02","06/06 10:05","Lê Hồng","wip","Bổ sung cốt thép"), v("P01","03/06 08:00","Lê Hồng","wip","") ] },
  { id: UID++, folder: "shared-mep", name: "MEP-Electrical-L2", type: "DWG", disc: "mep", status: "changes",
    size: "31 MB", date: "05/06 · 16:42", by: "Bùi An", rev: "P03", desc: "Hệ điện L2 — cần sửa va chạm",
    versions: [ v("P03","05/06 16:42","Bùi An","changes","CSM yêu cầu sửa tuyến máng"), v("P02","31/05 11:30","Bùi An","review",""), v("P01","24/05 09:00","Bùi An","wip","") ] },
  { id: UID++, folder: "pub-str", name: "STR-Column-Schedule", type: "PDF", disc: "str", status: "published",
    size: "2.4 MB", date: "05/06 · 14:00", by: "Lê Hồng", rev: "C02", desc: "Bảng thống kê cột BTCT",
    versions: [ v("C02","05/06 14:00","Lê Hồng","published","Phát hành kèm bản vẽ"), v("C01","28/05 09:00","Lê Hồng","approved","") ] },
  { id: UID++, folder: "shared-str", name: "STR-Beam-Detail-B04", type: "DWG", disc: "str", status: "review",
    size: "18 MB", date: "05/06 · 09:20", by: "Lê Hồng", rev: "P02", desc: "Chi tiết dầm B-04",
    versions: [ v("P02","05/06 09:20","Lê Hồng","review",""), v("P01","30/05 15:00","Lê Hồng","wip","") ] },
  { id: UID++, folder: "shared-inf", name: "INF-Coordination-Report", type: "DOCX", disc: "inf", status: "shared",
    size: "1.1 MB", date: "04/06 · 13:15", by: "Phạm Tuấn", rev: "C01", desc: "Biên bản phối hợp tuần 23",
    versions: [ v("C01","04/06 13:15","Phạm Tuấn","shared","") ] },
  { id: UID++, folder: "wip-arc", name: "ARC-Interior-Concept", type: "RVT", disc: "arc", status: "wip",
    size: "143 MB", date: "04/06 · 10:40", by: "Vũ Lan", rev: "P01", desc: "Ý tưởng nội thất sảnh",
    versions: [ v("P01","04/06 10:40","Vũ Lan","wip","") ] },
  { id: UID++, folder: "pub-arc", name: "ARC-Door-Schedule", type: "XLSX", disc: "arc", status: "published",
    size: "0.8 MB", date: "03/06 · 16:00", by: "Vũ Lan", rev: "C01", desc: "Thống kê cửa",
    versions: [ v("C01","03/06 16:00","Vũ Lan","published","") ] },
];

/* ---------- helpers (operate on the active folder set: mock or live) ---------- */
let ACTIVE_FOLDERS = FOLDERS;
function setActiveFolders(arr) { ACTIVE_FOLDERS = (arr && arr.length) ? arr : FOLDERS; }
const childFolders = (id) => ACTIVE_FOLDERS.filter(f => f.parent === id);
const folderById = (id) => ACTIVE_FOLDERS.find(f => f.id === id);
function descendantIds(id) {
  const out = [id]; let i = 0;
  while (i < out.length) { childFolders(out[i++]).forEach(c => out.push(c.id)); }
  return out;
}
function breadcrumb(id) {
  const chain = []; let cur = folderById(id);
  while (cur) { chain.unshift(cur); cur = cur.parent ? folderById(cur.parent) : null; }
  return chain;
}

/* ---------- faux drawing-sheet preview ---------- */
function SheetPreview({ file, big }) {
  const meta = TYPE_META[file.type] || { color: "#64748b", kind: "doc" };
  if (meta.kind === "model") {
    return (
      <div style={{ width: "100%", height: big ? 220 : 96, borderRadius: 10, overflow: "hidden",
        background: "radial-gradient(120% 120% at 50% 0%, #14323a, #0b1c21)", display: "grid", placeItems: "center", position: "relative" }}>
        <div style={{ position: "absolute", inset: 0, backgroundImage: "linear-gradient(rgba(120,200,190,.12) 1px,transparent 1px),linear-gradient(90deg,rgba(120,200,190,.12) 1px,transparent 1px)", backgroundSize: "22px 22px" }} />
        <Icon.cube size={big ? 56 : 30} color={DISC_COL[file.disc]} />
        <span className="tag-mono" style={{ position: "absolute", bottom: 8, left: 8, background: "rgba(255,255,255,.08)", color: "#cfe9e5", fontSize: 10 }}>{file.type} · 3D</span>
      </div>
    );
  }
  // drawing / doc sheet
  return (
    <div style={{ width: "100%", height: big ? 220 : 96, borderRadius: 10, overflow: "hidden",
      background: "#fff", border: "1px solid var(--line)", position: "relative", padding: big ? 14 : 8 }}>
      <div style={{ position: "absolute", inset: big ? 10 : 6, border: "1.5px solid #c9d4d6" }} />
      {meta.kind === "drawing" ? (
        <svg width="100%" height="100%" viewBox="0 0 200 130" style={{ position: "relative" }}>
          <g stroke="#9fb6bb" strokeWidth="1.1" fill="none">
            <rect x="30" y="24" width="90" height="60" /><rect x="44" y="40" width="28" height="44" />
            <rect x="86" y="24" width="34" height="34" /><line x1="30" y1="54" x2="120" y2="54" />
            <circle cx="150" cy="50" r="20" /><line x1="150" y1="30" x2="150" y2="70" /><line x1="130" y1="50" x2="170" y2="50" />
          </g>
          <g stroke={meta.color} strokeWidth="1.4" fill="none"><line x1="30" y1="96" x2="170" y2="96" /></g>
        </svg>
      ) : (
        <div style={{ position: "relative", paddingTop: big ? 8 : 2 }}>
          {[100,82,90,68,95,74,40].slice(0, big ? 7 : 4).map((w,i)=>(
            <div key={i} style={{ height: big?7:5, width: `${w}%`, background: i===0?meta.color:"#dde6e8", borderRadius: 3, margin: big?"0 0 9px":"0 0 6px" }} />
          ))}
        </div>
      )}
      {/* title block */}
      <div style={{ position: "absolute", right: big?12:7, bottom: big?12:7, width: big?96:54, height: big?40:22,
        border: "1.5px solid #c9d4d6", background: "#fff", display: "flex", flexDirection: "column", justifyContent: "center", paddingLeft: 5 }}>
        <span style={{ fontFamily: "var(--mono)", fontSize: big?9:6.5, color: "#6b7c80", fontWeight: 600 }}>{file.name.slice(0,big?12:8)}</span>
        <span style={{ fontFamily: "var(--mono)", fontSize: big?8:6, color: meta.color, fontWeight: 700 }}>REV {file.rev}</span>
      </div>
    </div>
  );
}

function TypeIcon({ type, size = 18 }) {
  const meta = TYPE_META[type] || { color: "#64748b", kind: "doc" };
  const ic = meta.kind === "model" ? "cube" : meta.kind === "drawing" ? "ruler" : meta.kind === "sheet" ? "grid" : "doc";
  const Ico = Icon[ic];
  return (
    <span style={{ width: 34, height: 34, borderRadius: 9, flex: "none", display: "grid", placeItems: "center",
      background: `${meta.color}1c`, color: meta.color }}><Ico size={size} /></span>
  );
}

window.FOLDERS = FOLDERS; window.FILES0 = FILES0; window.STATUS = STATUS; window.TYPE_META = TYPE_META;
window.SUITABILITY = SUITABILITY;
window.childFolders = childFolders; window.folderById = folderById;
window.descendantIds = descendantIds; window.breadcrumb = breadcrumb;
window.setActiveFolders = setActiveFolders;
window.SheetPreview = SheetPreview; window.TypeIcon = TypeIcon;
