/* profile.jsx — Configurações (perfil e senha) via API. */

function SettingsModal({ user, initialTab, onClose, onSave, pushToast }) {
  const { Ic, FX } = window;
  const [tab, setTab] = React.useState(initialTab || "perfil");
  const [name, setName] = React.useState(user.name || "");
  const [roleTitle, setRoleTitle] = React.useState(user.role_title || "");
  const [email, setEmail] = React.useState(user.email || "");
  const [avatar, setAvatar] = React.useState(user.avatar || null);
  const [cur, setCur] = React.useState("");
  const [pw, setPw] = React.useState("");
  const [pw2, setPw2] = React.useState("");
  const [err, setErr] = React.useState("");
  const [busy, setBusy] = React.useState(false);
  const fileRef = React.useRef(null);

  const initials = (name || "U").trim().split(/\s+/).map(w => w[0]).slice(0, 2).join("").toUpperCase();

  const pickFile = () => fileRef.current && fileRef.current.click();
  const onFile = (e) => {
    const f = e.target.files && e.target.files[0];
    if (!f) return;
    if (!f.type.startsWith("image/")) { pushToast("⚠️", "Selecione uma imagem"); return; }
    if (f.size > 200 * 1024) { pushToast("⚠️", "Imagem grande demais (máx 200 KB)"); return; }
    const reader = new FileReader();
    reader.onload = () => { setAvatar(reader.result); FX.sfx.play("click"); };
    reader.readAsDataURL(f);
  };

  const saveProfile = async () => {
    setErr("");
    if (!name.trim()) { setErr("O nome não pode ficar vazio."); return; }
    setBusy(true);
    try {
      const res = await window.Api.users.update(user.id, {
        name: name.trim(),
        role_title: roleTitle.trim() || "Membro",
        avatar,
      });
      onSave(res.user);
      pushToast("✅", "Perfil atualizado!");
      onClose();
    } catch (e) { setErr(e.message); } finally { setBusy(false); }
  };

  const saveEmail = async () => {
    setErr("");
    setBusy(true);
    try {
      const res = await window.Api.users.update(user.id, { email: email.trim() });
      onSave(res.user);
      pushToast("✅", "E-mail salvo!");
      onClose();
    } catch (e) { setErr(e.message); } finally { setBusy(false); }
  };

  const savePassword = async () => {
    setErr("");
    if (!cur) { setErr("Informe a senha atual."); return; }
    if (pw.length < 12) { setErr("A nova senha precisa de ao menos 12 caracteres."); return; }
    if (pw !== pw2) { setErr("As senhas não coincidem."); return; }
    setBusy(true);
    try {
      await window.Api.users.update(user.id, { password: pw, current_password: cur });
      pushToast("🔒", "Senha alterada!");
      setCur(""); setPw(""); setPw2("");
      onClose();
    } catch (e) { setErr(e.message); } finally { setBusy(false); }
  };

  return (
    <div className="modal" onMouseDown={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="modal-box settings-box">
        <button className="detail-close" style={{ top: 18, right: 18 }} onClick={onClose} aria-label="Fechar"><Ic.Close size={20} /></button>
        <h2>Configurações</h2>
        <p className="sub">Gerencie seu perfil e sua conta.</p>

        <div className="set-tabs">
          <button className={tab === "perfil" ? "on" : ""} onClick={() => { setTab("perfil"); setErr(""); }}>
            <Ic.User size={16} /> Perfil
          </button>
          <button className={tab === "conta" ? "on" : ""} onClick={() => { setTab("conta"); setErr(""); }}>
            <Ic.Lock size={16} /> Conta e senha
          </button>
        </div>

        {tab === "perfil" && (
          <div className="set-pane">
            <div className="avatar-edit">
              {avatar
                ? <img className="avatar-lg" src={avatar} alt="Avatar" />
                : <span className="avatar-lg avatar-initials">{initials}</span>}
              <div className="avatar-actions">
                <button className="btn-ghost" onClick={pickFile}><Ic.Image size={16} /> Trocar imagem</button>
                {avatar && <button className="btn-ghost danger" onClick={() => setAvatar(null)}><Ic.Trash size={16} /> Remover</button>}
                <input ref={fileRef} type="file" accept="image/*" hidden onChange={onFile} />
                <p className="hint">PNG, JPG ou WEBP — máx 200 KB, recomendado quadrado.</p>
              </div>
            </div>
            <div className="field">
              <label>Nome</label>
              <input className="input" value={name} onChange={e => setName(e.target.value)} placeholder="Seu nome" disabled={busy} />
            </div>
            <div className="field">
              <label>Cargo</label>
              <input className="input" value={roleTitle} onChange={e => setRoleTitle(e.target.value)} placeholder="Ex: Game Developer" disabled={busy} />
            </div>
            {err && <p className="form-err">{err}</p>}
            <div className="modal-foot">
              <button className="btn-ghost" onClick={onClose} disabled={busy}>Cancelar</button>
              <button className="btn-primary" onClick={saveProfile} disabled={busy}><Ic.Check size={18} /> {busy ? "Salvando…" : "Salvar perfil"}</button>
            </div>
          </div>
        )}

        {tab === "conta" && (
          <div className="set-pane">
            <div className="field">
              <label>E-mail</label>
              <div className="login-field" style={{ height: 48, margin: 0 }}>
                <Ic.Mail />
                <input type="email" value={email} onChange={e => setEmail(e.target.value)} placeholder="voce@exemplo.com" disabled={busy} />
              </div>
            </div>
            <div className="set-divider"><span>Alterar senha</span></div>
            <div className="field">
              <label>Senha atual</label>
              <input className="input" type="password" value={cur} onChange={e => setCur(e.target.value)} disabled={busy} />
            </div>
            <div className="field two">
              <div>
                <label>Nova senha (mín. 12)</label>
                <input className="input" type="password" value={pw} onChange={e => setPw(e.target.value)} disabled={busy} />
              </div>
              <div>
                <label>Confirmar</label>
                <input className="input" type="password" value={pw2} onChange={e => setPw2(e.target.value)} disabled={busy} />
              </div>
            </div>
            {err && <p className="form-err">{err}</p>}
            <div className="modal-foot">
              <button className="btn-ghost" onClick={saveEmail} disabled={busy}>Salvar e-mail</button>
              <button className="btn-primary" onClick={savePassword} disabled={busy}><Ic.Lock size={18} /> {busy ? "Alterando…" : "Alterar senha"}</button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

window.SettingsModal = SettingsModal;
