/* S5 メッセージ（アプリ内チャット）— やり取りの本体 */
const { useState, useRef, useEffect } = React;

function ChatScreen({ nav, id }) {
  const { THREADS, studentById, STUDENTS, PIPELINE } = window.SV_DATA;
  const { Avatar, Button, FitBadge, Pill } = window.SV_UI;
  const Icons = window.SV_Icons;

  const threadIds = Object.keys(THREADS);
  const [active, setActive] = useState(id && THREADS[id] ? id : threadIds[0]);
  useEffect(() => { if (id && THREADS[id]) setActive(id); }, [id]);
  const [text, setText] = useState("");
  const scrollRef = useRef(null);
  const s = studentById(active);
  const msgs = THREADS[active] || [];
  const stage = PIPELINE[active]?.stage;
  const mutualReady = msgs.some((m) => m.kind === "mutual");

  useEffect(() => { if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight; }, [active]);

  // スレッド一覧の最後のプレビュー
  const preview = (tid) => {
    const arr = THREADS[tid];
    const last = arr[arr.length - 1];
    return last.kind ? `[${{ scout: "スカウト", booking: "実習予約", experience: "実習完了", mutual: "相互意向確認" }[last.kind] || "通知"}]` : last.text;
  };
  const STAGE_LABEL = { scouted: "スカウト済み", talking: "やり取り中", booked: "実習予約済み", mutual: "相互意向確認", support: "選考サポート中", candidate: "候補" };

  const SystemEvent = ({ m }) => {
    const cfg = {
      scout: { icon: Icons.send, c: "var(--brand-600)", bg: "var(--brand-50)" },
      booking: { icon: Icons.calendar, c: "var(--brand-700)", bg: "var(--brand-50)" },
      experience: { icon: Icons.checkCircle, c: "var(--fit)", bg: "var(--fit-bg)" },
      mutual: { icon: Icons.heart, c: "var(--brand-700)", bg: "var(--brand-50)" },
    }[m.kind] || { icon: Icons.dot, c: "var(--ink-3)", bg: "var(--surface-3)" };
    const Icon = cfg.icon;
    return (
      <div style={{ display: "flex", justifyContent: "center", margin: "6px 0" }}>
        <div style={{ display: "inline-flex", alignItems: "center", gap: 9, background: cfg.bg, color: cfg.c, borderRadius: 999, padding: "7px 15px", fontSize: 12.5, fontWeight: 600, maxWidth: 460 }}>
          <Icon size={15} /><span style={{ color: "var(--ink-2)", fontWeight: 500 }}>{m.text}</span>
          <span style={{ color: "var(--ink-3)", fontSize: 11 }} className="num">{m.time}</span>
        </div>
      </div>
    );
  };

  const Bubble = ({ m }) => {
    const mine = m.from === "hospital";
    return (
      <div style={{ display: "flex", flexDirection: "column", alignItems: mine ? "flex-end" : "flex-start", margin: "10px 0" }}>
        <div style={{ display: "flex", gap: 9, alignItems: "flex-end", flexDirection: mine ? "row-reverse" : "row", maxWidth: "76%" }}>
          {!mine && <Avatar s={s} size={32} />}
          <div style={{
            background: mine ? "var(--brand-600)" : "var(--surface)", color: mine ? "#fff" : "var(--ink)",
            border: mine ? "none" : "1px solid var(--border)", borderRadius: 16,
            borderBottomRightRadius: mine ? 5 : 16, borderBottomLeftRadius: mine ? 16 : 5,
            padding: "11px 15px", fontSize: 13.5, lineHeight: 1.7, whiteSpace: "pre-wrap", boxShadow: "var(--shadow-sm)",
          }}>{m.text}</div>
        </div>
        <span className="num" style={{ fontSize: 10.5, color: "var(--ink-3)", margin: mine ? "4px 42px 0 0" : "4px 0 0 42px" }}>{m.time}</span>
      </div>
    );
  };

  return (
    <div style={{ display: "flex", height: "calc(100vh - 64px)" }}>
      {/* スレッド一覧 */}
      <div style={{ width: 300, flexShrink: 0, borderRight: "1px solid var(--border)", background: "var(--surface)", display: "flex", flexDirection: "column" }}>
        <div style={{ padding: "16px 18px 12px", borderBottom: "1px solid var(--border)" }}>
          <div className="disp" style={{ fontSize: 15, fontWeight: 700 }}>スレッド</div>
          <div style={{ fontSize: 11.5, color: "var(--ink-3)", marginTop: 3 }}>学生1人＝1スレッド。新着はLINEで通知。</div>
        </div>
        <div style={{ overflow: "auto", flex: 1 }}>
          {threadIds.map((tid) => {
            const st = studentById(tid);
            const on = tid === active;
            const unread = tid === "sato" || tid === "tanaka";
            return (
              <button key={tid} onClick={() => setActive(tid)} style={{ display: "flex", gap: 11, width: "100%", textAlign: "left", padding: "13px 16px", borderBottom: "1px solid var(--border)", background: on ? "var(--brand-50)" : "transparent", position: "relative" }}>
                {on && <span style={{ position: "absolute", left: 0, top: 0, bottom: 0, width: 3, background: "var(--brand-500)" }} />}
                <Avatar s={st} size={42} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 6 }}>
                    <span className="disp" style={{ fontSize: 13.5, fontWeight: 700, color: "var(--ink)" }}>{st.name}</span>
                    {unread && <span style={{ width: 8, height: 8, borderRadius: "50%", background: "var(--new)", flexShrink: 0 }} />}
                  </div>
                  <div style={{ fontSize: 11.5, color: "var(--ink-2)", marginTop: 3, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{preview(tid)}</div>
                  <div style={{ marginTop: 6 }}>
                    <span style={{ fontSize: 10.5, fontWeight: 700, color: "var(--brand-700)", background: "var(--brand-50)", border: "1px solid var(--brand-100)", borderRadius: 999, padding: "2px 8px" }}>{STAGE_LABEL[PIPELINE[tid]?.stage] || "候補"}</span>
                  </div>
                </div>
              </button>
            );
          })}
        </div>
      </div>

      {/* 会話 */}
      <div style={{ flex: 1, display: "flex", flexDirection: "column", minWidth: 0, background: "var(--surface-2)" }}>
        {/* 会話ヘッダー */}
        <div style={{ padding: "12px 22px", borderBottom: "1px solid var(--border)", background: "rgba(255,255,255,.9)", backdropFilter: "blur(6px)", display: "flex", alignItems: "center", gap: 12 }}>
          <Avatar s={s} size={40} />
          <div style={{ flex: 1 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 9 }}>
              <span className="disp" style={{ fontSize: 15.5, fontWeight: 700 }}>{s.name}</span>
              <FitBadge value={s.fit} size="sm" />
            </div>
            <div style={{ fontSize: 11.5, color: "var(--ink-2)", marginTop: 2 }}>{s.role}・{s.year} ／ 就業可能 {s.available}</div>
          </div>
          <Button variant="ghost" size="sm" iconRight={Icons.arrowRight} onClick={() => nav.go("detail", s.id)}>詳細</Button>
        </div>

        {/* メッセージ */}
        <div ref={scrollRef} style={{ flex: 1, overflow: "auto", padding: "20px 22px" }}>
          {msgs.map((m, i) => (m.from === "system" ? <SystemEvent key={i} m={m} /> : <Bubble key={i} m={m} />))}

          {/* 相互前向き → 日程提示アクション */}
          {mutualReady && (
            <div style={{ display: "flex", justifyContent: "center", margin: "14px 0 4px" }}>
              <div style={{ background: "var(--surface)", border: "1px solid var(--brand-100)", borderRadius: 16, padding: "16px 18px", maxWidth: 440, boxShadow: "var(--shadow-md)", textAlign: "center" }}>
                <div style={{ color: "var(--brand-600)", display: "flex", justifyContent: "center", marginBottom: 8 }}><Icons.heart size={22} /></div>
                <div style={{ fontSize: 13.5, fontWeight: 700, color: "var(--ink)" }}>両者が前向きでした</div>
                <div style={{ fontSize: 12.5, color: "var(--ink-2)", margin: "6px 0 14px", lineHeight: 1.6 }}>もう一度ゆっくり会う日程を出せます。病院の「前向き」は日程提示とセットです。</div>
                <Button variant="primary" size="sm" icon={Icons.calendar} onClick={() => nav.go("calendar")}>再訪の候補日を出す</Button>
              </div>
            </div>
          )}
        </div>

        {/* コンポーザ */}
        <div style={{ padding: "12px 22px 16px", borderTop: "1px solid var(--border)", background: "var(--surface)" }}>
          <div style={{ display: "flex", gap: 8, marginBottom: 9, flexWrap: "wrap" }}>
            <Pill icon={Icons.calendar} bg="var(--surface-3)">実習を案内</Pill>
          </div>
          <div style={{ display: "flex", gap: 10, alignItems: "flex-end" }}>
            <textarea value={text} onChange={(e) => setText(e.target.value)} placeholder="メッセージを入力… （推奨返信：24時間以内）" rows={1}
              style={{ flex: 1, padding: "12px 15px", borderRadius: 12, border: "1px solid var(--border-strong)", fontSize: 13.5, lineHeight: 1.6, resize: "none", fontFamily: "var(--sans)", maxHeight: 120 }} />
            <Button variant="primary" icon={Icons.send} onClick={() => setText("")}>送信</Button>
          </div>
        </div>
      </div>
    </div>
  );
}

window.SV_Chat = ChatScreen;
