// IAMGPT — slide-in side panel with contextual prompts and canned responses.
// (All responses canned / illustrative — no live LLM call in this prototype.)

function IamGpt({ open, onClose, context, profile, onOpenPlayer, onNav }) {
  const [messages, setMessages] = useState(() => [
    { role: "gpt", text: "IAMGPT online. I can explain ratings, suggest reinforcements, or convert a natural-language query into filters. Ask me anything — or tap a suggestion below." }
  ]);
  const [input, setInput] = useState("");
  const scrollRef = useRef(null);

  useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [messages, open]);

  // Context-aware suggestion prompts
  const suggestions = useMemo(() => {
    if (context?.screen === "player" && context?.player) {
      const p = context.player;
      return [
        { label: `Explain ${p.name}’s IAMS ${p.iams}`, handler: () => respondExplain(p) },
        { label: `Find 3 players similar to ${p.name.split(" ")[0]}`, handler: () => respondSimilar(p) },
        { label: `Draft a short scouting report`,      handler: () => respondReport(p) },
      ];
    }
    if (context?.screen === "analysis") {
      return [
        { label: "Which construction site is most urgent?", handler: () => respondUrgentSite() },
        { label: "Suggest a #6 under €5M",                   handler: () => respondSix() },
        { label: "Players to move on this window",           handler: () => respondMoveOn() },
      ];
    }
    return [
      { label: "Top 3 U21 wingers in budget",           handler: () => respondU21W() },
      { label: "Explain the Camelot model",             handler: () => respondCamelot() },
      { label: "Show dark-horse picks under €3M",       handler: () => respondDarkHorse() },
    ];
  }, [context]);

  const push = (msgs) => setMessages(m => [...m, ...msgs]);

  // ——— canned responses ———
  function respondExplain(p) {
    push([
      { role: "me", text: `Explain ${p.name}’s IAMS ${p.iams}` },
      { role: "gpt", text: `IAMS ${p.iams}/200 reflects a weighted average of 8 visible attributes on the 0-20 scale, emphasized by the ${window.IAMS_DATA.ROLES.find(r=>r.id===p.roleId)?.label || p.pos} role profile. Top drivers: Technique ${p.attrs.Technique}, Decisions ${p.attrs.Decisions}, Intelligence ${p.attrs.Intelligence}. Drag: ${p.attrs.Physicality < 12 ? `Physicality ${p.attrs.Physicality}` : p.attrs.Pressing < 10 ? `Pressing ${p.attrs.Pressing}` : "none significant"}. Community rating: ${p.ratings.community.v}. PRO scouts: ${p.ratings.pro.v}. Spread ±${Math.abs(p.ratings.community.v - p.ratings.pro.v)} points — consensus is tight.` },
    ]);
  }
  function respondSimilar(p) {
    const similar = window.IAMS_DATA.PLAYERS
      .filter(x => x.id !== p.id && x.pos === p.pos)
      .map(x => ({ x, diff: Math.abs(x.iams - p.iams) + Math.abs(x.age - p.age) * 2 }))
      .sort((a,b) => a.diff - b.diff).slice(0, 3);
    push([
      { role: "me", text: `Find 3 players similar to ${p.name.split(" ")[0]}` },
      { role: "gpt", text: "Here are three profile-adjacent matches:", suggestions: similar.map(s => ({
        label: `${s.x.name} · ${s.x.pos} · IAMS ${s.x.iams} · €${s.x.mv}M`,
        handler: () => { onOpenPlayer(s.x.id); onClose(); },
      })) },
    ]);
  }
  function respondReport(p) {
    const role = window.IAMS_DATA.ROLES.find(r => r.id === p.roleId)?.label || p.pos;
    push([
      { role: "me", text: "Draft a short scouting report" },
      { role: "gpt", text: `**${p.name}** (${p.age}, ${p.pos}, ${p.club}). Profiles as a ${role}. IAMS ${p.iams}. Key signals: Technique ${p.attrs.Technique}/20, Decisions ${p.attrs.Decisions}/20, Pace ${p.attrs.Pace}/20. Injury record ${p.injury.badge} (${p.injury.daysLost12m}d/12m). Market value €${p.mv}M with ${p.trend >= 0 ? "+" + p.trend : p.trend}% 30-day trend. ${p.tags?.join(", ")}. Recommendation: ${p.fit >= 80 ? "Shortlist — arrange live viewing next two match windows." : p.fit >= 60 ? "Monitor. Revisit in 2–3 months or request PRO scout tag." : "Park. Better fits available in current market."}` },
    ]);
  }
  function respondUrgentSite() {
    const site = window.IAMS_DATA.CONSTRUCTION_SITES.find(s => s.severity === "high");
    push([
      { role: "me", text: "Which construction site is most urgent?" },
      { role: "gpt", text: `Most urgent: **${site.label}**. ${site.note} Two high-severity sites overall; ${site.label} is weighted slightly higher because the squad has no internal next-man-up at this role.` },
    ]);
  }
  function respondSix() {
    const matches = window.IAMS_DATA.TARGETS.filter(t => t.pos === "DM" && t.mv <= 5).sort((a,b) => b.fit - a.fit);
    push([
      { role: "me", text: "Suggest a #6 under €5M" },
      { role: "gpt", text: `Filtered by pos=DM · MV ≤ €5M · ranked by club fit:`, suggestions: matches.map(p => ({
        label: `${p.name} · ${p.age} · IAMS ${p.iams} · fit ${p.fit}% · €${p.mv}M`,
        handler: () => { onOpenPlayer(p.id); onClose(); },
      })) },
    ]);
  }
  function respondMoveOn() {
    const out = window.IAMS_DATA.BVB_SQUAD.filter(p => p.categoryId === "transfer-out");
    push([
      { role: "me", text: "Players to move on this window" },
      { role: "gpt", text: `Band IV · disappointing / transfer-out:`, suggestions: out.map(p => ({
        label: `${p.name} · contract ${p.contract} · MV €${p.mv}M · IAMS ${p.iams}`,
        handler: () => { onOpenPlayer(p.id); onClose(); },
      })) },
    ]);
  }
  function respondU21W() {
    const list = window.IAMS_DATA.TARGETS.filter(t => t.pos === "W" && t.age <= 21).sort((a,b) => b.fit - a.fit).slice(0, 3);
    push([
      { role: "me", text: "Top 3 U21 wingers in budget" },
      { role: "gpt", text: `Translated to: pos=W · age≤21 · budget band ${profile.budget}. Ranked by fit:`, suggestions: list.map(p => ({
        label: `${p.name} · ${p.age} · fit ${p.fit}% · €${p.mv}M`,
        handler: () => { onOpenPlayer(p.id); onClose(); },
      })) },
    ]);
  }
  function respondCamelot() {
    push([
      { role: "me", text: "Explain the Camelot model" },
      { role: "gpt", text: "Camelot scores four axes on 0-100: **Role** (does the player’s natural role fit the system), **Geo** (cultural and linguistic proximity), **League** (tactical jump between current and target league), **Mental** (hidden attributes — professionalism, adaptability, leadership). Each axis is color-banded: ≥75 green, 55-74 yellow, <55 red. Analogous to the musical Camelot Wheel — adjacent keys ‘blend’, distant keys clash." },
    ]);
  }
  function respondDarkHorse() {
    const list = window.IAMS_DATA.TARGETS.filter(t => t.darkHorse && t.mv <= 3);
    push([
      { role: "me", text: "Show dark-horse picks under €3M" },
      { role: "gpt", text: `Dark-horse flag = strong in ≥1 key area despite off-profile drawbacks:`, suggestions: list.map(p => ({
        label: `${p.name} · ${p.pos} · ${p.age} · €${p.mv}M`,
        handler: () => { onOpenPlayer(p.id); onClose(); },
      })) },
    ]);
  }

  const submit = () => {
    if (!input.trim()) return;
    push([{ role: "me", text: input },
          { role: "gpt", text: `Heard. I’d normally run that against the live index. For this prototype the suggestion chips below cover the canned responses.` }]);
    setInput("");
  };

  return (
    <>
      {open && <div onClick={onClose} style={{
        position: "fixed", inset: 0, background: "rgba(0,0,0,0.22)", zIndex: 68,
      }}/>}
      <aside className={"iamgpt-panel " + (open ? "open" : "")}>
        <div style={{
          display: "flex", alignItems: "center", gap: 12,
          padding: "14px 18px",
          borderBottom: "1px solid var(--rule)",
          background: "var(--panel-2)",
        }}>
          <div style={{
            width: 30, height: 30,
            background: "var(--accent)", color: "var(--accent-ink)",
            display: "grid", placeItems: "center",
            fontFamily: "var(--mono)", fontWeight: 700, fontSize: 11,
          }}>GPT</div>
          <div>
            <div className="display" style={{ fontSize: 15, fontWeight: 600 }}>IAMGPT</div>
            <div className="mono" style={{ fontSize: 10, color: "var(--ink-muted)", letterSpacing: "0.1em", textTransform: "uppercase" }}>
              scout · explain · search · match
            </div>
          </div>
          <div style={{ flex: 1 }}/>
          <button className="btn ghost sm" onClick={onClose}>close</button>
        </div>

        <div ref={scrollRef} style={{
          flex: 1, overflowY: "auto",
          padding: "16px 18px",
          display: "flex", flexDirection: "column", gap: 12,
        }}>
          {messages.map((m, i) => (
            <div key={i} style={{
              alignSelf: m.role === "me" ? "flex-end" : "flex-start",
              maxWidth: "88%",
            }}>
              <div style={{
                padding: "10px 12px",
                background: m.role === "me" ? "var(--accent)" : "var(--panel-2)",
                color: m.role === "me" ? "var(--accent-ink)" : "var(--ink)",
                fontSize: 13, lineHeight: 1.5,
                whiteSpace: "pre-wrap",
                textWrap: "pretty",
              }}
                dangerouslySetInnerHTML={{ __html: m.text.replace(/\*\*(.+?)\*\*/g, "<strong>$1</strong>") }}/>
              {m.suggestions && (
                <div style={{ display: "flex", flexDirection: "column", gap: 6, marginTop: 6 }}>
                  {m.suggestions.map((s, j) => (
                    <button key={j} onClick={s.handler} className="card" style={{
                      padding: "8px 12px",
                      fontSize: 12,
                      background: "var(--panel)",
                      textAlign: "left",
                      border: "1px solid var(--rule-strong)",
                    }}>{s.label} <span style={{ color: "var(--accent)", marginLeft: 6 }}>→</span></button>
                  ))}
                </div>
              )}
            </div>
          ))}
        </div>

        <div style={{ padding: "12px 18px", borderTop: "1px solid var(--rule)", background: "var(--panel-2)" }}>
          <div className="mono" style={{ fontSize: 9, color: "var(--ink-muted)", letterSpacing: "0.12em", textTransform: "uppercase", marginBottom: 8 }}>
            Suggested for this view
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 6, marginBottom: 12 }}>
            {suggestions.map((s, i) => (
              <button key={i} onClick={s.handler} style={{
                padding: "8px 10px",
                fontSize: 12,
                textAlign: "left",
                border: "1px solid var(--rule-strong)",
                background: "var(--panel)",
                color: "var(--ink)",
              }}>✦ {s.label}</button>
            ))}
          </div>
          <div style={{ display: "flex", gap: 6 }}>
            <input type="text" value={input}
              onChange={e => setInput(e.target.value)}
              onKeyDown={e => { if (e.key === "Enter") submit(); }}
              placeholder="Ask in natural language…"
              style={{
                flex: 1, padding: "8px 10px",
                background: "var(--panel)", color: "var(--ink)",
                border: "1px solid var(--rule-strong)",
                fontSize: 13,
              }}/>
            <button className="btn accent sm" onClick={submit}>Send</button>
          </div>
        </div>
      </aside>
    </>
  );
}

Object.assign(window, { IamGpt });
