// Update profile page (re-uses onboarding inputs in a compact card layout)
// Wired to PrimaAPI.updateMe()

const UpdateProfile = ({ user, onSaved }) => {
  const [form, setForm] = React.useState({
    email: user?.primus_email || user?.email || "",
    fullName: user?.full_name || user?.name || "",
    empCode: user?.emp_code || user?.empCode || "",
    designation: user?.designation || "",
    yoe: user?.yoe ?? "",
    primary: user?.primary_domain || user?.primary || "",
    secondary: user?.secondary_domain || user?.secondary || "",
    skills: [...(user?.skills || [])],
    tools: [...(user?.tools || [])],
    methodologies: [...(user?.methodologies || [])],
    industries: [...(user?.industries || [])],
    regions: [...(user?.regions || [])],
    languages: [...(user?.languages || [])]
  });
  const [dirty, setDirty] = React.useState(false);
  const [saving, setSaving] = React.useState(false);
  const [error, setError] = React.useState(null);
  const set = (k, v) => { setForm(f => ({ ...f, [k]: v })); setDirty(true); };

  const handleSave = async () => {
    setSaving(true);
    setError(null);
    try {
      const payload = {
        full_name: form.fullName,
        yoe: parseInt(form.yoe, 10) || 0,
        primary_domain: form.primary,
        secondary_domain: form.secondary,
        skills: form.skills,
        tools: form.tools,
        methodologies: form.methodologies,
        industries: form.industries,
        regions: form.regions,
        languages: form.languages,
      };
      const updated = await PrimaAPI.updateMe(payload);
      setDirty(false);
      onSaved(updated);
    } catch (e) {
      setError(e.message || "Failed to save profile.");
    } finally {
      setSaving(false);
    }
  };

  return (
    <div className="page">
      <div className="page-head">
        <div>
          <div className="eyebrow"><Icon name="user" size={11} /> Consultant DNA</div>
          <h1 className="page-title">Update <em>profile</em></h1>
          <p className="page-sub">Your expertise drives staffing recommendations and downstream retrieval. Refine as you grow.</p>
        </div>
        <button className="btn primary" disabled={!dirty || saving} onClick={handleSave}>
          {saving ? "Saving…" : <><Icon name="check" size={14} /> Save changes</>}
        </button>
      </div>

      {error && (
        <div style={{ padding: "10px 14px", background: "var(--err-soft, #fef2f2)", color: "var(--err, #dc2626)", borderRadius: 6, fontSize: 13, marginBottom: 16 }}>{error}</div>
      )}

      <div className="grid-2">
        <div className="card">
          <div className="card-head"><h3 className="card-title">Basic details</h3></div>
          <div className="card-body" style={{ display: "flex", flexDirection: "column", gap: 14 }}>
            <Field label="Primus email" required hint="Read-only.">
              <TextInput readOnly value={form.email} />
            </Field>
            <Field label="Full name" required hint={form.email.toLowerCase().endsWith("@primuspartners.in") ? "Synced with HR records." : null}>
              <TextInput value={form.fullName} onChange={e => set("fullName", e.target.value)} readOnly={form.email.toLowerCase().endsWith("@primuspartners.in")} />
            </Field>
            <div className="grid-2">
              <Field label="Employee code" required>
                <TextInput value={form.empCode} readOnly />
              </Field>
              <Field label="Years of exp." required>
                <TextInput type="number" value={form.yoe} onChange={e => set("yoe", e.target.value)} />
              </Field>
            </div>
            <Field label="Designation" required hint={form.email.toLowerCase().endsWith("@primuspartners.in") ? "Synced from Microsoft Graph." : null}>
              <Select value={form.designation} onChange={v => set("designation", v)} options={TAXONOMY.designations} disabled={form.email.toLowerCase().endsWith("@primuspartners.in")} />
            </Field>
          </div>
        </div>

        <div className="card">
          <div className="card-head"><h3 className="card-title">Domain & expertise</h3></div>
          <div className="card-body" style={{ display: "flex", flexDirection: "column", gap: 14 }}>
            <div className="grid-2">
              <Field label="Primary domain" required>
                <Select value={form.primary} onChange={v => set("primary", v)} options={TAXONOMY.domains} />
              </Field>
              <Field label="Secondary domain" optional>
                <Select value={form.secondary} onChange={v => set("secondary", v)} options={TAXONOMY.domains.filter(d => d !== form.primary)} placeholder="Optional…" />
              </Field>
            </div>
            <Field label="Skills" required>
              <MultiSelect values={form.skills} onChange={v => set("skills", v)} options={TAXONOMY.skills} allowCustom />
            </Field>
            <Field label="Tools / Tech" optional>
              <MultiSelect values={form.tools} onChange={v => set("tools", v)} options={TAXONOMY.tools} allowCustom />
            </Field>
            <Field label="Methodologies" optional>
              <MultiSelect values={form.methodologies} onChange={v => set("methodologies", v)} options={TAXONOMY.methodologies} />
            </Field>
          </div>
        </div>

        <div className="card" style={{ gridColumn: "1 / -1" }}>
          <div className="card-head"><h3 className="card-title">Industry & geography</h3></div>
          <div className="card-body" style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 14 }}>
            <Field label="Industries" required>
              <MultiSelect values={form.industries} onChange={v => set("industries", v)} options={TAXONOMY.industries} />
            </Field>
            <Field label="Regions" optional>
              <MultiSelect values={form.regions} onChange={v => set("regions", v)} options={TAXONOMY.regions} />
            </Field>
            <Field label="Languages" optional>
              <MultiSelect values={form.languages} onChange={v => set("languages", v)} options={TAXONOMY.languages} allowCustom />
            </Field>
          </div>
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { UpdateProfile });
