/* hub-settings.jsx — trang Cài đặt (Hồ sơ · Giao diện · Thông báo · Tài khoản) */
(function () {
  const { useState } = React;
  const firstChar = (s) => ((s || "").trim()[0] || "?").toUpperCase();

  // Đọc ảnh → center-crop vuông → resize 160px → JPEG dataURL nhỏ (~10-20KB) để lưu thẳng vào profiles.avatar_url
  function fileToAvatarDataURL(file, size = 160) {
    return new Promise((resolve, reject) => {
      if (!file || !file.type || !file.type.startsWith("image/")) return reject(new Error("Tệp không phải ảnh"));
      const img = new Image();
      const url = URL.createObjectURL(file);
      img.onload = () => {
        URL.revokeObjectURL(url);
        const s = Math.min(img.width, img.height);
        const sx = (img.width - s) / 2, sy = (img.height - s) / 2;
        const c = document.createElement("canvas");
        c.width = c.height = size;
        c.getContext("2d").drawImage(img, sx, sy, s, s, 0, 0, size, size);
        resolve(c.toDataURL("image/jpeg", 0.82));
      };
      img.onerror = () => { URL.revokeObjectURL(url); reject(new Error("Không đọc được ảnh")); };
      img.src = url;
    });
  }

  const TABS = [
    { id: "profile", label: "Hồ sơ", icon: "users" },
    { id: "appearance", label: "Giao diện", icon: "sun" },
    { id: "notifications", label: "Thông báo", icon: "bell" },
    { id: "account", label: "Tài khoản & bảo mật", icon: "shield" },
  ];
  const ACCENTS = [
    { hex: "#0d9488", name: "Teal" },
    { hex: "#2563eb", name: "Lam" },
    { hex: "#7c3aed", name: "Tím" },
    { hex: "#e2683c", name: "Cam" },
  ];

  function Msg({ msg }) {
    if (!msg) return null;
    return <div className={"set-msg " + (msg.ok ? "ok" : "err")}>{msg.text}</div>;
  }

  function ProfileTab({ auth, onLogout }) {
    const prof = (auth && auth.profile) || {};
    const [fullName, setFullName] = useState(prof.full_name || "");
    const [avatar, setAvatar] = useState(prof.avatar_url || null);
    const acctType = (prof.role === "admin") ? "Quản trị viên" : "Người dùng";
    const [busy, setBusy] = useState(false);
    const [msg, setMsg] = useState(null);
    const fileRef = React.useRef(null);
    const email = (auth && auth.user && auth.user.email) || "—";
    const onFile = async (e) => {
      const f = e.target.files && e.target.files[0]; e.target.value = "";
      if (!f) return;
      try { setAvatar(await fileToAvatarDataURL(f)); setMsg(null); }
      catch (err) { setMsg({ ok: false, text: err.message }); }
    };
    const save = async () => {
      setBusy(true); setMsg(null);
      try {
        await cdeData.updateMyProfile({ full_name: fullName.trim(), avatar_url: avatar });
        setMsg({ ok: true, text: "Đã lưu hồ sơ. Tải lại trang để cập nhật mọi nơi." });
      } catch (e) { setMsg({ ok: false, text: e.message || "Lưu thất bại" }); }
      finally { setBusy(false); }
    };
    return (
      <div className="set-section">
        <div className="set-h">Hồ sơ cá nhân</div>
        <div className="set-profile-head">
          <div className="set-avatar" style={avatar ? { padding: 0, overflow: "hidden", background: "#fff" } : undefined}>
            {avatar ? <img src={avatar} alt="" style={{ width: "100%", height: "100%", objectFit: "cover", display: "block" }} /> : firstChar(fullName || email)}
          </div>
          <div className="set-profile-meta">
            <div className="n">{fullName || "(chưa đặt tên)"}</div><div className="r">{email}</div>
            <div style={{ display: "flex", gap: 8, marginTop: 9 }}>
              <button className="btn sm" onClick={() => fileRef.current && fileRef.current.click()}><Icon.upload size={13} /> Đổi ảnh</button>
              {avatar && <button className="btn sm" onClick={() => setAvatar(null)}><Icon.trash size={13} /> Xoá ảnh</button>}
            </div>
            <input ref={fileRef} type="file" accept="image/*" style={{ display: "none" }} onChange={onFile} />
          </div>
        </div>
        <label className="set-label">Họ và tên</label>
        <input className="set-input" value={fullName} onChange={e => setFullName(e.target.value)} placeholder="Họ và tên" />
        <label className="set-label">Loại tài khoản</label>
        <input className="set-input" value={acctType} disabled />
        <label className="set-label">Email</label>
        <input className="set-input" value={email} disabled />
        <Msg msg={msg} />
        <button className="btn set-save" disabled={busy} onClick={save}>{busy ? "Đang lưu…" : "Lưu thay đổi"}</button>
        {onLogout && <>
          <div className="set-divider" />
          <button className="btn set-logout" onClick={onLogout}>Đăng xuất</button>
        </>}
      </div>
    );
  }

  function AppearanceTab({ theme, setTheme, accent, setAccent }) {
    return (
      <div className="set-section">
        <div className="set-h">Giao diện</div>
        <label className="set-label">Chế độ</label>
        <div className="set-theme-row">
          <div className={"set-theme-opt " + (theme === "light" ? "active" : "")} onClick={() => setTheme("light")}>
            <Icon.sun size={18} /> Sáng</div>
          <div className={"set-theme-opt " + (theme === "dark" ? "active" : "")} onClick={() => setTheme("dark")}>
            <Icon.moon size={18} /> Tối</div>
        </div>
        <label className="set-label">Màu nhấn</label>
        <div className="set-accent">
          {ACCENTS.map(a => (
            <button key={a.hex} className={"set-swatch " + (accent === a.hex ? "active" : "")}
              title={a.name} style={{ background: a.hex }} onClick={() => setAccent(a.hex)}>
              {accent === a.hex && <Icon.check size={15} />}
            </button>
          ))}
        </div>
      </div>
    );
  }

  function NotificationsTab() {
    const [types, setTypes] = useState({ assign: true, approve: true, comment: true, system: false });
    const [chans, setChans] = useState({ app: true, email: false, telegram: false });
    const [msg, setMsg] = useState(null);
    const Toggle = ({ on, onClick, label }) => (
      <div className="set-row"><span>{label}</span>
        <button className={"set-toggle " + (on ? "on" : "")} onClick={onClick}><span className="knob" /></button></div>
    );
    return (
      <div className="set-section">
        <div className="set-h">Thông báo</div>
        <label className="set-label">Loại thông báo</label>
        <Toggle label="Giao việc" on={types.assign} onClick={() => setTypes({ ...types, assign: !types.assign })} />
        <Toggle label="Phê duyệt" on={types.approve} onClick={() => setTypes({ ...types, approve: !types.approve })} />
        <Toggle label="Bình luận" on={types.comment} onClick={() => setTypes({ ...types, comment: !types.comment })} />
        <Toggle label="Hệ thống" on={types.system} onClick={() => setTypes({ ...types, system: !types.system })} />
        <label className="set-label" style={{ marginTop: 18 }}>Kênh nhận</label>
        <Toggle label="Trong ứng dụng" on={chans.app} onClick={() => setChans({ ...chans, app: !chans.app })} />
        <Toggle label="Email" on={chans.email} onClick={() => setChans({ ...chans, email: !chans.email })} />
        <Toggle label="Telegram" on={chans.telegram} onClick={() => setChans({ ...chans, telegram: !chans.telegram })} />
        <Msg msg={msg} />
        <button className="btn set-save" onClick={() => setMsg({ ok: true, text: "Đã lưu tuỳ chọn thông báo." })}>Lưu</button>
      </div>
    );
  }

  function AccountTab({ auth, onLogout }) {
    const email = (auth && auth.user && auth.user.email) || "—";
    const [pw, setPw] = useState("");
    const [pw2, setPw2] = useState("");
    const [busy, setBusy] = useState(false);
    const [msg, setMsg] = useState(null);
    const change = async () => {
      setMsg(null);
      if (pw.length < 6) return setMsg({ ok: false, text: "Mật khẩu tối thiểu 6 ký tự." });
      if (pw !== pw2) return setMsg({ ok: false, text: "Mật khẩu nhập lại không khớp." });
      setBusy(true);
      try {
        await cdeAuth.changePassword(pw);
        setMsg({ ok: true, text: "Đổi mật khẩu thành công." });
        setPw(""); setPw2("");
      } catch (e) { setMsg({ ok: false, text: e.message || "Đổi mật khẩu thất bại" }); }
      finally { setBusy(false); }
    };
    return (
      <div className="set-section">
        <div className="set-h">Tài khoản & bảo mật</div>
        <label className="set-label">Email đăng nhập</label>
        <input className="set-input" value={email} disabled />
        <label className="set-label">Mật khẩu mới</label>
        <input className="set-input" type="password" value={pw} onChange={e => setPw(e.target.value)} placeholder="Tối thiểu 6 ký tự" />
        <label className="set-label">Nhập lại mật khẩu</label>
        <input className="set-input" type="password" value={pw2} onChange={e => setPw2(e.target.value)} placeholder="Nhập lại" />
        <Msg msg={msg} />
        <button className="btn set-save" disabled={busy} onClick={change}>{busy ? "Đang đổi…" : "Đổi mật khẩu"}</button>
        <div className="set-divider" />
        <button className="btn set-logout" onClick={onLogout}>Đăng xuất khỏi thiết bị này</button>
      </div>
    );
  }

  function SettingsPage({ auth, theme, setTheme, accent, setAccent, onLogout }) {
    const [tab, setTab] = useState("profile");
    return (
      <div className="set-wrap">
        <nav className="set-nav">
          {TABS.map(t => (
            <div key={t.id} className={"set-nav-item " + (tab === t.id ? "active" : "")} onClick={() => setTab(t.id)}>
              {React.createElement(Icon[t.icon], { size: 16 })}<span>{t.label}</span>
            </div>
          ))}
        </nav>
        <div className="set-body">
          {tab === "profile" && <ProfileTab auth={auth} onLogout={onLogout} />}
          {tab === "appearance" && <AppearanceTab theme={theme} setTheme={setTheme} accent={accent} setAccent={setAccent} />}
          {tab === "notifications" && <NotificationsTab />}
          {tab === "account" && <AccountTab auth={auth} onLogout={onLogout} />}
        </div>
      </div>
    );
  }

  window.SettingsPage = SettingsPage;
})();
