/* ============================================================
   EBTR — Author Portal: Profile editor
   The author drafts name-line, descriptive title, bio, photo and
   picks a role badge from the CONTROLLED legal list. Badge + title
   are marked "pending editor approval" until an editor confirms them
   (on first acceptance) — so the public byline stays trustworthy.
   ============================================================ */
const { Button: PBtnP, Badge: PBadgeP, Eyebrow: PEyeP } = window.EBTHubDesignSystem_ccdc9d;
const PFIELD = { fontFamily: "var(--font-body)", fontSize: 15, color: "var(--white)", background: "var(--neutral-900)", border: "1px solid var(--border-strong)", borderRadius: "var(--radius-sm)", padding: "12px 14px", outline: "none", width: "100%" };

function PField({ label, hint, children }) {
  return (
    <label style={{ display: "flex", flexDirection: "column", gap: 8, marginBottom: 22 }}>
      <span style={{ fontFamily: "var(--font-ui)", fontSize: 11, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--text-secondary)" }}>{label}</span>
      {hint && <span style={{ fontFamily: "var(--font-body)", fontSize: 13, lineHeight: 1.5, color: "var(--text-muted)", marginTop: -2 }}>{hint}</span>}
      {children}
    </label>
  );
}

function PProfile({ me, onSave, onBack }) {
  const D = window.EBTR_AUTHOR;
  const [form, setForm] = React.useState({ name: me.name, title: me.title || "", bio: me.bio || "", badges: me.badges || (me.badge && me.badge.label !== "— none" ? [me.badge] : []) });
  const hasBadge = (label) => (form.badges || []).some((x) => x.label === label);
  const toggleBadge = (b) => setForm((f) => {
    if (b.label === "— none") return { ...f, badges: [] };
    const has = (f.badges || []).some((x) => x.label === b.label);
    return { ...f, badges: has ? f.badges.filter((x) => x.label !== b.label) : [...(f.badges || []), { label: b.label, variant: b.variant }] };
  });
  const [saved, setSaved] = React.useState(false);
  const set = (k, v) => { setForm((f) => ({ ...f, [k]: v })); setSaved(false); };
  const initials = (form.name || "?").split(" ").map((x) => x[0]).filter(Boolean).slice(0, 2).join("");
  const save = () => { onSave({ ...form, initials }); setSaved(true); };

  return (
    <main style={{ maxWidth: 1100, margin: "0 auto", padding: "44px var(--space-7) 80px" }}>
      <button onClick={onBack} style={{ display: "inline-flex", alignItems: "center", gap: 9, background: "none", border: "none", padding: 0, cursor: "pointer", fontFamily: "var(--font-ui)", fontSize: 11, letterSpacing: "0.12em", textTransform: "uppercase", color: "var(--text-secondary)", marginBottom: 26 }}>← Dashboard</button>
      <PEyeP color="orange">Your profile</PEyeP>
      <h1 style={{ fontFamily: "var(--font-ui)", fontSize: "clamp(28px,3vw,40px)", letterSpacing: "0.02em", textTransform: "uppercase", color: "var(--white)", margin: "12px 0 8px" }}>Author profile</h1>
      <p style={{ fontFamily: "var(--font-body)", fontSize: 16, lineHeight: 1.6, color: "var(--text-secondary)", maxWidth: 680, margin: "0 0 36px" }}>This is what readers see on your byline and the “About the author” block. You draft it here; an editor confirms your role badge and title when they first accept a piece.</p>

      <div className="pf-prof-grid" style={{ display: "grid", gridTemplateColumns: "minmax(0,1fr) 320px", gap: 48, alignItems: "start" }}>
        {/* form */}
        <div style={{ minWidth: 0 }}>
          <PField label="Name" hint="From your EBTHub account.">
            <input value={form.name} onChange={(e) => set("name", e.target.value)} style={{ ...PFIELD, opacity: 0.7 }} readOnly />
          </PField>

          <PField label="Role badges" hint="Select all that apply — you can hold several. Per our statutes, editors confirm your badges and set the single one shown on each published byline.">
            <div style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
              {D.badgeOptions.map((b) => {
                const active = b.label === "— none" ? (form.badges || []).length === 0 : hasBadge(b.label);
                return (
                  <button key={b.label} onClick={() => toggleBadge(b)} title={b.note} style={{ display: "inline-flex", alignItems: "center", gap: 8, background: active ? "rgba(255,140,3,0.1)" : "none", border: active ? "1px solid var(--ebt-orange)" : "1px solid var(--border-strong)", padding: "8px 12px", cursor: "pointer", borderRadius: "var(--radius-sm)" }}>
                    <PBadgeP variant={b.variant} shape="square" size="sm">{b.label}</PBadgeP>
                  </button>
                );
              })}
            </div>
          </PField>

          <PField label="Descriptive line" hint="Optional. e.g. “ex-CTO, financial services”. Keep it short and factual — leave blank for just name + badge.">
            <input value={form.title} onChange={(e) => set("title", e.target.value)} placeholder="ex-CTO, financial services" style={PFIELD} maxLength={70} />
          </PField>

          <PField label="Short bio" hint="2–3 sentences, in EBTHub's voice. Shown under “About the author”.">
            <textarea rows={4} value={form.bio} onChange={(e) => set("bio", e.target.value)} placeholder="What you've done, and what you write about — direct, specific, no fluff." style={{ ...PFIELD, resize: "vertical", lineHeight: 1.5 }} maxLength={320} />
          </PField>

          <PField label="Photo" hint="Optional. Paste a public image URL (Google Drive 'Anyone with link', or any host). Square works best, shown circular.">
            <input value={form.portraitUrl || ""} onChange={(e) => set("portraitUrl", e.target.value)} placeholder="https://drive.google.com/thumbnail?id=…&sz=w400" style={PFIELD} />
          </PField>

          <div style={{ display: "flex", alignItems: "center", gap: 16, marginTop: 8 }}>
            <button type="button" onClick={save} style={{ display: "inline-flex", alignItems: "center", justifyContent: "center", background: "var(--ebt-orange)", border: "none", padding: "14px 26px", cursor: "pointer", fontFamily: "var(--font-ui)", fontSize: 12, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--neutral-1000)" }}>Save profile</button>
            {saved && <span style={{ fontFamily: "var(--font-ui)", fontSize: 11, letterSpacing: "0.06em", textTransform: "uppercase", color: "var(--blue-400)" }}>✓ Saved · pending editor confirmation</span>}
          </div>
        </div>

        {/* live byline preview */}
        <aside className="pf-prof-side" style={{ position: "sticky", top: 92 }}>
          <div style={{ fontFamily: "var(--font-ui)", fontSize: 11, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--text-secondary)", marginBottom: 14 }}>Byline preview</div>
          <div style={{ border: "1px solid var(--border-hairline)", padding: "24px 24px 26px" }}>
            <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 14 }}>
              <div style={{ minWidth: 0 }}>
                <div style={{ display: "flex", alignItems: "center", gap: 6, flexWrap: "wrap" }}>
                  <span style={{ fontFamily: "var(--font-body)", fontWeight: 700, fontSize: 16, color: "var(--white)" }}>{form.name}</span>
                  {(form.badges || []).map((bd) => <PBadgeP key={bd.label} variant={bd.variant} shape="square" size="sm">{bd.label}</PBadgeP>)}
                </div>
                {form.title && <div style={{ fontFamily: "var(--font-ui)", fontSize: 10.5, letterSpacing: "0.05em", color: "var(--text-muted)", marginTop: 5, textTransform: "uppercase" }}>{form.title}</div>}
              </div>
            </div>
            <p style={{ fontFamily: "var(--font-body)", fontSize: 14, lineHeight: 1.6, color: "var(--text-secondary)", margin: 0 }}>{form.bio || "Your short bio appears here."}</p>
          </div>
          <div style={{ display: "flex", gap: 9, alignItems: "flex-start", marginTop: 16, fontFamily: "var(--font-body)", fontSize: 12.5, lineHeight: 1.5, color: "var(--text-muted)" }}>
            <span style={{ color: "var(--ebt-orange)" }}>●</span>
            <span>Badge &amp; descriptive line are <strong style={{ color: "var(--text-secondary)" }}>editor-controlled</strong> — they publish only once an editor confirms them, usually when your first piece is accepted.</span>
          </div>
        </aside>
      </div>
    </main>
  );
}

Object.assign(window, { PProfile });
