// src/Chat.jsx — chat thread with messages, sources, photo galleries, follow-ups

const FLOWS = () => window.ALCY_DATA.FLOWS;

// Map a free-form question to a canned flow id. Falls back to "forges".
function routeQuestion(q) {
  const s = q.toLowerCase();
  if (s.includes("forge") && (s.includes("photo") || s.includes("montre") || s.includes("voir"))) return "forgesPhotos";
  if (s.includes("forge") || s.includes("devos") || s.includes("lemaire")) return "forges";
  if (s.includes("paris") || s.includes("roubaix") || s.includes("vélo") || s.includes("velo") || s.includes("course")) return "paris";
  if (s.includes("école") || s.includes("ecole") || s.includes("classe") || s.includes("dubois")) return "ecolePhotos";
  return "forges";
}

const MessageBubble = ({ msg }) => {
  // Convert simple markdown-ish: **bold**, • bullets, \n
  const renderText = (t) =>
    t.split("\n").map((line, i) => {
      const parts = line.split(/(\*\*[^*]+\*\*)/g).map((p, j) =>
        p.startsWith("**") && p.endsWith("**")
          ? <strong key={j}>{p.slice(2, -2)}</strong>
          : <React.Fragment key={j}>{p}</React.Fragment>
      );
      return <div key={i} style={{ minHeight: line ? undefined : "0.5em" }}>{parts}</div>;
    });

  return (
    <div className={`msg-row ${msg.role} fade-in`}>
      {msg.role === "alcy" && <div className="msg-avatar alcy" />}
      <div style={{ flex: 1, minWidth: 0 }}>
        <div className="msg-bubble">
          {msg.typing ? (
            <div className="typing"><span></span><span></span><span></span></div>
          ) : (
            <>
              {renderText(msg.text)}

              {msg.photos && (
                <div className="photo-gallery">
                  {msg.photos.slice(0, 6).map((p) => (
                    <PhotoCard key={p.id} photo={p} />
                  ))}
                </div>
              )}

              {msg.sources && msg.sources.length > 0 && (
                <div className="sources">
                  <div className="sources-head">
                    <span>✦ Sources</span>
                    <span style={{ color: "var(--text-soft)", fontWeight: 400, letterSpacing: 0, textTransform: "none" }}>
                      · {msg.sources.length} document{msg.sources.length > 1 ? "s" : ""}
                    </span>
                  </div>
                  <div className="source-cards">
                    {msg.sources.map((s, i) => <SourceCard key={i} source={s} />)}
                  </div>
                </div>
              )}

              {msg.followups && msg.followups.length > 0 && (
                <div className="followups">
                  {msg.followups.map((f, i) => (
                    <button key={i} className={`chip followup-btn pastel-${(i % 8) + 1}`} onClick={() => msg.onFollowup(f)}>
                      <span className="arr">↳</span> {f}
                    </button>
                  ))}
                </div>
              )}
            </>
          )}
        </div>
        {!msg.typing && msg.time && (
          <div className="msg-time" style={msg.role === "user" ? { textAlign: "right" } : null}>
            {msg.time}
          </div>
        )}
      </div>
    </div>
  );
};

const Chat = ({ messages, onAsk, onFollowup, kid }) => {
  const [text, setText] = React.useState("");
  const threadRef = React.useRef(null);

  React.useEffect(() => {
    const el = threadRef.current;
    if (el) el.scrollTop = el.scrollHeight;
  }, [messages]);

  const submit = (q) => {
    const v = (q || text).trim();
    if (!v) return;
    onAsk(v);
    setText("");
  };

  return (
    <div className="chat-wrap">
      <div className="chat-thread" ref={threadRef}>
        {messages.map((m, i) => (
          <MessageBubble key={i} msg={{ ...m, onFollowup }} />
        ))}
      </div>

      <div className="composer-wrap">
        <form
          className="composer"
          onSubmit={(e) => { e.preventDefault(); submit(); }}
        >
          <span className="placeholder-icon">✦</span>
          <input
            value={text}
            onChange={(e) => setText(e.target.value)}
            placeholder={kid ? "Pose une autre question…" : "Posez une autre question à Alcy…"}
          />
          <button type="submit" className="send" aria-label="Envoyer">
            <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
              <path d="M2 8h11M9 4l4 4-4 4" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          </button>
        </form>
        <div className="composer-foot">
          <span>
            <span className="badge">⌘ K · raccourcis</span>
            <span style={{ marginLeft: 10 }}>
              {kid
                ? "Tu peux écrire comme tu parles, Alcy comprend !"
                : "Alcy cite ses sources : photos, documents et témoignages du fonds local."}
            </span>
          </span>
          <span style={{ color: "var(--text-soft)" }}>
            Connecté à <strong style={{ color: "var(--primary)" }}>1 842</strong> documents
          </span>
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { Chat, routeQuestion });
