/* Profile creation screen — Q7 Option D
   Smart-defaults form. Three style variants exposed via tweak:
   - 'form'   : form-first, fields are primary
   - 'chat'   : chat-first, fields populate progressively
   - 'hybrid' : split layout (default) */

const { useState: useStateP, useEffect: useEffectP, useRef: useRefP } = React;

function ProfileScreen({ profileId, onContinue, profileStyle = "hybrid" }) {
  const baseProfile = dbq.profileById(profileId);
  const refinements = dbq.refinementsForProfile(profileId);
  const [theme, setTheme] = useStateP(baseProfile.theme);
  const [generated, setGenerated] = useStateP(true);
  const [generating, setGenerating] = useStateP(false);
  const [profile, setProfile] = useStateP(baseProfile);
  const [chat, setChat] = useStateP("");
  const [showRefinements, setShowRefinements] = useStateP(false);

  useEffectP(() => {
    setProfile(baseProfile);
    setTheme(baseProfile.theme);
  }, [profileId]);

  function regenerate() {
    setGenerating(true);
    setGenerated(false);
    setTimeout(() => {
      setProfile({ ...baseProfile, theme });
      setGenerated(true);
      setGenerating(false);
    }, 700);
  }

  const Form = (
    <div className="card" style={{ padding: 0, overflow: "hidden" }}>
      <div style={{ padding: "16px 20px", borderBottom: "1px solid var(--line)", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
        <div className="label">Profile · Investor lens</div>
        <span className="tag tag-pos"><span className="tag-dot" /> auto-filled</span>
      </div>
      <div style={{ padding: "8px 20px" }}>
        {[
          ["Theme", "theme", profile.themeInterpretation, true],
          ["Risk tolerance", "risk_tolerance"],
          ["Time horizon", "time_horizon"],
          ["Geography", "geography"],
          ["Market cap", "mcap_preference"],
          ["Exclusions", "exclusions"],
          ["Style tilt", "style_tilt"],
        ].map(([label, key, override, isTheme]) => (
          <div className="field" key={key}>
            <div className="field-row">
              <div className="field-label">{label}</div>
              <input
                className="field-value"
                value={isTheme ? override || profile[key] : profile[key]}
                onChange={(e) => setProfile({ ...profile, [key]: e.target.value })}
              />
            </div>
            {profile.rationales[key] && (
              <div className="field-rationale">↳ {profile.rationales[key]}</div>
            )}
          </div>
        ))}
      </div>
      <div style={{ padding: "12px 20px", borderTop: "1px solid var(--line)", background: "var(--bg-2)", display: "flex", justifyContent: "space-between", alignItems: "center", gap: 12, flexWrap: "wrap" }}>
        <div className="mono" style={{ fontSize: 11, color: "var(--ink-4)" }}>
          Each field is editable. Hover to change.
        </div>
        <div style={{ display: "flex", gap: 8 }}>
          <button className="btn btn-sm" onClick={regenerate}>
            <Icon name="refresh" size={12} /> Regenerate defaults
          </button>
          <button className="btn btn-primary btn-sm" onClick={onContinue}>
            Continue to Thesis Lab <Icon name="arrow" size={12} />
          </button>
        </div>
      </div>
    </div>
  );

  const Chat = (
    <div className="card" style={{ padding: 0, display: "flex", flexDirection: "column", minHeight: 360 }}>
      <div style={{ padding: "16px 20px", borderBottom: "1px solid var(--line)", display: "flex", justifyContent: "space-between" }}>
        <div className="label">Refine via chat</div>
        <span className="mono" style={{ fontSize: 11, color: "var(--ink-4)" }}>haiku · cheap pass</span>
      </div>
      <div style={{ padding: 20, flex: 1, display: "flex", flexDirection: "column", gap: 14 }}>
        <ChatBubble who="thesis">
          I read <em>“{theme}”</em> as <strong>{baseProfile.themeInterpretation.split(/\s+[-—]\s+|\.\s+|;\s+/)[0]}</strong>. I’ve filled the lens with sensible defaults. Edit any field, or tell me what to change.
        </ChatBubble>
        {showRefinements ? (
          <ChatBubble who="thesis">
            <div style={{ marginBottom: 10 }}>This theme can be sliced multiple ways. Which angle?</div>
            <div style={{ display: "grid", gap: 8 }}>
              {refinements.map((r) => (
                <button key={r.id} className="btn btn-sm" style={{ justifyContent: "flex-start", textAlign: "left" }}>
                  <span style={{ flex: 1 }}>{r.label}</span>
                  <span className="mono" style={{ fontSize: 10, color: "var(--ink-4)" }}>{r.hint}</span>
                </button>
              ))}
            </div>
          </ChatBubble>
        ) : (
          <ChatBubble who="user">I have a small NVDA position already, factor that in.</ChatBubble>
        )}
        {!showRefinements && (
          <ChatBubble who="thesis">
            Got it — added an NVDA-overlap penalty to scoring. Concentrated AI bets will rank lower for you. Reflected in the profile sidebar (style tilt → diversification overlay).
          </ChatBubble>
        )}
      </div>
      <div style={{ padding: 12, borderTop: "1px solid var(--line)", display: "flex", gap: 8 }}>
        <input
          value={chat}
          onChange={(e) => setChat(e.target.value)}
          placeholder="Add detail, edit, or ask…"
          style={{ flex: 1, padding: "8px 12px", border: "1px solid var(--line-2)", borderRadius: "var(--d-radius)", background: "var(--bg)", outline: "none", fontSize: "var(--d-text-sm)" }}
        />
        <button className="btn btn-sm" onClick={() => setShowRefinements(!showRefinements)}>
          {showRefinements ? "Show reply" : "Show 3-angle"}
        </button>
      </div>
    </div>
  );

  return (
    <div style={{ maxWidth: 1180, margin: "0 auto", padding: "32px 24px 80px" }}>
      <SectionHead
        eyebrow="01 — profile"
        title="What are you investigating?"
        sub="The profile is your investor lens — slow-changing. We auto-fill it; you tweak. Then we propose theses against it."
      />

      {/* Theme prompt */}
      <div className="card" style={{ marginBottom: 18, padding: 0 }}>
        <div style={{ padding: "10px 16px", borderBottom: "1px solid var(--line)", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
          <div className="label">Theme</div>
          <div className="mono" style={{ fontSize: 11, color: "var(--ink-4)" }}>↵ to regenerate</div>
        </div>
        <div style={{ display: "flex", alignItems: "center", padding: "12px 16px", gap: 12 }}>
          <Icon name="search" size={18} style={{ color: "var(--ink-4)" }} />
          <input
            value={theme}
            onChange={(e) => setTheme(e.target.value)}
            onKeyDown={(e) => e.key === "Enter" && regenerate()}
            placeholder="data centers"
            style={{ flex: 1, fontFamily: "var(--font-serif)", fontSize: 22, fontWeight: 500, border: "none", background: "transparent", outline: "none", letterSpacing: "-0.01em" }}
          />
          {generating && <span className="mono" style={{ fontSize: 11, color: "var(--ink-4)" }}>analyzing<span className="pulse-dot">…</span></span>}
        </div>
      </div>

      {/* Layout depending on style */}
      {profileStyle === "form" && Form}
      {profileStyle === "chat" && (
        <div style={{ display: "grid", gap: 16 }}>
          {Chat}
          <details>
            <summary style={{ cursor: "pointer", fontSize: 13, color: "var(--ink-3)", padding: "8px 0" }}>Show structured fields ▾</summary>
            <div style={{ marginTop: 8 }}>{Form}</div>
          </details>
        </div>
      )}
      {profileStyle === "hybrid" && (
        <div style={{ display: "grid", gridTemplateColumns: "1.3fr 1fr", gap: 18, alignItems: "start" }}
             className="profile-split">
          {Form}
          {Chat}
        </div>
      )}
    </div>
  );
}

function ChatBubble({ who, children }) {
  const isUser = who === "user";
  return (
    <div style={{ display: "flex", justifyContent: isUser ? "flex-end" : "flex-start" }}>
      <div
        style={{
          maxWidth: "85%",
          padding: "10px 14px",
          fontSize: "var(--d-text-sm)",
          lineHeight: 1.5,
          borderRadius: 12,
          background: isUser ? "var(--ink)" : "var(--bg-2)",
          color: isUser ? "var(--bg)" : "var(--ink)",
          border: isUser ? "none" : "1px solid var(--line)",
        }}
      >
        {children}
      </div>
    </div>
  );
}

Object.assign(window, { ProfileScreen });
