// Animated chat hero — WhatsApp-style, Eventdaddy paper palette.

const { useState, useEffect, useRef } = React;

const SCRIPT = [
  { from: "user", t: "Coffee with Sarah $12", time: "10:42" },
  { from: "ai", typing: 700 },
  { from: "ai", t: ["Logged ", { tag: "Dining", tone: "peach" }, " — ", { em: "$12.00" }, ". Coffee count this month: 14."], time: "10:42" },
  { from: "user", t: "uber to airport 45", time: "14:15" },
  { from: "ai", typing: 800 },
  { from: "ai", t: ["Got it — ", { tag: "Transport", tone: "sky" }, " ", { em: "$45.00" }, "."], time: "14:15" },
  { from: "user", t: "How much on food this month?", time: "14:16" },
  { from: "ai", typing: 1100 },
  { from: "ai", card: "summary", time: "14:16" },
  { from: "user", t: "split dinner $86 with mike + ana", time: "20:08" },
  { from: "ai", typing: 900 },
  { from: "ai", t: ["Split ", { em: "$86.00" }, " three ways. Your share: ", { em: "$28.67" }, ". I'll remind ", { tag: "Mike", tone: "lavender" }, " and ", { tag: "Ana", tone: "sage" }, " tomorrow."], time: "20:08" },
];

function RichText({ parts }) {
  if (typeof parts === "string") return parts;
  return parts.map((p, i) => {
    if (typeof p === "string") return <React.Fragment key={i}>{p}</React.Fragment>;
    if (p.tag) return <span key={i} className={`ed-tag ed-tag--${p.tone || "lavender"}`} style={{ verticalAlign: "baseline" }}>{p.tag}</span>;
    if (p.em) return <em key={i} style={{ fontStyle: "italic", fontWeight: 600 }}>{p.em}</em>;
    return null;
  });
}

function SummaryCard() {
  const rows = [
    { label: "Dining",    v: 312.40, pct: 64, tone: "peach" },
    { label: "Transport", v: 188.20, pct: 38, tone: "sky" },
    { label: "Groceries", v: 142.10, pct: 29, tone: "sage" },
    { label: "Other",     v:  71.30, pct: 14, tone: "butter" },
  ];
  const total = rows.reduce((s, r) => s + r.v, 0);
  return (
    <div style={{
      background: "var(--surface-2)", border: "1px solid var(--border)",
      borderRadius: 10, padding: 14, width: 280, fontFamily: "var(--font-mono)",
    }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 10 }}>
        <span style={{ fontSize: 11, letterSpacing: "0.12em", textTransform: "uppercase", color: "var(--ink-2)" }}>October — food &amp; out</span>
      </div>
      <div style={{ fontSize: 22, fontWeight: 700, lineHeight: 1.1, marginBottom: 2 }}>${total.toFixed(2)}</div>
      <div style={{ fontSize: 12, color: "var(--ink-2)", marginBottom: 12 }}>across 4 categories — 23% under budget</div>
      <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
        {rows.map(r => (
          <div key={r.label} style={{ display: "grid", gridTemplateColumns: "76px 1fr 56px", alignItems: "center", gap: 8 }}>
            <span className={`ed-tag ed-tag--${r.tone}`} style={{ justifySelf: "start", fontSize: 11 }}>{r.label}</span>
            <div style={{ height: 6, background: "var(--surface-3)", borderRadius: 3, overflow: "hidden" }}>
              <div style={{ width: `${r.pct}%`, height: "100%", background: "var(--ink-1)", opacity: 0.7 }} />
            </div>
            <span style={{ fontSize: 12, textAlign: "right", color: "var(--ink-2)", fontVariantNumeric: "tabular-nums" }}>${r.v.toFixed(0)}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

function Bubble({ from, children, time, tail }) {
  const isUser = from === "user";
  return (
    <div style={{ display: "flex", justifyContent: isUser ? "flex-end" : "flex-start", marginBottom: 6 }}>
      <div className="melo-bubble" style={{
        position: "relative", maxWidth: "78%",
        padding: "8px 12px 6px",
        borderRadius: 12,
        borderTopRightRadius: isUser && tail ? 4 : 12,
        borderTopLeftRadius: !isUser && tail ? 4 : 12,
        background: isUser ? "var(--accent)" : "var(--surface)",
        color: isUser ? "#fff" : "var(--ink-1)",
        border: isUser ? "1px solid var(--accent)" : "1px solid var(--border)",
        fontSize: 13.5, lineHeight: 1.5,
        fontFamily: "var(--font-mono)", wordBreak: "break-word",
      }}>
        <div>{children}</div>
        <div style={{
          fontSize: 10, opacity: 0.6, textAlign: "right", marginTop: 2,
          fontVariantNumeric: "tabular-nums",
          color: isUser ? "rgba(255,255,255,0.85)" : "var(--ink-2)",
        }}>{time} {isUser && <span style={{ marginLeft: 2 }}>✓✓</span>}</div>
      </div>
    </div>
  );
}

function TypingIndicator() {
  return (
    <div style={{ display: "flex", justifyContent: "flex-start", marginBottom: 6 }}>
      <div className="melo-bubble" style={{
        background: "var(--surface)", border: "1px solid var(--border)",
        borderRadius: 12, padding: "10px 14px",
        display: "flex", gap: 4,
      }}>
        {[0, 1, 2].map(i => (
          <span key={i} style={{
            display: "inline-block", width: 6, height: 6, borderRadius: 999,
            background: "var(--ink-3)",
            animation: `meloDot 1.2s ease-in-out ${i * 0.15}s infinite`,
          }} />
        ))}
      </div>
    </div>
  );
}

function ChatHero({ replayKey, isMobile }) {
  const [step, setStep] = useState(0);
  const [typingMs, setTypingMs] = useState(null);
  const scrollerRef = useRef(null);

  useEffect(() => { setStep(0); setTypingMs(null); }, [replayKey]);

  useEffect(() => {
    if (step >= SCRIPT.length) return;
    const next = SCRIPT[step];
    let id;
    if (next.from === "user") {
      id = setTimeout(() => setStep(step + 1), 900);
    } else if (next.typing) {
      setTypingMs(next.typing);
      id = setTimeout(() => { setTypingMs(null); setStep(step + 1); }, next.typing);
    } else {
      id = setTimeout(() => setStep(step + 1), next.card ? 1800 : 1200);
    }
    return () => clearTimeout(id);
  }, [step, replayKey]);

  useEffect(() => {
    const el = scrollerRef.current;
    if (el) el.scrollTo({ top: el.scrollHeight, behavior: "smooth" });
  }, [step, typingMs]);

  useEffect(() => {
    if (step >= SCRIPT.length) {
      const id = setTimeout(() => setStep(0), 4500);
      return () => clearTimeout(id);
    }
  }, [step]);

  const messages = SCRIPT.slice(0, step).filter(m => !m.typing);

  return (
    <div className="melo-chat" style={{
      width: "100%", maxWidth: 380, margin: "0 auto",
      background: "var(--surface)", border: "1px solid var(--border)",
      borderRadius: 18, overflow: "hidden", boxShadow: "var(--shadow-pop)",
      display: "flex", flexDirection: "column", height: isMobile ? 440 : 560,
    }}>
      {/* Header */}
      <div style={{
        padding: "14px 16px", borderBottom: "1px solid var(--border)",
        display: "flex", alignItems: "center", gap: 12,
        background: "var(--surface-2)",
      }}>
        <div style={{
          width: 36, height: 36, borderRadius: 999,
          background: "var(--accent)", color: "#fff",
          display: "flex", alignItems: "center", justifyContent: "center",
          fontFamily: "var(--font-mono)", fontWeight: 700, fontSize: 15,
        }}>M</div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontFamily: "var(--font-mono)", fontWeight: 700, fontSize: 14, color: "var(--ink-1)" }}>Melo</div>
          <div style={{ fontSize: 11, color: "var(--ink-2)", display: "flex", alignItems: "center", gap: 5 }}>
            <span style={{ width: 6, height: 6, borderRadius: 999, background: "#3FB950", display: "inline-block" }} />
            online — typically replies instantly
          </div>
        </div>
        <span style={{ fontSize: 11, color: "var(--ink-3)", letterSpacing: "0.08em" }}>e2ee</span>
      </div>

      {/* Messages */}
      <div ref={scrollerRef} style={{
        flex: 1, overflowY: "auto", padding: "16px 14px",
        background: "var(--paper)", display: "flex", flexDirection: "column",
      }}>
        {messages.map((m, i) => {
          const prev = messages[i - 1];
          const tail = !prev || prev.from !== m.from;
          if (m.card === "summary") {
            return (
              <div key={i} style={{ display: "flex", justifyContent: "flex-start", marginBottom: 6 }}>
                <SummaryCard />
              </div>
            );
          }
          return (
            <Bubble key={i} from={m.from} time={m.time} tail={tail}>
              <RichText parts={m.t} />
            </Bubble>
          );
        })}
        {typingMs && <TypingIndicator />}
      </div>

      {/* Composer */}
      <div style={{
        padding: "10px 12px", borderTop: "1px solid var(--border)",
        background: "var(--surface-2)", display: "flex", alignItems: "center", gap: 8,
      }}>
        <div style={{
          flex: 1, background: "var(--surface)", border: "1px solid var(--border)",
          borderRadius: 999, padding: "8px 14px",
          fontSize: 13, color: "var(--ink-3)", fontFamily: "var(--font-mono)",
        }}>Message Melo…</div>
        <div style={{
          width: 34, height: 34, borderRadius: 999,
          background: "var(--accent)", color: "#fff",
          display: "flex", alignItems: "center", justifyContent: "center",
        }}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
            <line x1="22" y1="2" x2="11" y2="13"/>
            <polygon points="22 2 15 22 11 13 2 9 22 2"/>
          </svg>
        </div>
      </div>
    </div>
  );
}

window.ChatHero = ChatHero;
