// analyst-profile.jsx — the analyst PROFILE surfaces.
//
// AnalystProfile: a tap-to-open card (right drawer on desktop, full-screen sheet
//   on mobile — the SAME .flyout pattern the event/watchlist flyouts use, so it
//   works identically on touch, no hover). Read-only; editing lives in Settings.
// AnalystStyleCaption: the one-line style tag + risk note shown UNDER an analyst's
//   name in the Event / Position detail headers — so a viewer sees the style at
//   the moment they act on a signal (the fix for "took a DEV 0DTE not knowing").
//
// Stats (win rate / record / net) are computed by the caller from the trade
// record and passed in — never stored on the analyst, so a profile can never
// restate P&L.

function AnalystStyleCaption({ analyst }) {
  if (!analyst) return null;
  const tag = analyst.style_tag, risk = analyst.risk_note;
  if (!tag && !risk) return null;
  return (
    <div className="an-caption">
      {tag && <span className="an-tag">{tag}</span>}
      {tag && risk && <span className="an-caption-dot">·</span>}
      {risk && <span className="an-caption-risk">{risk}</span>}
    </div>
  );
}

function AnalystProfile({ analyst, stats, onClose, canEdit, onSave }) {
  const [editing, setEditing] = useState(false);
  const [tag, setTag] = useState("");
  const [risk, setRisk] = useState("");
  const [note, setNote] = useState("");
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState(null);

  useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape" && !busy) onClose(); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [onClose, busy]);

  if (!analyst) return null;
  const col = analyst.color || "var(--accent)";
  const swatch = <span className="swatch lg" style={{ "--col": col }} />;
  const hasIntro = !!(analyst.style_tag || analyst.style_note || analyst.risk_note);
  const pct = (n) => (n == null ? "—" : `${n >= 0 ? "+" : ""}${(n * 100).toFixed(1)}%`);

  function startEdit() {
    setTag(analyst.style_tag || ""); setRisk(analyst.risk_note || ""); setNote(analyst.style_note || "");
    setErr(null); setEditing(true);
  }
  async function save() {
    setBusy(true); setErr(null);
    try {
      await onSave({ style_tag: tag.trim() || null, risk_note: risk.trim() || null, style_note: note.trim() || null });
      setEditing(false);
    } catch (e) { setErr(e.message || "couldn't save"); }
    finally { setBusy(false); }
  }

  return (
    <>
      <div className="flyout-back" onClick={() => !busy && onClose()} />
      <div className="flyout an-flyout" role="dialog" aria-modal="true" aria-label={`${analyst.handle} profile`} style={{ "--col": col }}>
        <div className="flyout-hdr an-hdr">
          <div className="an-id">
            {analyst.avatarUrl
              ? <DiscordAvatar url={analyst.avatarUrl} size={40} className="an-pic" style={{ "--col": col }} fallback={swatch} />
              : swatch}
            <div className="an-id-txt">
              <div className="an-name">{analyst.handle}</div>
              {!editing && analyst.style_tag && <div className="an-tag">{analyst.style_tag}</div>}
            </div>
          </div>
          <div className="an-hdr-actions">
            {canEdit && !editing && <button className="btn ghost sm" onClick={startEdit}>Edit</button>}
            <button className="flyout-close" onClick={onClose} aria-label="Close" disabled={busy}>✕</button>
          </div>
        </div>

        <div className="flyout-body an-body">
          {stats && (stats.count > 0) && (
            <div className="an-stats">
              <div className="an-stat"><span className="an-stat-v">{stats.winRate == null ? "—" : Math.round(stats.winRate * 100) + "%"}</span><span className="an-stat-l">win rate</span></div>
              <div className="an-stat"><span className="an-stat-v">{stats.wins}·{stats.losses}</span><span className="an-stat-l">record</span></div>
              <div className="an-stat"><span className={"an-stat-v " + (stats.avg >= 0 ? "up" : "down")}>{pct(stats.avg)}</span><span className="an-stat-l">avg / trade</span></div>
              <div className="an-stat"><span className="an-stat-v">{stats.count}</span><span className="an-stat-l">scored trades</span></div>
            </div>
          )}

          {editing ? (
            <div className="an-edit">
              <label className="an-field">
                <span className="an-field-l">Style tag <em>(a quick label, e.g. "0DTE · Aggressive")</em></span>
                <input className="an-input" maxLength={40} value={tag} onChange={e => setTag(e.target.value)} placeholder="0DTE · Aggressive" />
              </label>
              <label className="an-field">
                <span className="an-field-l">Risk-management note <em>(one line members should know)</em></span>
                <input className="an-input" maxLength={200} value={risk} onChange={e => setRisk(e.target.value)} placeholder="Size small, tight stops — these can expire same day" />
              </label>
              <label className="an-field">
                <span className="an-field-l">About the style <em>(1–3 sentences, optional)</em></span>
                <textarea className="an-input" rows={3} maxLength={400} value={note} onChange={e => setNote(e.target.value)} placeholder="How I trade, what a typical setup looks like…" />
              </label>
              {err && <div className="an-err">⚠️ {err}</div>}
              <div className="an-edit-actions">
                <button className="btn primary sm" onClick={save} disabled={busy}>{busy ? "Saving…" : "Save"}</button>
                <button className="btn ghost sm" onClick={() => setEditing(false)} disabled={busy}>Cancel</button>
              </div>
            </div>
          ) : (
            <>
              {analyst.risk_note && <blockquote className="an-risk">{analyst.risk_note}</blockquote>}
              {analyst.style_note && <p className="an-note">{analyst.style_note}</p>}
              {!hasIntro && (
                <div className="an-empty">
                  No profile written yet{canEdit ? " — add a trading style and risk note so members know what to expect." : "."}
                  {canEdit && <div style={{ marginTop: 10 }}><button className="btn sm" onClick={startEdit}>Write profile</button></div>}
                </div>
              )}
            </>
          )}
        </div>
      </div>
    </>
  );
}

Object.assign(window, { AnalystProfile, AnalystStyleCaption });
