/* FrontCall Hub — Mensagens (SMS com clientes + avisos da Riley).
   · Threads por cliente: SMS automáticos da Riley (com selo) + respostas do
     cliente + respostas do dono.
   · Thread fixa "Riley · Avisos" (PT, sem composer): lead quente, resumo do dia.
   · Resposta rápida em PT que envia em INGLÊS — a Riley traduz.
   Estado vive em window.FCThreads pra sobreviver à navegação. */

window.FCThreads = window.FCThreads || JSON.parse(JSON.stringify(window.FCData.threads));

const msgUnreadTotal = () => window.FCThreads.reduce((s, t) => s + (t.unread || 0), 0);
const msgNow = () => new Date().toLocaleTimeString("en-US", { hour: "numeric", minute: "2-digit" });

const MSG_QUICK = [
  { pt: "Tá incluso sim!", en: "Yes, that's included!" },
  { pt: "Pode ser, confirmado!", en: "Yes, that works — confirmed!" },
  { pt: "Posso te ligar?", en: "Can I give you a quick call?" },
  { pt: "Obrigado! 🙏", en: "Thank you so much!" },
];

/* ---------------- lista de conversas ---------------- */
function ThreadRow({ t, active, onClick }) {
  const last = t.msgs[t.msgs.length - 1];
  const isRiley = t.kind === "riley";
  const rel = t.clientId ? ((D.clients.find((c) => c.id === t.clientId) || {}).relation || null) : null;
  const relTag = rel && (
    <span style={{
      flex: "none", fontSize: 9, fontWeight: "var(--fw-bold)", letterSpacing: "var(--ls-wide)", textTransform: "uppercase",
      color: rel === "ativo" ? "var(--success-600)" : rel === "lead" ? "var(--brand)" : "var(--text-faint)",
      background: rel === "ativo" ? "var(--success-bg)" : rel === "lead" ? "var(--surface-brand-subtle)" : "var(--surface-sunken)",
      padding: "2px 7px", borderRadius: "var(--radius-full)",
    }}>{rel === "ativo" ? "cliente" : rel === "lead" ? "lead" : "inativo"}</span>
  );
  return (
    <Card interactive onClick={onClick} style={{ padding: "13px 16px", border: active ? "1.5px solid var(--brand)" : "1px solid var(--border-subtle)" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
        {isRiley
          ? <span style={{ width: 42, height: 42, borderRadius: "var(--radius-full)", background: "var(--blue-600)", display: "flex", alignItems: "center", justifyContent: "center", flex: "none", boxShadow: "var(--shadow-brand)" }}><WaveBars active={t.unread > 0} size={18} color="#fff" /></span>
          : <Avatar name={t.name} size={42} />}
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 8 }}>
            <span style={{ display: "inline-flex", alignItems: "center", gap: 7, minWidth: 0 }}>
              <span style={{ fontWeight: t.unread ? "var(--fw-bold)" : "var(--fw-semibold)", color: "var(--text-strong)", fontSize: "var(--fs-body)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{t.name}</span>
              {relTag}
            </span>
            <span style={{ fontSize: "var(--fs-micro)", color: "var(--text-faint)", flex: "none", fontFamily: "var(--font-mono)" }}>{last ? last.at : ""}</span>
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 3 }}>
            <span style={{ flex: 1, minWidth: 0, fontSize: "var(--fs-caption)", color: t.unread ? "var(--text-primary)" : "var(--text-muted)", fontWeight: t.unread ? "var(--fw-medium)" : "var(--fw-regular)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
              {last ? (last.who === "me" ? "Você: " : "") + last.text : ""}
            </span>
            {t.unread > 0 && (
              <span style={{ flex: "none", minWidth: 20, height: 20, borderRadius: "var(--radius-full)", background: "var(--brand)", color: "#fff", fontSize: "var(--fs-micro)", fontWeight: "var(--fw-bold)", display: "inline-flex", alignItems: "center", justifyContent: "center", padding: "0 6px" }}>{t.unread}</span>
            )}
          </div>
        </div>
      </div>
    </Card>
  );
}

function ThreadList({ onPick, activeId, q }) {
  const threads = window.FCThreads.filter((t) => !q || t.name.toLowerCase().includes(q.toLowerCase()));
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
      {threads.map((t) => <ThreadRow key={t.id} t={t} active={t.id === activeId} onClick={() => onPick(t.id)} />)}
      {threads.length === 0 && <Card inset><EmptyState art={<WaveBars />} title="Nenhuma conversa" description="As conversas por SMS com seus clientes aparecem aqui." /></Card>}
    </div>
  );
}

function MessagesScreen({ go }) {
  const [q, setQ] = React.useState("");
  return (
    <div style={{ padding: "12px 16px 24px" }}>
      <SearchBox q={q} setQ={setQ} placeholder="Buscar conversa…" />
      <ThreadList q={q} onPick={(id) => go("chat", id)} />
    </div>
  );
}

/* ---------------- bolhas ---------------- */
function MsgBubble({ m, isRileyThread }) {
  const mine = m.who === "me";
  const auto = m.who === "auto";
  if (auto && isRileyThread) {
    return (
      <div style={{ display: "flex", gap: 10, alignItems: "flex-start", maxWidth: "92%" }}>
        <span style={{ width: 30, height: 30, borderRadius: "var(--radius-full)", background: "var(--surface-brand-subtle)", display: "flex", alignItems: "center", justifyContent: "center", flex: "none", marginTop: 2 }}><WaveBars size={13} /></span>
        <div>
          <div style={{ background: "var(--surface-card)", border: "1px solid var(--border-subtle)", borderRadius: "4px 16px 16px 16px", padding: "11px 14px", fontSize: "var(--fs-sm)", color: "var(--text-primary)", lineHeight: 1.5, boxShadow: "var(--shadow-xs)" }}>{m.text}</div>
          <div style={{ fontSize: "var(--fs-micro)", color: "var(--text-faint)", marginTop: 4, fontFamily: "var(--font-mono)" }}>{m.at}</div>
        </div>
      </div>
    );
  }
  return (
    <div style={{ display: "flex", flexDirection: "column", alignItems: mine || auto ? "flex-end" : "flex-start" }}>
      <div style={{
        maxWidth: "82%", padding: "11px 14px", fontSize: "var(--fs-sm)", lineHeight: 1.5,
        borderRadius: mine || auto ? "16px 16px 4px 16px" : "16px 16px 16px 4px",
        background: mine ? "var(--brand)" : auto ? "var(--surface-brand-subtle)" : "var(--surface-card)",
        color: mine ? "#fff" : "var(--text-primary)",
        border: mine ? "none" : auto ? "1px solid color-mix(in oklab, var(--brand) 20%, transparent)" : "1px solid var(--border-subtle)",
        boxShadow: "var(--shadow-xs)",
      }}>{m.text}</div>
      <div style={{ display: "flex", alignItems: "center", gap: 6, marginTop: 4, fontSize: "var(--fs-micro)", color: "var(--text-faint)" }}>
        {auto && <span style={{ display: "inline-flex", alignItems: "center", gap: 4, color: "var(--brand)", fontWeight: "var(--fw-semibold)" }}><WaveBars size={9} /> {m.tag || "Riley · automática"}</span>}
        {m.tag && !auto && <span style={{ color: "var(--brand)", fontWeight: "var(--fw-semibold)" }}>{m.tag}</span>}
        <span style={{ fontFamily: "var(--font-mono)" }}>{m.at}</span>
      </div>
    </div>
  );
}

/* ---------------- conversa ---------------- */
function ChatPanel({ id, go }) {
  const [, force] = React.useState(0);
  const scrollRef = React.useRef(null);
  const [draft, setDraft] = React.useState("");
  const t = window.FCThreads.find((x) => x.id === id);

  React.useEffect(() => {
    if (t) { t.unread = 0; force((n) => n + 1); }
  }, [id]);
  React.useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  });

  if (!t) return null;
  const isRiley = t.kind === "riley";

  const send = (text, tag) => {
    if (!text.trim()) return;
    t.msgs.push({ who: "me", text: text.trim(), at: msgNow(), tag });
    setDraft("");
    force((n) => n + 1);
  };

  return (
    <div style={{ height: "100%", minHeight: 0, display: "flex", flexDirection: "column" }}>
      <div ref={scrollRef} style={{ flex: 1, minHeight: 0, overflowY: "auto", padding: "16px 16px 8px", display: "flex", flexDirection: "column", gap: 14 }}>
        {!isRiley && (
          <div style={{ alignSelf: "center", fontSize: "var(--fs-micro)", fontWeight: "var(--fw-bold)", letterSpacing: "var(--ls-eyebrow)", textTransform: "uppercase", color: "var(--text-faint)", background: "var(--surface-sunken)", borderRadius: "var(--radius-full)", padding: "5px 12px" }}>
            SMS · conversa em inglês
          </div>
        )}
        {t.msgs.map((m, i) => <MsgBubble key={i} m={m} isRileyThread={isRiley} />)}
      </div>

      {isRiley ? (
        <div style={{ flex: "none", padding: "12px 16px 26px", textAlign: "center", fontSize: "var(--fs-caption)", color: "var(--text-muted)", borderTop: "1px solid var(--border-subtle)", background: "var(--surface-card)" }}>
          Canal de avisos da Riley — ajuste o que chega aqui em Configurações → Notificações.
        </div>
      ) : (
        <div style={{ flex: "none", background: "var(--surface-card)", borderTop: "1px solid var(--border-subtle)", padding: "10px 12px 24px" }}>
          <div style={{ display: "flex", gap: 8, overflowX: "auto", paddingBottom: 10, scrollbarWidth: "none" }}>
            {MSG_QUICK.map((qk) => (
              <button key={qk.pt} onClick={() => send(qk.en, "traduzido pela Riley")} style={{
                flex: "none", border: "1px solid var(--border-default)", background: "var(--surface-page)",
                color: "var(--text-secondary)", borderRadius: "var(--radius-full)", padding: "8px 14px",
                fontSize: "var(--fs-caption)", fontWeight: "var(--fw-semibold)", cursor: "pointer", fontFamily: "var(--font-sans)",
              }}>{qk.pt}</button>
            ))}
          </div>
          <div style={{ display: "flex", gap: 9, alignItems: "center" }}>
            <input value={draft} onChange={(e) => setDraft(e.target.value)}
              onKeyDown={(e) => { if (e.key === "Enter") send(draft); }}
              placeholder="Escreve em inglês… (dica: usa os atalhos)"
              onFocus={(e) => { e.target.style.borderColor = "var(--brand)"; e.target.style.boxShadow = "var(--focus-shadow)"; }}
              onBlur={(e) => { e.target.style.borderColor = "var(--border-default)"; e.target.style.boxShadow = "none"; }}
              style={{ flex: 1, minWidth: 0, height: 44, borderRadius: "var(--radius-full)", border: "1px solid var(--border-default)", background: "var(--surface-page)", padding: "0 16px", fontFamily: "var(--font-sans)", fontSize: "var(--fs-sm)", color: "var(--text-strong)", outline: "none", transition: "border-color var(--dur-fast), box-shadow var(--dur-fast)" }} />
            <button onClick={() => send(draft)} disabled={!draft.trim()} style={{
              width: 44, height: 44, borderRadius: "var(--radius-full)", border: "none", flex: "none",
              background: draft.trim() ? "var(--brand)" : "var(--gray-200)", cursor: draft.trim() ? "pointer" : "default",
              display: "flex", alignItems: "center", justifyContent: "center", boxShadow: draft.trim() ? "var(--shadow-brand)" : "none",
              transition: "background var(--dur-fast) var(--ease-standard)",
            }}>
              <Icon name="arrow-up-right" size={19} color={draft.trim() ? "#fff" : "var(--gray-400)"} strokeWidth={2.4} />
            </button>
          </div>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { MessagesScreen, ThreadList, ChatPanel, msgUnreadTotal });
