// Agente de Contas — animated chat flow with typing, selection, error, success.
const { useState, useEffect, useRef, useCallback } = React;

const ITEMS = [
  { id: "plano", title: "Atualização do plano", desc: "Reajuste aplicado ao seu plano atual", value: "+ R$ 20,00" },
  { id: "juros", title: "Juros e multa", desc: "Aplicados devido ao pagamento após o vencimento", value: "+ R$ 28,99" },
];

// **bold** + \n aware text renderer (TIM agent messages are plain text on white).
function Rich({ text, size = 16 }) {
  return text.split("\n").map((line, li) => (
    <span key={li} style={{ display: "block", minHeight: line ? undefined : size * 0.6 }}>
      {line.split("**").map((part, i) => i % 2 ? <b key={i} style={{ fontWeight: 700 }}>{part}</b> : <React.Fragment key={i}>{part}</React.Fragment>)}
    </span>
  ));
}

function UserBubble({ text }) {
  return (
    <div style={{ display: "flex", justifyContent: "flex-end", padding: "8px 24px" }}>
      <div style={{ maxWidth: 312, background: TIM.grayBg, borderRadius: 18, padding: "12px 16px", position: "relative", fontFamily: "'Hanken Grotesk',system-ui" }}>
        <span style={{ fontSize: 16, lineHeight: "22px", color: "#000" }}>{text}</span>
        <span style={{ display: "block", textAlign: "right", marginTop: 2, lineHeight: 0 }}>
          <svg width="18" height="10" viewBox="0 0 18 10" fill="none" style={{ display: "inline" }}><path d="M1 5l3 3 6-6M7 8l1 1 7-7" stroke="#000" strokeWidth="1.3" strokeLinecap="round" strokeLinejoin="round"/></svg>
        </span>
      </div>
    </div>
  );
}

function Typing() {
  return (
    <div style={{ padding: "4px 24px 8px" }}>
      <div style={{ display: "inline-flex", gap: 5, background: TIM.grayBg, borderRadius: 16, padding: "12px 16px" }}>
        {[0,1,2].map(i => <span key={i} className="typedot" style={{ animationDelay: `${i * 0.18}s` }} />)}
      </div>
    </div>
  );
}

function Feedback() {
  const [v, setV] = useState(null);
  return (
    <div style={{ display: "flex", gap: 20, padding: "4px 24px 18px" }}>
      <button className="pressable" onClick={() => setV(v === "up" ? null : "up")} style={{ background: "none", border: "none", cursor: "pointer", padding: 0 }}>
        {Ic.thumbUp(v === "up" ? TIM.blue : TIM.txtGray, 20, v === "up" ? TIM.blue : "none")}
      </button>
      <button className="pressable" onClick={() => setV(v === "down" ? null : "down")} style={{ background: "none", border: "none", cursor: "pointer", padding: 0 }}>
        {Ic.thumbDown(v === "down" ? TIM.red : TIM.txtGray, 20, v === "down" ? TIM.red : "none")}
      </button>
    </div>
  );
}

// The two compared bills: Em atraso ⇄ A vencer.
function CompareCards() {
  const Card = ({ flag, flagColor, flagBg, icon, value, month, due }) => (
    <div style={{ flex: 1, border: "1px solid " + TIM.border, borderRadius: 14, padding: "12px 10px", display: "flex", flexDirection: "column", alignItems: "center", gap: 6, fontFamily: "'Hanken Grotesk',system-ui" }}>
      <span style={{ display: "inline-flex", alignItems: "center", gap: 5, background: flagBg, color: flagColor, borderRadius: 16, padding: "3px 10px 3px 7px", fontSize: 13, fontWeight: 600 }}>{icon} {flag}</span>
      <span style={{ fontSize: 22, fontWeight: 700, letterSpacing: "-0.5px" }}>{value}</span>
      <span style={{ fontSize: 14, color: "#000" }}>{month}</span>
    </div>
  );
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 12, padding: "8px 24px 4px" }}>
      <Card flag="Em atraso" flagColor={TIM.red} flagBg={TIM.pink} icon={Ic.alertTri(TIM.red, 14)} value="R$ 100,16" month="Abril 2025" />
      <span style={{ flexShrink: 0 }}>{Ic.refresh("#000", 22)}</span>
      <Card flag="A vencer" flagColor="#9a6b00" flagBg={TIM.yellowBg} icon={Ic.clock(TIM.yellow, 14)} value="R$ 135,78" month="Maio 2025" />
    </div>
  );
}

function ItemsList({ selected, onToggle, locked }) {
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 12, padding: "10px 24px 4px" }}>
      {ITEMS.map(it => {
        const on = selected.includes(it.id);
        return (
          <button key={it.id} className="pressable" disabled={locked} onClick={() => onToggle(it.id)} style={{
            textAlign: "left", display: "flex", gap: 12, alignItems: "center", padding: "16px 16px",
            background: "#fff", borderRadius: 14, cursor: locked ? "default" : "pointer",
            border: "1.5px solid " + (on ? TIM.blue : TIM.border), fontFamily: "'Hanken Grotesk',system-ui",
            opacity: locked && !on ? 0.55 : 1, transition: "border-color .15s",
          }}>
            <span style={{ flex: 1, minWidth: 0 }}>
              <span style={{ display: "block", fontSize: 16, fontWeight: 600, color: "#000" }}>{it.title}</span>
              <span style={{ display: "block", fontSize: 13, color: TIM.txtGray, lineHeight: "17px", marginTop: 2 }}>{it.desc}</span>
              <span style={{ display: "inline-block", marginTop: 6, fontSize: 14, fontWeight: 700, color: TIM.blue }}>{it.value}</span>
            </span>
            <span style={{
              width: 24, height: 24, borderRadius: 7, flexShrink: 0, display: "grid", placeItems: "center",
              border: on ? "none" : "2px solid " + TIM.stroke, background: on ? TIM.blue : "transparent",
            }}>
              {on && <svg width="14" height="14" viewBox="0 0 24 24" fill="none"><path d="M5 12l5 5 9-10" stroke="#fff" strokeWidth="2.6" strokeLinecap="round" strokeLinejoin="round"/></svg>}
            </span>
          </button>
        );
      })}
    </div>
  );
}

function ProtocolCard() {
  const [copied, setCopied] = useState(false);
  return (
    <div style={{ margin: "10px 24px 4px", border: "1px solid " + TIM.border, borderRadius: 14, padding: "18px 18px", display: "flex", alignItems: "center", justifyContent: "space-between", fontFamily: "'Hanken Grotesk',system-ui" }}>
      <span>
        <span style={{ display: "block", fontSize: 17, fontWeight: 700 }}>Protocolo</span>
        <span style={{ display: "block", fontSize: 15, color: "#000", marginTop: 2 }}>123178127389</span>
      </span>
      <button className="pressable" onClick={() => { setCopied(true); setTimeout(() => setCopied(false), 1600); }} style={{ background: "none", border: "none", cursor: "pointer", color: TIM.blue, fontSize: 17, fontWeight: 700, fontFamily: "'Hanken Grotesk',system-ui" }}>
        {copied ? "Copiado" : "Copiar"}
      </button>
    </div>
  );
}

// Pill buttons for the action bar.
// Button - Pill (Figma node 1:4922): radius 12, inset 1px border for outline,
// 14px/500 label, h48 medium. Not a full pill — rounded rectangle.
function Pill({ children, variant = "outline-blue", onClick, disabled, grow, icon }) {
  const base = { height: 48, borderRadius: 12, fontSize: 14, fontWeight: 500, lineHeight: "20px", cursor: disabled ? "default" : "pointer", padding: "14px 16px", display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 8, fontFamily: "'Hanken Grotesk',system-ui", flex: grow ? 1 : undefined, whiteSpace: "nowrap", border: "none" };
  const styles = {
    "outline-blue": { ...base, boxShadow: "inset 0 0 0 1px " + TIM.blue, background: "#fff", color: TIM.blue },
    "outline-red":  { ...base, boxShadow: "inset 0 0 0 1px " + TIM.red, background: "#fff", color: TIM.red },
    "contained":    { ...base, background: TIM.blue, color: "#fff" },
    "disabled":     { ...base, boxShadow: "inset 0 0 0 1px " + TIM.stroke, background: "#fff", color: TIM.stroke },
  };
  return <button className={disabled ? "" : "pressable"} onClick={onClick} style={styles[variant]}>{icon}{children}</button>;
}

function AgenteScreen({ onClose }) {
  const [msgs, setMsgs] = useState([]);
  const [typing, setTyping] = useState(false);
  const [stage, setStage] = useState("loading"); // loading | intro | review | done
  const [selected, setSelected] = useState([]);
  const [error, setError] = useState(false);
  const scrollRef = useRef(null);
  const idRef = useRef(0);
  const speed = (window.__protoSpeed || 1);

  const nid = () => ++idRef.current;
  const scrollDown = useCallback(() => {
    requestAnimationFrame(() => { const s = scrollRef.current; if (s) s.scrollTop = s.scrollHeight; });
  }, []);

  // generic: append user bubble, show typing, then append an agent turn.
  const sequence = useCallback((userText, agentTurn, nextStage) => {
    setMsgs(m => [...m, { id: nid(), role: "user", text: userText }]);
    scrollDown();
    setTimeout(() => { setTyping(true); scrollDown(); }, 450 / speed);
    setTimeout(() => {
      setTyping(false);
      setMsgs(m => [...m, { id: nid(), role: "agent", ...agentTurn, feedback: true }]);
      setStage(nextStage);
      scrollDown();
    }, (450 + 1350) / speed);
  }, [scrollDown, speed]);

  // intro runs on mount
  useEffect(() => {
    sequence(
      "Entenda seus valores da fatura",
      { blocks: [
        { kind: "text", text: "Identificamos que você teve uma variação no valor na sua fatura e vamos te explicar agora:" },
        { kind: "compare" },
        { kind: "text", text: "Seu plano foi atualizado e teve um acréscimo de **R$ 20,00**. Também houve a incidência de Juros e Multas devido ao atraso de **(XX) dias** no pagamento da fatura anterior." },
      ]},
      "intro"
    );
  }, []); // eslint-disable-line

  const onRevisar = () => {
    setStage("loading");
    sequence(
      "Revisão dos valores da fatura",
      { blocks: [
        { kind: "text", text: "Estes são os itens que aumentaram o valor da sua conta. Aqui você pode ver mais detalhes ou escolher quais deseja contestar:" },
        { kind: "items" },
      ]},
      "review"
    );
  };

  const toggle = (id) => { setError(false); setSelected(s => s.includes(id) ? s.filter(x => x !== id) : [...s, id]); };

  const onConfirmar = () => {
    if (!selected.length) { setError(true); setTimeout(() => setError(false), 3500); scrollDown(); return; }
    setStage("loading");
    const titles = ITEMS.filter(i => selected.includes(i.id)).map(i => i.title);
    const list = titles.length > 1 ? titles.slice(0, -1).join(", ") + " e " + titles[titles.length - 1] : titles[0];
    sequence(
      `Enviar os itens ${list} para análise um de nossos especialistas.`,
      { blocks: [
        { kind: "text", text: "✅ **Sua solicitação foi registrada com sucesso!**\n\nEntraremos em contato pelo **WhatsApp** em até 24 horas.\n\nFique atento para garantir que receba todas as informações com segurança.\n\nAguarde que um de nossos especialistas vai entrar em contato com você." },
        { kind: "protocol" },
      ]},
      "done"
    );
  };

  const renderBlock = (b, locked) => {
    if (b.kind === "text") return <div style={{ padding: "6px 24px", fontSize: 16, lineHeight: "24px", color: "#000", fontFamily: "'Hanken Grotesk',system-ui" }}><Rich text={b.text} /></div>;
    if (b.kind === "compare") return <CompareCards />;
    if (b.kind === "items") return <ItemsList selected={selected} onToggle={toggle} locked={locked} />;
    if (b.kind === "protocol") return <ProtocolCard />;
    return null;
  };

  return (
    <div style={{ flex: 1, display: "flex", flexDirection: "column", background: "#fff", overflow: "hidden", position: "relative" }}>
      {/* header */}
      <div style={{ paddingTop: 54, flexShrink: 0 }}>
        <div style={{ height: 56, display: "flex", alignItems: "center", justifyContent: "center", position: "relative", borderBottom: "1px solid " + TIM.grayBg }}>
          <SmileLogo size={30} />
          <button className="pressable" onClick={onClose} style={{ position: "absolute", right: 20, background: "none", border: "none", cursor: "pointer", padding: 4 }}>{Ic.close("#000", 24)}</button>
        </div>
      </div>

      {/* error toast */}
      {error && (
        <div className="toastIn" style={{ position: "absolute", top: 116, left: 16, right: 16, zIndex: 20, display: "flex", gap: 12, alignItems: "flex-start", background: TIM.pink, borderRadius: 14, padding: "16px 16px" }}>
          <span style={{ flexShrink: 0, marginTop: 1 }}>{Ic.alertTri(TIM.red, 22)}</span>
          <span style={{ flex: 1, fontSize: 16, lineHeight: "22px", color: "#000", fontFamily: "'Hanken Grotesk',system-ui" }}>Nenhum item selecionado. Por favor, escolha um item antes de continuar.</span>
          <button onClick={() => setError(false)} style={{ background: "none", border: "none", cursor: "pointer", padding: 2 }}>{Ic.close("#000", 20)}</button>
        </div>
      )}

      {/* chat */}
      <div ref={scrollRef} className="scrollArea" style={{ flex: 1, overflowY: "auto", paddingTop: 12, paddingBottom: 120 }}>
        {msgs.map(m => m.role === "user"
          ? <div key={m.id} className="msgIn"><UserBubble text={m.text} /></div>
          : (
            <div key={m.id} className="msgIn">
              {m.blocks.map((b, i) => <React.Fragment key={i}>{renderBlock(b, stage === "done" || (stage !== "review"))}</React.Fragment>)}
              {m.feedback && <Feedback />}
            </div>
          )
        )}
        {typing && <Typing />}
      </div>

      {/* action bar */}
      <div style={{ position: "absolute", left: 0, right: 0, bottom: 0, padding: "20px 24px 28px", display: "flex", gap: 8, justifyContent: "flex-end",
        borderRadius: "16px 16px 0 0", background: "linear-gradient(180deg, rgba(255,255,255,0) 0%, #fff 42%)", borderTop: "1px solid " + TIM.grayBg, boxShadow: "0 -4px 10px -1px " + TIM.grayBg }}>
        {stage === "intro" && (<>
          <Pill variant="outline-blue" grow onClick={onRevisar}>Revisar valores</Pill>
          <Pill variant="outline-red" onClick={onClose} icon={<svg width="16" height="16" viewBox="0 0 24 24" fill="none"><path d="M17 17H7V7M17 7L7 17" stroke={TIM.red} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/></svg>}>Encerrar</Pill>
        </>)}
        {stage === "review" && (<>
          <Pill variant={selected.length ? "contained" : "disabled"} grow onClick={onConfirmar}>Confirmar seleção</Pill>
          <Pill variant="outline-red" onClick={onClose} icon={<svg width="16" height="16" viewBox="0 0 24 24" fill="none"><path d="M17 17H7V7M17 7L7 17" stroke={TIM.red} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/></svg>}>Encerrar</Pill>
        </>)}
        {stage === "done" && (
          <Pill variant="outline-blue" grow onClick={onClose} icon={Ic.whatsapp(TIM.blue, 22)}>Continuar via whatsapp</Pill>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { AgenteScreen });
