/* ============================================================
   Clash coordination (FR-10) — track clash results imported from an
   external engine (Navisworks/Solibri/ifcclash/APS) and link to BCF issues.
   ============================================================ */

const CLASH_STATUS = {
  active:    { label: "Đang mở", cls: "danger", icon: "alert" },
  reviewing: { label: "Đang xử lý", cls: "warn", icon: "clock" },
  resolved:  { label: "Đã xử lý", cls: "ok", icon: "checkCircle" },
  approved:  { label: "Đã duyệt", cls: "inf", icon: "check" },
};

const CLASH_MOCK = [
  { id: "m1", code: "CLH-001", element_a: "Cột BTCT C-14", element_b: "Ống gió chính D-630", disc_a: "str", disc_b: "mep", location: "Trục B · +18.4m", distance_mm: 85, status: "active", group_name: "STR ↔ MEP · Ga C", source: "Navisworks" },
  { id: "m2", code: "CLH-003", element_a: "Dầm B-04", element_b: "Máng cáp điện CT-200", disc_a: "str", disc_b: "mep", location: "Trục B-C · +15.0m", distance_mm: 40, status: "reviewing", group_name: "STR ↔ MEP · Ga C", source: "Navisworks" },
  { id: "m3", code: "CLH-004", element_a: "Ống thoát D-300", element_b: "Sàn ke ga", disc_a: "inf", disc_b: "str", location: "Ga L3 · -2.1m", distance_mm: 120, status: "active", group_name: "INF ↔ STR · Ke ga L3", source: "Solibri" },
  { id: "m4", code: "CLH-005", element_a: "Hố ga HG-12", element_b: "Móng cột M-06", disc_a: "inf", disc_b: "str", location: "Ga L3 · -3.4m", distance_mm: 15, status: "resolved", group_name: "INF ↔ STR · Ke ga L3", source: "Solibri" },
  { id: "m5", code: "CLH-006", element_a: "Panel mặt đứng P-22", element_b: "Miệng gió OAG-3", disc_a: "arc", disc_b: "mep", location: "Mặt đứng Bắc", distance_mm: 8, status: "approved", group_name: "ARC ↔ MEP · Mặt đứng", source: "Navisworks" },
];

function Clash() {
  const auth = (typeof useAuthCtx === "function") ? useAuthCtx() : null;
  const live = !!(auth && auth.user && window.CDE_READY);
  const [rows, setRows] = useState(CLASH_MOCK);
  const [busy, setBusy] = useState(null);
  const reload = React.useCallback(async () => {
    const d = live ? await cdeData.clashes().catch(e => { console.warn("clash live:", e.message); return CLASH_MOCK; }) : CLASH_MOCK;
    setRows(d);
  }, [live]);
  React.useEffect(() => { reload(); }, [reload]);
  React.useEffect(() => {
    if (!live || !window.sb) return;
    const ch = window.sb.channel("rt-clashes")
      .on("postgres_changes", { event: "*", schema: "public", table: "clashes" }, () => reload())
      .subscribe();
    return () => { try { window.sb.removeChannel(ch); } catch {} };
  }, [live, reload]);

  const total = rows.length;
  const active = rows.filter(r => r.status === "active").length;
  const done = rows.filter(r => r.status === "resolved" || r.status === "approved").length;

  const setStatus = async (c, status) => {
    if (!live) return;
    setBusy(c.id);
    try { await cdeData.setClashStatus(c.id, status); reload(); }
    catch (e) { window.alert("Đổi trạng thái thất bại: " + e.message); }
    finally { setBusy(null); }
  };
  const toIssue = async (c) => {
    if (!live) { window.alert("Đăng nhập để chuyển va chạm thành issue."); return; }
    setBusy(c.id);
    try { const iss = await cdeData.clashToIssue(c); reload(); window.alert("Đã tạo issue " + iss.code + " từ " + c.code); }
    catch (e) { window.alert("Tạo issue thất bại: " + e.message); }
    finally { setBusy(null); }
  };

  return (
    <div className="content">
      <PageHead title="Va chạm & Điều phối" sub="Kết quả clash nhập từ Navisworks / Solibri / BCF · liên kết Issue">
        <button className="btn sm"><Icon.upload size={14} /> Nhập BCF</button>
        <button className="btn sm" onClick={() => downloadCSV("clash-report.csv",
          ["Mã", "Phần tử A", "Phần tử B", "Bộ môn", "Vị trí", "Xuyên (mm)", "Trạng thái", "Nguồn"],
          rows.map(r => [r.code, r.element_a, r.element_b, (DISC_NAME[r.disc_a] || r.disc_a) + " ↔ " + (DISC_NAME[r.disc_b] || r.disc_b), r.location, r.distance_mm, CLASH_STATUS[r.status]?.label, r.source]))}>
          <Icon.download size={14} /> Xuất CSV</button>
      </PageHead>

      <div className="grid g-4" style={{ marginBottom: 18 }}>
        {[["Tổng va chạm", total, "var(--accent)", "burst"], ["Đang mở", active, "var(--danger)", "alert"],
          ["Đã xử lý/duyệt", done, "var(--ok)", "checkCircle"], ["Nhóm tổ hợp", new Set(rows.map(r => r.group_name)).size, "var(--mep)", "layers"]].map(([l, v, c, ic], i) => {
          const Ico = Icon[ic] || Icon.box;
          return <div key={i} className="card stat" style={{ flexDirection: "row", alignItems: "center", gap: 14 }}>
            <div className="stat-ico" style={{ background: `${c}1f`, color: c }}><Ico size={20} /></div>
            <div><div className="tnum" style={{ fontSize: 26, fontWeight: 800 }}>{v}</div>
              <div style={{ fontSize: 12.5, color: "var(--ink-3)", fontWeight: 600 }}>{l}</div></div>
          </div>;
        })}
      </div>

      <div className="card" style={{ padding: "8px 10px" }}>
        <table className="tbl">
          <thead><tr>
            <th style={{ paddingLeft: 14 }}>Mã</th><th>Cặp va chạm</th><th>Bộ môn</th><th>Vị trí</th>
            <th>Xuyên</th><th>Trạng thái</th><th style={{ width: 220 }}>Hành động</th>
          </tr></thead>
          <tbody>
            {rows.map((c) => {
              const st = CLASH_STATUS[c.status] || CLASH_STATUS.active; const Sico = Icon[st.icon];
              return (
                <tr key={c.id}>
                  <td><span className="tag-mono">{c.code}</span></td>
                  <td>
                    <div className="t-strong" style={{ fontSize: 12.5 }}>{c.element_a}</div>
                    <div style={{ fontSize: 11.5, color: "var(--ink-3)", fontWeight: 500 }}>↔ {c.element_b}</div>
                  </td>
                  <td><span className={`chip ${c.disc_a}`} style={{ marginRight: 4 }}>{DISC_NAME[c.disc_a] || c.disc_a}</span><span className={`chip ${c.disc_b}`}>{DISC_NAME[c.disc_b] || c.disc_b}</span></td>
                  <td style={{ fontSize: 12.5, color: "var(--ink-2)" }}>{c.location}</td>
                  <td className="tnum" style={{ fontWeight: 700, color: c.distance_mm >= 50 ? "var(--danger)" : "var(--ink-2)" }}>{c.distance_mm}mm</td>
                  <td><span className={`chip ${st.cls}`}><Sico size={12} /> {st.label}</span></td>
                  <td>
                    {live ? (
                      <div style={{ display: "flex", gap: 6, alignItems: "center" }}>
                        <select value={c.status} disabled={busy === c.id} onChange={(e) => setStatus(c, e.target.value)}
                          style={{ height: 30, borderRadius: 8, border: "1px solid var(--line)", background: "var(--surface)", color: "var(--ink)", font: "inherit", fontSize: 12, fontWeight: 600, padding: "0 6px" }}>
                          {Object.entries(CLASH_STATUS).map(([k, v]) => <option key={k} value={k}>{v.label}</option>)}
                        </select>
                        {c.issue_id
                          ? <span className="chip ok" style={{ height: 28 }}><Icon.flag size={12} /> Đã gắn issue</span>
                          : <button className="btn sm" disabled={busy === c.id} onClick={() => toIssue(c)}><Icon.flag size={13} /> Tạo issue</button>}
                      </div>
                    ) : <span style={{ fontSize: 12, color: "var(--ink-4)" }}>Đăng nhập để xử lý</span>}
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
      <div style={{ marginTop: 14, fontSize: 12, color: "var(--ink-4)", fontWeight: 500, padding: "0 4px" }}>
        Phát hiện va chạm hình học do công cụ chuyên dụng (Navisworks/Solibri/ifcclash/APS) thực hiện rồi nhập vào CDE qua BCF — đúng spec FR-10 (CDE theo dõi & điều phối, không tự viết clash engine).
      </div>
    </div>
  );
}

window.Clash = Clash;
