/* global React, Icon */
const { useState: useStateP, useEffect: useEffectP } = React;

// ==================== PROFILE ====================
function ProfileScreen({ t, lang, setLang }) {
  const [profile, setProfile] = useStateP(null);
  const [loading, setLoading] = useStateP(true);
  const [err, setErr]         = useStateP(null);

  // Form state
  const [fullName, setFullName] = useStateP("");
  const [locale,   setLocaleVal] = useStateP("fr");
  const [savingProfile, setSavingProfile] = useStateP(false);
  const [profileMsg, setProfileMsg]       = useStateP(null);

  // Password change
  const [pwd1, setPwd1] = useStateP("");
  const [pwd2, setPwd2] = useStateP("");
  const [savingPwd, setSavingPwd] = useStateP(false);
  const [pwdMsg,  setPwdMsg]      = useStateP(null);

  // Default display currency (via the same hook used by the topbar)
  const { currency, setCurrency, rates } = window.melr.useCurrency();

  useEffectP(() => {
    let cancelled = false;
    (async () => {
      try {
        const p = await window.melr.currentProfile();
        if (cancelled) return;
        if (!p) { setErr("not_logged_in"); setLoading(false); return; }
        setProfile(p);
        setFullName(p.full_name || "");
        setLocaleVal(p.locale || "fr");
      } catch (e) {
        if (!cancelled) setErr(e.message);
      } finally {
        if (!cancelled) setLoading(false);
      }
    })();
    return () => { cancelled = true; };
  }, []);

  if (loading) return <div className="page"><div className="page-body" style={{ padding: 40 }}>{lang === "fr" ? "Chargement du profil…" : "Loading profile…"}</div></div>;
  if (err === "not_logged_in") return <div className="page"><div className="page-body" style={{ padding: 40, color: "#b91c1c" }}>{lang === "fr" ? "Connectez-vous pour accéder à votre profil." : "Sign in to access your profile."}</div></div>;

  const saveProfile = async (e) => {
    e.preventDefault();
    setProfileMsg(null); setSavingProfile(true);
    try {
      const patch = { full_name: fullName.trim(), locale };
      const updated = await window.melr.updateProfile(patch);
      setProfile(updated);
      // Sync the global language toggle if it changed
      if (setLang && locale !== lang) setLang(locale);
      setProfileMsg({ tone: "success", text: lang === "fr" ? "Profil mis à jour." : "Profile updated." });
    } catch (e2) {
      setProfileMsg({ tone: "danger", text: e2.message });
    } finally {
      setSavingProfile(false);
    }
  };

  const savePwd = async (e) => {
    e.preventDefault();
    setPwdMsg(null);
    if (pwd1.length < 6) { setPwdMsg({ tone: "danger", text: lang === "fr" ? "Min. 6 caractères." : "Min 6 characters." }); return; }
    if (pwd1 !== pwd2)   { setPwdMsg({ tone: "danger", text: lang === "fr" ? "Les deux mots de passe ne correspondent pas." : "Passwords don't match." }); return; }
    setSavingPwd(true);
    try {
      await window.melr.changePassword(pwd1);
      setPwd1(""); setPwd2("");
      setPwdMsg({ tone: "success", text: lang === "fr" ? "Mot de passe modifié." : "Password changed." });
    } catch (e2) {
      setPwdMsg({ tone: "danger", text: e2.message });
    } finally {
      setSavingPwd(false);
    }
  };

  const inp = { padding: "8px 10px", borderRadius: 6, border: "1px solid var(--line)", fontSize: 13, background: "var(--bg, white)", color: "var(--text, #111)" };
  const lbl = { fontSize: 11, opacity: 0.75 };

  return (
    <div className="page">
      <div className="page-header">
        <div className="page-eyebrow">{lang === "fr" ? "MON COMPTE" : "MY ACCOUNT"}</div>
        <div className="page-header-row">
          <div>
            <h1 className="page-title">{lang === "fr" ? "Mon profil" : "My profile"}</h1>
            <div className="page-sub">{profile && profile.email}</div>
          </div>
        </div>
      </div>

      <div className="page-body" style={{ display: "grid", gap: 18, gridTemplateColumns: "1fr 1fr" }}>

        {/* === Informations === */}
        <form onSubmit={saveProfile} className="card" style={{ padding: 20 }}>
          <div style={{ fontSize: 15, fontWeight: 600, marginBottom: 12 }}>
            {lang === "fr" ? "Informations" : "Information"}
          </div>
          <div style={{ display: "grid", gap: 10 }}>
            <label style={{ display: "grid", gap: 4 }}>
              <span style={lbl}>{lang === "fr" ? "Nom complet" : "Full name"}</span>
              <input value={fullName} onChange={(e) => setFullName(e.target.value)} required style={inp} />
            </label>
            <label style={{ display: "grid", gap: 4 }}>
              <span style={lbl}>{lang === "fr" ? "Email" : "Email"}</span>
              <input value={profile.email || ""} disabled style={{ ...inp, opacity: 0.6, cursor: "not-allowed" }} />
            </label>
            <label style={{ display: "grid", gap: 4 }}>
              <span style={lbl}>{lang === "fr" ? "Langue par défaut" : "Default language"}</span>
              <select value={locale} onChange={(e) => setLocaleVal(e.target.value)} style={inp}>
                <option value="fr">Français</option>
                <option value="en">English</option>
              </select>
            </label>
            {profile.organization_id ? (
              <div className="text-faint" style={{ fontSize: 12 }}>
                <Icon.check className="xxs" /> {lang === "fr" ? "Membre de l'organisation REFT Africa" : "Member of REFT Africa"}
              </div>
            ) : (
              <div style={{ color: "#92400e", fontSize: 12 }}>
                <Icon.info className="xxs" /> {lang === "fr"
                  ? "Votre compte n'est pas encore rattaché à une organisation. Demandez à un administrateur de vous ajouter."
                  : "Your account is not yet assigned to an organization. Ask an admin to add you."}
              </div>
            )}
            {profileMsg && (
              <div style={{
                marginTop: 4, padding: "8px 10px", borderRadius: 6, fontSize: 12,
                background: profileMsg.tone === "success" ? "#dcfce7" : "#fee2e2",
                color:      profileMsg.tone === "success" ? "#166534" : "#991b1b",
              }}>{profileMsg.text}</div>
            )}
            <div style={{ display: "flex", justifyContent: "flex-end", marginTop: 4 }}>
              <button type="submit" disabled={savingProfile}
                style={{ padding: "8px 14px", borderRadius: 6, border: 0, background: "#2563eb", color: "white", cursor: "pointer", fontWeight: 600 }}>
                {savingProfile ? "…" : (lang === "fr" ? "Enregistrer" : "Save")}
              </button>
            </div>
          </div>
        </form>

        {/* === Devise préférée === */}
        <div className="card" style={{ padding: 20 }}>
          <div style={{ fontSize: 15, fontWeight: 600, marginBottom: 12 }}>
            {lang === "fr" ? "Devise d'affichage préférée" : "Preferred display currency"}
          </div>
          <div className="text-faint" style={{ fontSize: 12, marginBottom: 12 }}>
            {lang === "fr"
              ? "Choisissez la devise dans laquelle les montants sont affichés sur tous les écrans (Dashboard, Projets, Détail, etc.). Cette préférence est sauvegardée sur votre navigateur."
              : "Pick the currency for amounts shown across all screens. The choice is saved on your browser."}
          </div>
          <div style={{ display: "grid", gap: 6 }}>
            {Object.entries(rates).map(([code, meta]) => (
              <button key={code} type="button"
                onClick={() => setCurrency(code)}
                className={"btn sm" + (code === currency ? " primary" : "")}
                style={{ justifyContent: "flex-start", textAlign: "left" }}>
                <span className="mono" style={{ width: 50, fontWeight: 600 }}>{code}</span>
                <span style={{ flex: 1 }}>{meta.name}</span>
                <span className="text-faint" style={{ fontSize: 11 }}>1 EUR = {meta.rate} {meta.symbol}</span>
                {code === currency && <Icon.check className="xxs" />}
              </button>
            ))}
          </div>
          <div className="text-faint" style={{ fontSize: 11, marginTop: 10 }}>
            {lang === "fr" ? "Vous pouvez ajouter d'autres devises depuis le sélecteur dans la barre du haut." : "You can add more currencies from the topbar selector."}
          </div>
        </div>

        {/* === Mot de passe === */}
        <form onSubmit={savePwd} className="card" style={{ padding: 20 }}>
          <div style={{ fontSize: 15, fontWeight: 600, marginBottom: 12 }}>
            {lang === "fr" ? "Changer le mot de passe" : "Change password"}
          </div>
          <div style={{ display: "grid", gap: 10 }}>
            <label style={{ display: "grid", gap: 4 }}>
              <span style={lbl}>{lang === "fr" ? "Nouveau mot de passe" : "New password"}</span>
              <input type="password" value={pwd1} onChange={(e) => setPwd1(e.target.value)}
                autoComplete="new-password" required minLength={6} style={inp} />
            </label>
            <label style={{ display: "grid", gap: 4 }}>
              <span style={lbl}>{lang === "fr" ? "Confirmer" : "Confirm"}</span>
              <input type="password" value={pwd2} onChange={(e) => setPwd2(e.target.value)}
                autoComplete="new-password" required minLength={6} style={inp} />
            </label>
            {pwdMsg && (
              <div style={{
                padding: "8px 10px", borderRadius: 6, fontSize: 12,
                background: pwdMsg.tone === "success" ? "#dcfce7" : "#fee2e2",
                color:      pwdMsg.tone === "success" ? "#166534" : "#991b1b",
              }}>{pwdMsg.text}</div>
            )}
            <div style={{ display: "flex", justifyContent: "flex-end", marginTop: 4 }}>
              <button type="submit" disabled={savingPwd}
                style={{ padding: "8px 14px", borderRadius: 6, border: 0, background: "#7c3aed", color: "white", cursor: "pointer", fontWeight: 600 }}>
                {savingPwd ? "…" : (lang === "fr" ? "Modifier" : "Update")}
              </button>
            </div>
          </div>
        </form>

        {/* === Session === */}
        <div className="card" style={{ padding: 20 }}>
          <div style={{ fontSize: 15, fontWeight: 600, marginBottom: 12 }}>
            {lang === "fr" ? "Session" : "Session"}
          </div>
          <div style={{ display: "grid", gap: 8 }}>
            <div className="text-faint" style={{ fontSize: 12 }}>
              {lang === "fr" ? "Vous êtes connecté en tant que" : "Signed in as"} <b>{profile.email}</b>
            </div>
            <button type="button"
              onClick={async () => { await window.melr.supabase.auth.signOut(); }}
              style={{ padding: "8px 14px", borderRadius: 6, border: "1px solid var(--line)", background: "transparent", cursor: "pointer", marginTop: 8, alignSelf: "flex-start" }}>
              <Icon.logout className="xxs" /> {lang === "fr" ? "Se déconnecter" : "Sign out"}
            </button>
          </div>
        </div>

      </div>
    </div>
  );
}

window.ProfileScreen = ProfileScreen;
