// screens/chat-rail.jsx — Arco assistant chat rail (right column of app shell)
// Collapsed = 56px icon strip with sparkle + unread dot. Expanded = 372px with
// thread list, suggestions, intro, and an input row. State persisted via
// the parent app via data-chat on .app + localStorage("arco.chat").

function ChatRail({ ctx, expanded, onToggle }) {
  const { tt, data, nav } = ctx;
  const [input, setInput] = React.useState("");

  // Derive "last 3 threads" from data.conversations if present, else mock-up.
  const threads = (data?.conversations || []).slice(0, 3);

  // Three pinned suggestions surface the same kinds of questions the agent
  // can answer today (read-only tools per CLAUDE.md §7 — escritura via UI).
  const suggestions = [
    { key: "chat.sug.overdue",  onPick: () => nav && nav("income") },
    { key: "chat.sug.expenses", onPick: () => nav && nav("expenses") },
    { key: "chat.sug.summer",   onPick: () => nav && nav("summer") },
  ];

  // Tiny unread heuristic: any conversation with unread > 0 lights the dot.
  const hasUnread = (data?.conversations || []).some((c) => c.unread > 0);

  if (!expanded) {
    return (
      <aside className="chat-rail" data-state="collapsed" aria-label={tt("chat.title")}>
        <button className="chat-rail-toggle" onClick={onToggle}
                aria-label={tt("chat.expand")} title={tt("chat.expand")}>
          <Icon name="chat" size={16} />
          {hasUnread && <span className="badge-dot" aria-hidden />}
        </button>
        <div className="chat-rail-icons" aria-hidden>
          <button className="chat-rail-toggle" tabIndex={-1} title={tt("chat.title")}
                  onClick={onToggle} aria-label={tt("chat.title")}>
            <span style={{
              width: 24, height: 24, borderRadius: 9999, background: "var(--ef-primary)",
              color: "var(--ef-primary-ink)", display: "inline-flex",
              alignItems: "center", justifyContent: "center"
            }}>
              <Icon name="spark" size={12} />
            </span>
          </button>
        </div>
      </aside>
    );
  }

  return (
    <aside className="chat-rail" data-state="expanded" aria-label={tt("chat.title")}>
      <header className="chat-rail-head">
        <span className="sparkle" aria-hidden><Icon name="spark" size={14} /></span>
        <div className="chat-rail-head-title">{tt("chat.title")}</div>
        <button className="chat-rail-toggle" style={{ marginLeft: "auto" }}
                onClick={onToggle} aria-label={tt("chat.collapse")} title={tt("chat.collapse")}>
          <Icon name="panelClose" size={14} />
        </button>
      </header>

      <div className="chat-rail-body">
        <p className="chat-rail-intro">{tt("chat.intro")}</p>

        {/* Demo conversation: shows the agent's voice and tone */}
        <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
          <div className="bubble out" style={{ alignSelf: "flex-end", maxWidth: "82%" }}>{tt("chat.demo.user")}</div>
          <div className="bubble in" style={{ alignSelf: "flex-start", maxWidth: "92%" }}>{tt("chat.demo.agent")}</div>
          <button className="btn sm" style={{ alignSelf: "flex-start", marginTop: 2 }}
                  onClick={() => ctx.nav && ctx.nav("dashboard")}>
            {tt("chat.demo.cta")}
          </button>
        </div>

        <div>
          <div className="chat-rail-section-label" style={{ marginBottom: 8 }}>
            {tt("chat.suggestions")}
          </div>
          <div className="chat-rail-sugg">
            {suggestions.map((s) => (
              <button key={s.key} onClick={s.onPick}>{tt(s.key)}</button>
            ))}
          </div>
        </div>

        {threads.length > 0 && (
          <div>
            <div className="chat-rail-section-label" style={{ marginBottom: 8 }}>
              {tt("chat.threadsLabel")}
            </div>
            <div>
              {threads.map((c) => {
                const last = c.messages && c.messages[c.messages.length - 1];
                const tn = data.byId && c.tenantId ? data.byId.tenant(c.tenantId) : null;
                return (
                  <div key={c.id} className="chat-rail-thread"
                       onClick={() => nav && nav("messages", c.id)}>
                    <span className="who">{tn ? tn.name : c.subject || tt("ui.untitled")}</span>
                    <span className="snippet">{last ? last.text : ""}</span>
                  </div>
                );
              })}
            </div>
          </div>
        )}
      </div>

      <form className="chat-rail-foot" onSubmit={(e) => {
        e.preventDefault();
        if (!input.trim()) return;
        ctx.showToast && ctx.showToast(tt("chat.title") + ": " + input.trim().slice(0, 60));
        setInput("");
      }}>
        <input
          className="chat-rail-input"
          placeholder={tt("chat.placeholder")}
          value={input}
          onChange={(e) => setInput(e.target.value)}
          aria-label={tt("chat.placeholder")}
        />
        <button className="chat-rail-send" type="submit"
                aria-label={tt("chat.send")} disabled={!input.trim()}>
          <Icon name="chevR" size={14} />
        </button>
      </form>
    </aside>
  );
}

window.ChatRail = ChatRail;
