/* ChatPanel — 核心聊天区 + 底部投喂/快捷/输入 */
const { useRef: useRefC, useEffect: useEffectC, useState: useStateC } = React;

function ChatLog({ messages }) {
  const ref = useRefC(null);
  useEffectC(() => {
    const el = ref.current;
    if (el) el.scrollTop = el.scrollHeight;
  }, [messages]);

  return (
    <div className="chat" ref={ref} aria-live="polite">
      {messages.map((m) => {
        if (m.type === "mem")
          return (
            <div className="mem-chip" key={m.id}>
              <svg
                width="13"
                height="13"
                viewBox="0 0 24 24"
                aria-hidden="true"
              >
                <path
                  d="M6 3h12a1 1 0 0 1 1 1v16l-7-4-7 4V4a1 1 0 0 1 1-1z"
                  fill="#e8746a"
                  stroke="#2a2018"
                  strokeWidth="1.8"
                  strokeLinejoin="round"
                />
              </svg>
              {m.text}
            </div>
          );
        if (m.type === "toast")
          return (
            <div className="toast-line" key={m.id}>
              ✦ {m.text}
            </div>
          );
        if (m.type === "sep")
          return (
            <div className="day-sep" key={m.id}>
              {m.text}
            </div>
          );
        if (m.typing)
          return (
            <div className="msg pet typing" key={m.id}>
              <i></i>
              <i></i>
              <i></i>
            </div>
          );
        return (
          <div
            className={`msg ${m.role} ${m.fallback ? "fallback" : ""}`}
            key={m.id}
          >
            {m.categoryLabel ? (
              <span className="msg-tag">{m.categoryLabel}</span>
            ) : null}
            {m.photo ? (
              <img className="msg-photo" src={m.photo} alt="分享的图片" />
            ) : null}
            {m.text}
          </div>
        );
      })}
    </div>
  );
}

function Composer({ busy, onSend, onPhoto, categoryId, onCategory }) {
  const inputRef = useRefC(null);
  const fileRef = useRefC(null);
  const PET = window.PET;
  const selected = PET.categoryById(categoryId);

  function submit(e) {
    e.preventDefault();
    const v = inputRef.current.value.trim();
    if (!v || busy) return;
    inputRef.current.value = "";
    onSend(v, categoryId);
  }

  function pickPhoto(e) {
    const f = e.target.files && e.target.files[0];
    if (!f) return;
    const text = inputRef.current.value.trim();
    const reader = new FileReader();
    reader.onload = () => {
      inputRef.current.value = "";
      onPhoto(reader.result, categoryId, text);
    };
    reader.readAsDataURL(f);
    e.target.value = "";
  }

  return (
    <div className="composer">
      <div className="tray-label">消息定性</div>
      <div className="category-row" role="radiogroup" aria-label="消息定性标签">
        {PET.CATEGORIES.map((cat) => (
          <button
            key={cat.id}
            type="button"
            role="radio"
            aria-checked={cat.id === categoryId}
            className={`chip ${cat.accent ? "accent" : ""} ${cat.id === categoryId ? "selected" : ""}`}
            onClick={() => onCategory(cat.id)}
            disabled={busy}
            title={cat.hint}
          >
            {cat.label}
          </button>
        ))}
      </div>
      <p className="category-hint">{selected.hint}</p>

      <form className="input-row" onSubmit={submit}>
        <button
          type="button"
          className="photo-btn"
          onClick={() => fileRef.current && fileRef.current.click()}
          disabled={busy}
          aria-label="发图片给小猫看"
        >
          <svg width="20" height="20" viewBox="0 0 24 24" aria-hidden="true">
            <rect
              x="3"
              y="5"
              width="18"
              height="14"
              rx="2.5"
              fill="none"
              stroke="#2a2018"
              strokeWidth="2"
            />
            <circle cx="8.5" cy="10" r="1.6" fill="#2a2018" />
            <path
              d="M5 17l5-5 4 4 2-2 3 3"
              fill="none"
              stroke="#2a2018"
              strokeWidth="2"
              strokeLinejoin="round"
            />
          </svg>
        </button>
        <input
          ref={fileRef}
          type="file"
          accept="image/*"
          hidden
          onChange={pickPhoto}
        />
        <input
          ref={inputRef}
          type="text"
          autoComplete="off"
          maxLength={140}
          placeholder={`${selected.label}: ${selected.hint}`}
          disabled={busy}
        />
        <button className="send-btn" type="submit" disabled={busy}>
          发送
        </button>
      </form>
    </div>
  );
}

function FeedDock({ busy, onFeed, cooldown }) {
  const PET = window.PET;
  const [open, setOpen] = useStateC(false);
  return (
    <div className={`feed-dock ${open ? "open" : ""}`} aria-label="投喂小猫">
      {open ? (
        <div className="feed-menu">
          {PET.FOODS.map((f) => (
            <button
              key={f.id}
              type="button"
              className={`food-dot ${cooldown[f.id] ? "cooldown" : ""}`}
              onClick={() => {
                onFeed(f);
                setOpen(false);
              }}
              disabled={busy}
              title={f.name}
              aria-label={`投喂${f.name}`}
            >
              <FoodIcon glyph={f.glyph} />
            </button>
          ))}
        </div>
      ) : null}
      <button
        type="button"
        className="feed-toggle"
        onClick={() => setOpen((v) => !v)}
        disabled={busy}
        title="投喂小猫"
        aria-label="投喂小猫"
        aria-expanded={open}
      >
        <FoodIcon glyph="fish" />
      </button>
    </div>
  );
}

Object.assign(window, { ChatLog, Composer, FeedDock });
