const { useState: useStateP } = React;

// Self-service profile page for any logged-in user (admin or CISO): edit own
// name and change password. Email, company and role are not editable here.
function Profile({ api, user, onBack, onUpdated, onLogout }) {
  const [firstName, setFirstName] = useStateP(user.firstName || "");
  const [lastName, setLastName] = useStateP(user.lastName || "");
  const [savingProfile, setSavingProfile] = useStateP(false);
  const [profileMsg, setProfileMsg] = useStateP(null); // {ok, text}

  const [cur, setCur] = useStateP("");
  const [nw, setNw] = useStateP("");
  const [rep, setRep] = useStateP("");
  const [savingPw, setSavingPw] = useStateP(false);
  const [pwMsg, setPwMsg] = useStateP(null);

  const MIN = 10;
  const companyLabel = user.companyName || (user.role === "admin" ? "Datavise · Administration" : "—");

  const saveProfile = async (e) => {
    e && e.preventDefault();
    setProfileMsg(null);
    if (!firstName.trim() || !lastName.trim()) { setProfileMsg({ ok: false, text: "Vor- und Nachname dürfen nicht leer sein." }); return; }
    setSavingProfile(true);
    const res = await api.updateProfile({ firstName: firstName.trim(), lastName: lastName.trim() });
    setSavingProfile(false);
    if (res.ok) { setProfileMsg({ ok: true, text: "Profil gespeichert." }); onUpdated && onUpdated(); }
    else setProfileMsg({ ok: false, text: "Speichern fehlgeschlagen." });
  };

  const savePw = async (e) => {
    e && e.preventDefault();
    setPwMsg(null);
    if (nw.length < MIN) { setPwMsg({ ok: false, text: `Das neue Passwort muss mindestens ${MIN} Zeichen haben.` }); return; }
    if (nw !== rep) { setPwMsg({ ok: false, text: "Die neuen Passwörter stimmen nicht überein." }); return; }
    setSavingPw(true);
    const res = await api.changePassword(cur, nw);
    setSavingPw(false);
    if (res.ok) { setPwMsg({ ok: true, text: "Passwort aktualisiert." }); setCur(""); setNw(""); setRep(""); return; }
    const map = {
      wrong_current_password: "Das aktuelle Passwort ist nicht korrekt.",
      weak_password: `Das neue Passwort muss mindestens ${MIN} Zeichen haben.`,
      password_reused: "Das neue Passwort muss sich vom aktuellen unterscheiden.",
    };
    setPwMsg({ ok: false, text: map[res.error] || "Passwort konnte nicht geändert werden." });
  };

  const ctrl = { width: "100%", boxSizing: "border-box", fontFamily: "var(--dv-font-sans)", fontSize: 15, padding: "12px 14px", border: "1px solid var(--dv-border)", borderRadius: 8, color: "var(--dv-fg-strong)", background: "#fff", outline: "none", marginBottom: 14 };
  const ro = { ...ctrl, background: "var(--dv-slate-50)", color: "var(--dv-fg-muted)", cursor: "not-allowed" };
  const lbl = { display: "block", fontSize: 13, fontWeight: 600, color: "var(--dv-navy)", marginBottom: 6 };
  const card = { background: "#fff", border: "1px solid var(--dv-border)", borderRadius: 16, boxShadow: "var(--dv-shadow-sm)", padding: 28, marginBottom: 20 };
  const cta = (busy) => ({ background: "var(--dv-green)", color: "#fff", border: "none", fontFamily: "var(--dv-font-sans)", fontWeight: 700, fontSize: 15, padding: "12px 22px", borderRadius: 9999, cursor: busy ? "wait" : "pointer", opacity: busy ? 0.7 : 1, boxShadow: "var(--dv-shadow-sm)" });
  const Note = ({ m }) => m ? <div style={{ display: "flex", gap: 8, alignItems: "center", background: m.ok ? "var(--dv-success-bg)" : "var(--dv-danger-bg)", color: m.ok ? "#15803d" : "#b91c1c", fontSize: 13, padding: "10px 12px", borderRadius: 8, marginBottom: 16 }}><i data-lucide={m.ok ? "check-circle" : "alert-circle"} style={{ width: 16, height: 16 }}></i>{m.text}</div> : null;

  return (
    <div style={{ minHeight: "100vh", background: "var(--dv-slate-50)" }}>
      <header style={{ background: "var(--dv-navy)", color: "#fff", position: "sticky", top: 0, zIndex: 20 }}>
        <div style={{ maxWidth: 760, margin: "0 auto", padding: "0 24px", height: 62, display: "flex", alignItems: "center", justifyContent: "space-between" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
            <img src="./assets/logo-datavise-white.svg" alt="Datavise" style={{ height: 26 }} />
            <span style={{ width: 1, height: 20, background: "rgba(255,255,255,.22)" }}></span>
            <span style={{ fontSize: 14.5, fontWeight: 700 }}>Mein Profil</span>
          </div>
          <button onClick={onBack} style={{ display: "inline-flex", alignItems: "center", gap: 7, background: "transparent", border: "1px solid rgba(255,255,255,.25)", color: "#fff", fontFamily: "var(--dv-font-sans)", fontWeight: 600, fontSize: 13, padding: "7px 14px", borderRadius: 9999, cursor: "pointer" }}>
            <i data-lucide="arrow-left" style={{ width: 15, height: 15 }}></i> Zurück
          </button>
        </div>
      </header>

      <div style={{ maxWidth: 760, margin: "0 auto", padding: "28px 24px" }}>
        {/* Details */}
        <form onSubmit={saveProfile} style={card}>
          <h2 style={{ fontSize: 19, fontWeight: 700, color: "var(--dv-navy)", margin: "0 0 4px" }}>Persönliche Daten</h2>
          <p style={{ fontSize: 13, color: "var(--dv-fg-subtle)", margin: "0 0 20px" }}>E-Mail und Firma sind fest hinterlegt und können hier nicht geändert werden.</p>
          <Note m={profileMsg} />
          <div style={{ display: "flex", gap: 14 }}>
            <div style={{ flex: 1 }}><label style={lbl}>Vorname</label><input style={ctrl} value={firstName} onChange={(e) => setFirstName(e.target.value)} /></div>
            <div style={{ flex: 1 }}><label style={lbl}>Nachname</label><input style={ctrl} value={lastName} onChange={(e) => setLastName(e.target.value)} /></div>
          </div>
          <label style={lbl}>E-Mail</label>
          <input style={ro} value={user.email} disabled />
          <label style={lbl}>Firma</label>
          <input style={ro} value={companyLabel} disabled />
          <button type="submit" disabled={savingProfile} className="dv-portal-cta" style={cta(savingProfile)}>{savingProfile ? "Speichern …" : "Änderungen speichern"}</button>
        </form>

        {/* Password */}
        <form onSubmit={savePw} style={card}>
          <h2 style={{ fontSize: 19, fontWeight: 700, color: "var(--dv-navy)", margin: "0 0 4px" }}>Passwort ändern</h2>
          <p style={{ fontSize: 13, color: "var(--dv-fg-subtle)", margin: "0 0 20px" }}>Mindestens {MIN} Zeichen. Nach der Änderung bleibst du angemeldet.</p>
          <Note m={pwMsg} />
          <label style={lbl}>Aktuelles Passwort</label>
          <input type="password" style={ctrl} value={cur} onChange={(e) => setCur(e.target.value)} autoComplete="current-password" />
          <label style={lbl}>Neues Passwort</label>
          <input type="password" style={ctrl} value={nw} onChange={(e) => setNw(e.target.value)} autoComplete="new-password" placeholder={`Mindestens ${MIN} Zeichen`} />
          <label style={lbl}>Neues Passwort wiederholen</label>
          <input type="password" style={ctrl} value={rep} onChange={(e) => setRep(e.target.value)} autoComplete="new-password" />
          <button type="submit" disabled={savingPw} className="dv-portal-cta" style={cta(savingPw)}>{savingPw ? "Speichern …" : "Passwort aktualisieren"}</button>
        </form>

        <div style={{ textAlign: "center" }}>
          <button onClick={onLogout} style={{ background: "transparent", border: "none", color: "var(--dv-fg-muted)", fontFamily: "var(--dv-font-sans)", fontSize: 13, cursor: "pointer" }}>Abmelden</button>
        </div>
      </div>
    </div>
  );
}

window.Profile = Profile;
