/* Profile & Settings page */
(function () {
  const h = React.createElement;
  const { useState, useEffect } = React;

  function ProfileSettings({ user, onUpdate, onBack }) {
    // ── Profile info state ──
    const [firstName, setFirstName] = useState(user?.first_name || "");
    const [lastName, setLastName] = useState(user?.last_name || "");
    const [company, setCompany] = useState(user?.company || "");
    const [phone, setPhone] = useState(user?.phone_number || "");
    const [profileBusy, setProfileBusy] = useState(false);
    const [profileMsg, setProfileMsg] = useState(null);

    // ── Password state ──
    const [curPwd, setCurPwd] = useState("");
    const [newPwd, setNewPwd] = useState("");
    const [confirmPwd, setConfirmPwd] = useState("");
    const [pwdBusy, setPwdBusy] = useState(false);
    const [pwdMsg, setPwdMsg] = useState(null);

    // Sync fields if parent user object changes
    useEffect(() => {
      if (user) {
        setFirstName(user.first_name || "");
        setLastName(user.last_name || "");
        setCompany(user.company || "");
        setPhone(user.phone_number || "");
      }
    }, [user]);

    const saveProfile = async (e) => {
      e.preventDefault();
      setProfileBusy(true);
      setProfileMsg(null);
      try {
        const updated = await window.API.auth.updateProfile(
          firstName,
          lastName,
          company,
          phone,
        );
        setProfileMsg({
          kind: "success",
          text: "Profile updated successfully.",
        });
        if (onUpdate) onUpdate(updated.user || updated);
      } catch (err) {
        setProfileMsg({
          kind: "danger",
          text: err.message || "Failed to update profile.",
        });
      }
      setProfileBusy(false);
    };

    const changePassword = async (e) => {
      e.preventDefault();
      if (newPwd !== confirmPwd) {
        setPwdMsg({ kind: "danger", text: "New passwords do not match." });
        return;
      }
      if (newPwd.length < 8) {
        setPwdMsg({
          kind: "danger",
          text: "Password must be at least 8 characters.",
        });
        return;
      }
      setPwdBusy(true);
      setPwdMsg(null);
      try {
        await window.API.auth.changePassword(curPwd, newPwd);
        setPwdMsg({ kind: "success", text: "Password changed successfully." });
        setCurPwd("");
        setNewPwd("");
        setConfirmPwd("");
      } catch (err) {
        setPwdMsg({
          kind: "danger",
          text: err.message || "Failed to change password.",
        });
      }
      setPwdBusy(false);
    };

    const { Btn, Card, Callout, Icon } = window;

    const fieldStyle = {
      display: "flex",
      flexDirection: "column",
      gap: 5,
      marginBottom: 16,
    };
    const labelStyle = {
      fontSize: 13,
      color: "var(--fg-subtle)",
      fontWeight: 500,
    };
    const inputStyle = {
      width: "100%",
      padding: "9px 12px",
      background: "var(--bg)",
      border: "1px solid var(--border)",
      borderRadius: 6,
      color: "var(--fg)",
      fontSize: 14,
      fontFamily: "inherit",
      outline: "none",
      boxSizing: "border-box",
    };
    const inputReadonlyStyle = {
      ...inputStyle,
      opacity: 0.55,
      cursor: "not-allowed",
    };
    const rowStyle = {
      display: "grid",
      gridTemplateColumns: "1fr 1fr",
      gap: 14,
    };

    return h(
      "div",
      { style: { maxWidth: 660, margin: "20px auto", padding: "0 0 48px" } },

      // Header
      h(
        "div",
        {
          style: {
            display: "flex",
            alignItems: "center",
            gap: 14,
            marginBottom: 32,
          },
        },
        h(
          "button",
          {
            onClick: onBack,
            style: {
              background: "none",
              border: "1px solid var(--border)",
              borderRadius: 6,
              color: "var(--fg-subtle)",
              cursor: "pointer",
              padding: "6px 14px",
              fontSize: 13,
              display: "flex",
              alignItems: "center",
              gap: 6,
              fontFamily: "inherit",
            },
          },
          h(Icon, { name: "arrow-left", size: 14 }),
          "Back",
        ),
        h(
          "div",
          null,
          h(
            "h1",
            { style: { margin: 0, fontSize: 22, fontWeight: 700 } },
            "Profile & Settings",
          ),
          h(
            "p",
            {
              style: {
                margin: "2px 0 0",
                fontSize: 13,
                color: "var(--fg-subtle)",
              },
            },
            "Manage your account information and security",
          ),
        ),
      ),

      // ── Account info card ──────────────────────────────────────────────────────
      h(
        Card,
        { eyebrow: "Account", title: "Account Information" },
        h(
          "div",
          {
            style: {
              display: "grid",
              gridTemplateColumns: "1fr 1fr",
              gap: 14,
              marginTop: 4,
            },
          },
          h(
            "div",
            { style: fieldStyle },
            h("label", { style: labelStyle }, "Email address"),
            h(
              "div",
              {
                style: {
                  ...inputReadonlyStyle,
                  display: "flex",
                  alignItems: "center",
                  gap: 8,
                },
              },
              h(Icon, {
                name: "mail",
                size: 14,
                style: { color: "var(--fg-subtle)", flexShrink: 0 },
              }),
              user?.email || "—",
            ),
          ),
          h(
            "div",
            { style: fieldStyle },
            h("label", { style: labelStyle }, "Account status"),
            h(
              "div",
              {
                style: {
                  display: "flex",
                  alignItems: "center",
                  gap: 8,
                  marginTop: 2,
                },
              },
              h(
                "span",
                {
                  style: {
                    display: "inline-flex",
                    alignItems: "center",
                    gap: 5,
                    padding: "4px 10px",
                    borderRadius: 20,
                    fontSize: 12,
                    fontWeight: 600,
                    background: user?.email_verified
                      ? "rgba(34,197,94,.12)"
                      : "rgba(234,179,8,.12)",
                    color: user?.email_verified
                      ? "var(--ok, #22c55e)"
                      : "#eab308",
                    border: user?.email_verified
                      ? "1px solid rgba(34,197,94,.2)"
                      : "1px solid rgba(234,179,8,.2)",
                  },
                },
                h(Icon, {
                  name: user?.email_verified ? "check-circle" : "alert-circle",
                  size: 12,
                }),
                user?.email_verified ? "Verified" : "Not verified",
              ),
            ),
          ),
        ),
      ),

      h("div", { style: { height: 16 } }),

      // ── Personal info card ─────────────────────────────────────────────────────
      h(
        Card,
        { eyebrow: "Profile", title: "Personal Information" },
        profileMsg &&
          h(
            "div",
            { style: { marginBottom: 16 } },
            h(Callout, { kind: profileMsg.kind }, profileMsg.text),
          ),
        h(
          "form",
          { onSubmit: saveProfile },
          h(
            "div",
            { style: rowStyle },
            h(
              "div",
              { style: fieldStyle },
              h("label", { style: labelStyle }, "First name"),
              h("input", {
                style: inputStyle,
                value: firstName,
                required: true,
                onChange: (e) => setFirstName(e.target.value),
                onFocus: (e) => (e.target.style.borderColor = "var(--accent)"),
                onBlur: (e) => (e.target.style.borderColor = "var(--border)"),
              }),
            ),
            h(
              "div",
              { style: fieldStyle },
              h("label", { style: labelStyle }, "Last name"),
              h("input", {
                style: inputStyle,
                value: lastName,
                required: true,
                onChange: (e) => setLastName(e.target.value),
                onFocus: (e) => (e.target.style.borderColor = "var(--accent)"),
                onBlur: (e) => (e.target.style.borderColor = "var(--border)"),
              }),
            ),
          ),
          h(
            "div",
            { style: fieldStyle },
            h("label", { style: labelStyle }, "Company"),
            h("input", {
              style: inputStyle,
              value: company,
              onChange: (e) => setCompany(e.target.value),
              onFocus: (e) => (e.target.style.borderColor = "var(--accent)"),
              onBlur: (e) => (e.target.style.borderColor = "var(--border)"),
              placeholder: "Sunridge Solar LLC",
            }),
          ),
          h(
            "div",
            { style: fieldStyle },
            h("label", { style: labelStyle }, "Phone number"),
            h("input", {
              style: inputStyle,
              value: phone,
              type: "tel",
              onChange: (e) => setPhone(e.target.value),
              onFocus: (e) => (e.target.style.borderColor = "var(--accent)"),
              onBlur: (e) => (e.target.style.borderColor = "var(--border)"),
              placeholder: "(555) 000-0000",
            }),
          ),
          h(
            "div",
            { style: { marginTop: 8 } },
            h(
              "button",
              {
                type: "submit",
                disabled: profileBusy,
                style: {
                  padding: "9px 22px",
                  background: "var(--accent, #f97316)",
                  color: "#fff",
                  border: "none",
                  borderRadius: 6,
                  fontSize: 14,
                  fontWeight: 600,
                  cursor: profileBusy ? "not-allowed" : "pointer",
                  opacity: profileBusy ? 0.65 : 1,
                  fontFamily: "inherit",
                },
              },
              profileBusy ? "Saving…" : "Save changes",
            ),
          ),
        ),
      ),

      h("div", { style: { height: 16 } }),

      // ── Change password card ───────────────────────────────────────────────────
      h(
        Card,
        { eyebrow: "Security", title: "Change Password" },
        pwdMsg &&
          h(
            "div",
            { style: { marginBottom: 16 } },
            h(Callout, { kind: pwdMsg.kind }, pwdMsg.text),
          ),
        h(
          "form",
          { onSubmit: changePassword },
          h(
            "div",
            { style: fieldStyle },
            h("label", { style: labelStyle }, "Current password"),
            h("input", {
              style: inputStyle,
              type: "password",
              value: curPwd,
              required: true,
              onChange: (e) => setCurPwd(e.target.value),
              onFocus: (e) => (e.target.style.borderColor = "var(--accent)"),
              onBlur: (e) => (e.target.style.borderColor = "var(--border)"),
              autoComplete: "current-password",
            }),
          ),
          h(
            "div",
            { style: rowStyle },
            h(
              "div",
              { style: fieldStyle },
              h("label", { style: labelStyle }, "New password"),
              h("input", {
                style: inputStyle,
                type: "password",
                value: newPwd,
                required: true,
                onChange: (e) => setNewPwd(e.target.value),
                onFocus: (e) => (e.target.style.borderColor = "var(--accent)"),
                onBlur: (e) => (e.target.style.borderColor = "var(--border)"),
                autoComplete: "new-password",
                placeholder: "Min. 8 characters",
              }),
            ),
            h(
              "div",
              { style: fieldStyle },
              h("label", { style: labelStyle }, "Confirm new password"),
              h("input", {
                style: inputStyle,
                type: "password",
                value: confirmPwd,
                required: true,
                onChange: (e) => setConfirmPwd(e.target.value),
                onFocus: (e) => (e.target.style.borderColor = "var(--accent)"),
                onBlur: (e) => (e.target.style.borderColor = "var(--border)"),
                autoComplete: "new-password",
                placeholder: "Repeat new password",
              }),
            ),
          ),
          h(
            "div",
            { style: { marginTop: 8 } },
            h(
              "button",
              {
                type: "submit",
                disabled: pwdBusy,
                style: {
                  padding: "9px 22px",
                  background: "var(--accent, #f97316)",
                  color: "#fff",
                  border: "none",
                  borderRadius: 6,
                  fontSize: 14,
                  fontWeight: 600,
                  cursor: pwdBusy ? "not-allowed" : "pointer",
                  opacity: pwdBusy ? 0.65 : 1,
                  fontFamily: "inherit",
                },
              },
              pwdBusy ? "Changing…" : "Change password",
            ),
          ),
        ),
      ),
    );
  }

  window.ProfileSettings = ProfileSettings;
})();
