/* ============================================================
   Reports · Schedule · Coverage · Settings
   ============================================================ */

/* ---------------- Reports / Analytics ---------------- */
const PUB_WEEKS = [120,142,138,165,180,172,205,228,240,256];
function Reports() {
  return (
    <div className="content">
      <PageHead title="Báo cáo & Phân tích" sub="Hiệu suất đồng bộ & đóng góp · Hợp đồng CP-02"><Toolbar /></PageHead>
      <div className="grid g-4" style={{ marginBottom: 18 }}>
        <Stat icon="upload" tint="var(--accent)" label="Lượt xuất bản / 7N" value="256" trend="+11%" trendDir="up" />
        <Stat icon="link" tint="var(--str)" label="Va chạm đã giải quyết" value="184" trend="+26" trendDir="up" />
        <Stat icon="clock" tint="var(--mep)" label="Thời gian đồng bộ TB" value="3.2" unit="ph" trend="−0.8 ph" trendDir="down" />
        <Stat icon="checkCircle" tint="var(--ok)" label="Tỷ lệ duyệt lần 1" value="87" unit="%" trend="+5%" trendDir="up" />
      </div>
      <div className="grid g-2u" style={{ marginBottom: 18 }}>
        <div className="card card-pad">
          <div className="card-head" style={{ marginBottom: 16 }}>
            <div><div className="card-title">Lượt xuất bản theo tuần</div><div className="card-sub">10 tuần gần nhất</div></div>
            <span className="chip ok"><Icon.arrowUp size={12} /> Xu hướng tăng</span>
          </div>
          <BarChart data={PUB_WEEKS} />
        </div>
        <div className="card card-pad">
          <div className="card-title" style={{ marginBottom: 16 }}>Đóng góp theo bộ môn</div>
          <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
            {[["Hạ tầng","inf",96],["Kết cấu","str",78],["Kiến trúc","arc",64],["MEP","mep",52]].map(([n,d,v],i)=>(
              <div className="bar-row" key={i}>
                <span className="nm"><span className="sw" style={{ background: DISC_COL[d] }} />{n}</span>
                <span className="bar"><span style={{ width: `${v}%`, background: DISC_COL[d] }} /></span>
                <span className="pc tnum">{v}%</span>
              </div>
            ))}
          </div>
          <div style={{ marginTop: 22, padding: 14, borderRadius: 12, background: "var(--sunken)" }}>
            <div style={{ fontSize: 12.5, color: "var(--ink-2)", fontWeight: 600, lineHeight: 1.5 }}>
              Bộ môn <b>MEP</b> có độ phủ thấp nhất (79%). Khuyến nghị ưu tiên xuất NWC cho 12 mô hình còn thiếu.
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function BarChart({ data, color = "var(--accent)" }) {
  const max = Math.max(...data);
  return (
    <div style={{ display: "flex", alignItems: "flex-end", gap: 10, height: 200, padding: "0 4px" }}>
      {data.map((v,i) => (
        <div key={i} style={{ flex: 1, display: "flex", flexDirection: "column", alignItems: "center", gap: 8 }}>
          <div style={{ width: "100%", height: `${(v/max)*170}px`, borderRadius: "7px 7px 3px 3px",
            background: i === data.length-1 ? color : "color-mix(in oklab, var(--accent) 32%, transparent)",
            transition: "height .7s cubic-bezier(.2,.8,.2,1)" }} />
          <span style={{ fontSize: 10.5, color: "var(--ink-4)", fontWeight: 600 }}>T{i+1}</span>
        </div>
      ))}
    </div>
  );
}

/* ---------------- Schedule / Tiến độ ---------------- */
const GANTT = [
  { t: "Khảo sát & gốc toạ độ", disc: "inf", s: 0, w: 18, st: "done" },
  { t: "Mô hình hạ tầng L3", disc: "inf", s: 12, w: 32, st: "done" },
  { t: "Kết cấu ga C", disc: "str", s: 24, w: 30, st: "active" },
  { t: "Vỏ hầm TBM", disc: "inf", s: 30, w: 26, st: "active" },
  { t: "Kiến trúc mặt đứng", disc: "arc", s: 44, w: 28, st: "active" },
  { t: "Hệ thống MEP", disc: "mep", s: 54, w: 30, st: "next" },
  { t: "Tổ hợp & kiểm tra va chạm", disc: "str", s: 70, w: 22, st: "next" },
  { t: "Bàn giao mô hình hoàn công", disc: "arc", s: 84, w: 16, st: "next" },
];
function Schedule() {
  return (
    <div className="content">
      <PageHead title="Tiến độ mô hình hoá" sub="Lộ trình BIM theo bộ môn · Q1 → Q4 2026"><Toolbar /></PageHead>
      <div className="card card-pad">
        <div style={{ display: "flex", marginBottom: 14, paddingLeft: 220 }}>
          {["Q1","Q2","Q3","Q4"].map(q => <div key={q} style={{ flex: 1, fontSize: 11.5, fontWeight: 700, color: "var(--ink-4)", letterSpacing: ".06em" }}>{q} 2026</div>)}
        </div>
        <div style={{ position: "relative" }}>
          <div style={{ position: "absolute", left: "calc(220px + 32%)", top: -6, bottom: 0, width: 2, background: "var(--accent)", opacity: .5, zIndex: 2 }}>
            <div style={{ position: "absolute", top: -6, left: -4, width: 10, height: 10, borderRadius: 99, background: "var(--accent)" }} />
            <div style={{ position: "absolute", top: -23, left: 8, fontSize: 10.5, fontWeight: 700, color: "var(--accent)", whiteSpace: "nowrap" }}>Hôm nay</div>
          </div>
          {GANTT.map((g,i) => (
            <div key={i} style={{ display: "flex", alignItems: "center", height: 44 }}>
              <div style={{ width: 220, fontSize: 13, fontWeight: 600, color: "var(--ink-2)", display: "flex", alignItems: "center", gap: 9, paddingRight: 14 }}>
                <span style={{ width: 7, height: 7, borderRadius: 99, background: DISC_COL[g.disc], flex: "none" }} />
                <span style={{ whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{g.t}</span>
              </div>
              <div style={{ flex: 1, position: "relative", height: 26 }}>
                <div style={{ position: "absolute", left: `${g.s}%`, width: `${g.w}%`, top: 3, height: 20, borderRadius: 7,
                  background: g.st === "done" ? `color-mix(in oklab, ${DISC_COL[g.disc]} 55%, transparent)`
                    : g.st === "active" ? DISC_COL[g.disc] : "var(--sunken)",
                  border: g.st === "next" ? "1.5px dashed var(--line)" : "none",
                  display: "flex", alignItems: "center", paddingLeft: 9, overflow: "hidden", whiteSpace: "nowrap" }}>
                  {g.st === "active" && <span style={{ fontSize: 10.5, fontWeight: 800, color: "#fff", whiteSpace: "nowrap" }}>● Đang chạy</span>}
                  {g.st === "done" && <Icon.check size={13} color="#fff" />}
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

/* ---------------- Coverage matrix ---------------- */
function Coverage() {
  const stations = ["Ga A","Ga B","Ga C","Hầm L3-1","Hầm L3-2","Depot"];
  const discs = ["inf","str","arc","mep"];
  const grid = [[100,98,92,88],[96,94,90,82],[94,90,86,79],[100,96,72,64],[98,92,68,58],[90,86,80,76]];
  const cell = (v) => v >= 95 ? "var(--ok)" : v >= 85 ? "var(--inf)" : v >= 75 ? "var(--warn)" : "var(--danger)";
  return (
    <div className="content">
      <PageHead title="Ma trận độ phủ" sub="Tỷ lệ DWG ↔ NWC ↔ IFC theo công trình × bộ môn"><Toolbar /></PageHead>
      <div className="card card-pad">
        <table className="tbl" style={{ tableLayout: "fixed" }}>
          <thead><tr><th style={{ paddingLeft: 14 }}>Công trình</th>
            {discs.map(d => <th key={d} style={{ textAlign: "center" }}>{DISC_NAME[d]}</th>)}</tr></thead>
          <tbody>
            {stations.map((s,ri) => (
              <tr key={s}>
                <td className="t-strong">{s}</td>
                {grid[ri].map((v,ci) => (
                  <td key={ci} style={{ textAlign: "center" }}>
                    <span style={{ display: "inline-flex", alignItems: "center", justifyContent: "center",
                      minWidth: 56, height: 30, borderRadius: 8, fontWeight: 800, fontSize: 13,
                      background: `${cell(v)}1c`, color: cell(v) }} className="tnum">{v}%</span>
                  </td>
                ))}
              </tr>
            ))}
          </tbody>
        </table>
        <div style={{ display: "flex", gap: 18, marginTop: 18, paddingLeft: 14, fontSize: 12, color: "var(--ink-3)", fontWeight: 600 }}>
          {[["≥95% Đầy đủ","var(--ok)"],["85–94% Tốt","var(--inf)"],["75–84% Cần lưu ý","var(--warn)"],["<75% Thiếu","var(--danger)"]].map(([l,c],i)=>(
            <span key={i} style={{ display: "flex", alignItems: "center", gap: 7 }}><span style={{ width: 10, height: 10, borderRadius: 3, background: c }} />{l}</span>
          ))}
        </div>
      </div>
    </div>
  );
}

/* ---------------- Settings ---------------- */
function Settings({ theme, setTheme, accent, setAccent }) {
  const ACCENTS = [["#0d9488","Teal"],["#2563eb","Xanh dương"],["#7c3aed","Tím"],["#e2683c","Cam đất"]];
  return (
    <div className="content">
      <PageHead title="Cài đặt" sub="Tuỳ chỉnh giao diện & quy tắc đồng bộ" />
      <div style={{ maxWidth: 760, display: "flex", flexDirection: "column", gap: 18 }}>
        <div className="card card-pad">
          <div className="card-title" style={{ marginBottom: 4 }}>Giao diện</div>
          <div className="card-sub" style={{ marginBottom: 18 }}>Chế độ hiển thị & màu nhấn thương hiệu</div>
          <div style={{ display: "flex", gap: 12, marginBottom: 22 }}>
            {[["light","Sáng","sun"],["dark","Tối","moon"]].map(([m,l,ic])=>{
              const Ico = Icon[ic];
              return <button key={m} onClick={()=>setTheme(m)} style={{ flex: 1, padding: "16px", borderRadius: 12, cursor: "pointer",
                border: `1.5px solid ${theme===m?"var(--accent)":"var(--line)"}`, background: theme===m?"var(--accent-soft)":"var(--surface)",
                display: "flex", alignItems: "center", gap: 12, color: theme===m?"var(--accent)":"var(--ink-2)", fontWeight: 700, fontSize: 14 }}>
                <Ico size={20} /> {l} {theme===m && <Icon.check size={16} style={{ marginLeft: "auto" }} />}
              </button>;
            })}
          </div>
          <div style={{ fontSize: 12.5, fontWeight: 700, color: "var(--ink-2)", marginBottom: 12 }}>Màu nhấn</div>
          <div style={{ display: "flex", gap: 12 }}>
            {ACCENTS.map(([c,n])=>(
              <button key={c} onClick={()=>setAccent(c)} title={n} style={{ width: 44, height: 44, borderRadius: 12, cursor: "pointer",
                background: c, border: accent===c?"3px solid var(--surface)":"3px solid transparent",
                boxShadow: accent===c?`0 0 0 2px ${c}`:"none" }} />
            ))}
          </div>
        </div>
        <div className="card card-pad">
          <div className="card-title" style={{ marginBottom: 4 }}>Quy tắc đồng bộ</div>
          <div className="card-sub" style={{ marginBottom: 16 }}>Tự động hoá luồng DWG → NWC → IFC</div>
          {[["Tự động xuất NWC khi nạp DWG mới",true],["Cảnh báo khi lệch gốc toạ độ > 0.1m",true],["Tự kiểm tra va chạm sau mỗi lần tổ hợp",true],["Khoá phiên bản đã phê duyệt",false]].map(([l,on],i)=>(
            <div key={i} style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "14px 0", borderTop: i?"1px solid var(--line-soft)":"none" }}>
              <span style={{ fontSize: 13.5, fontWeight: 600, color: "var(--ink-2)" }}>{l}</span>
              <Toggle on={on} />
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function Toggle({ on: init }) {
  const [on, setOn] = useState(init);
  return (
    <button onClick={()=>setOn(!on)} style={{ width: 44, height: 26, borderRadius: 99, border: 0, cursor: "pointer", padding: 3,
      background: on ? "var(--accent)" : "var(--line)", transition: ".2s", display: "flex", justifyContent: on?"flex-end":"flex-start" }}>
      <span style={{ width: 20, height: 20, borderRadius: 99, background: "#fff", boxShadow: "0 1px 3px rgba(0,0,0,.2)", transition: ".2s" }} />
    </button>
  );
}

window.Reports = Reports;
window.Schedule = Schedule;
window.Coverage = Coverage;
window.Settings = Settings;
