/* Chat drawer — slide-in AI chat scoped to the selected clip */
const { useState: useCS, useEffect: useCE, useRef: useCR } = React;

function ChatDrawer({
  open,
  clip,
  media,
  selectedCount,
  animateMode,
  onChangeAnimateMode,
  pendingText,
  onClose,
  onSendPrompt,
  onAnimateClip,
}) {
  const [draft, setDraft] = useCS("");
  const bodyRef = useCR(null);

  useCE(() => {
    if (bodyRef.current) {
      bodyRef.current.scrollTop = bodyRef.current.scrollHeight;
    }
  }, [clip?.chat?.length, pendingText]);

  const send = async (text) => {
    if (!text.trim() || !clip || pendingText) return;
    const prompt = text.trim();
    setDraft("");

    try {
      await onAnimateClip(clip.id, prompt, animateMode);
    } catch (err) {
      onSendPrompt(clip.id, {
        role: "assistant",
        text: `Animation failed: ${err?.message || "Unknown error."}`,
      });
    }
  };

  const suggestions = ["Make it feel dreamy", "Slow push-in", "Handheld shake", "Film grain", "Teal & orange"];
  const asset = clip ? media.find((m) => m.id === clip.mediaId) : null;
  const thumbStyle = asset && asset.type !== "audio" ? { backgroundImage: `url("${asset.url}")` } : undefined;

  return (
    <aside className={"chat-drawer " + (open ? "open" : "")} aria-hidden={!open}>
      <div className="chat-head">
        <div className="chat-head-top">
          <span style={{display:"flex", alignItems:"center", gap:6}}>
            <Icon.Sparkle/> Clip AI
          </span>
          <button className="chat-head-close" onClick={onClose} aria-label="Close">
            <Icon.Close/>
          </button>
        </div>
        {clip && (
          <div className="chat-clip-card">
            <div className="chat-clip-thumb" style={thumbStyle}>
              {asset?.type === "audio" && <span className="chat-clip-audio-pill">AUDIO</span>}
            </div>
            <div style={{minWidth:0}}>
              <div className="chat-clip-name">{clip.name}</div>
              <div className="chat-clip-meta">{clip.type.toUpperCase()} · {clip.duration.toFixed(2)}s · start {formatTC(clip.start)}</div>
            </div>
          </div>
        )}
        <div className="chat-mode-row">
          <button
            type="button"
            className={"chat-mode-btn " + (animateMode === "replace" ? "active" : "")}
            onClick={() => onChangeAnimateMode("replace")}
            disabled={!!pendingText}
            title="Generate one video per selected image clip"
          >
            Replace Each
          </button>
          <button
            type="button"
            className={"chat-mode-btn " + (animateMode === "stitch" ? "active" : "")}
            onClick={() => onChangeAnimateMode("stitch")}
            disabled={!!pendingText}
            title="Generate one stitched video from selected images"
          >
            Stitch Selected
          </button>
        </div>
        {clip && selectedCount > 1 && (
          <div className="chat-mode-meta">
            {selectedCount} clips selected. Shift-click creates range selection.
          </div>
        )}
      </div>

      <div className="chat-body" ref={bodyRef}>
        {(!clip || clip.chat.length === 0) && !pendingText && (
          <div className="msg assistant" style={{alignSelf:"stretch", maxWidth:"100%"}}>
            I'm scoped to <strong>{clip?.name || "this clip"}</strong>. Ask me to animate it, change its look, or apply an effect — I'll only touch this clip.
          </div>
        )}
        {clip && clip.chat.map((m, i) => (
          <div key={i} className={"msg " + m.role}>
            {m.text}
            {m.effects && m.effects.length > 0 && (
              <div className="action-chip"><span className="dot"/>Applied · {m.effects.join(", ")}</div>
            )}
          </div>
        ))}
        {pendingText && (
          <div className="msg assistant">{pendingText}<span style={{opacity:0.5}}>▍</span></div>
        )}
      </div>

      {clip && clip.chat.length === 0 && (
        <div className="chat-suggestions">
          {suggestions.map((s) => (
            <span key={s} className="chip" onClick={() => send(s)}>{s}</span>
          ))}
        </div>
      )}

      <div className="chat-input-wrap">
        <form className="chat-input" onSubmit={(e) => { e.preventDefault(); send(draft); }}>
          <input
            type="text"
            value={draft}
            onChange={(e) => setDraft(e.target.value)}
            placeholder={clip ? `Prompt "${clip.name}"…` : "Select a clip first"}
            disabled={!clip || !!pendingText}
          />
          <button type="submit" className="chat-send" disabled={!draft.trim() || !!pendingText}>
            <Icon.Send/>
          </button>
        </form>
      </div>
    </aside>
  );
}

window.ChatDrawer = ChatDrawer;
