// Floating Chat Widget — minimized → welcome → pre-chat → active → offline
const { Avatar: WAvatar, Btn: WBtn, Field: WField, Input: WInput, Dropdown: WDrop, ConcernIcon: WCon } = window.UI;

const WIDGET_EMOJIS = ["😀","😁","😂","😊","😍","😉","😎","🤗","🙏","👍","👎","👌","👏","🙌","🔥","✨","🎉","✅","❌","⚠️","💡","❤️","💚","😢","😅","🤔","🙂"];

// Customer-side voice call: shows an incoming-call banner when the CSR invites,
// then acts as the WebRTC callee (answers the agent's offer).
function WidgetVoiceCall({ conversationId }) {
  const [status, setStatus] = React.useState("idle"); // idle|incoming|connecting|connected|ended
  const [muted, setMuted] = React.useState(false);
  const callRef = React.useRef(null);
  const audioRef = React.useRef(null);

  React.useEffect(() => {
    if (!conversationId) return;
    const off = window.LoopData.onCall((m) => {
      if (m.conversationId !== conversationId || m.from !== "agent") return;
      if (m.action === "invite") setStatus("incoming");
      else if (m.action === "hangup") { if (callRef.current) { callRef.current.hangup(); callRef.current = null; } if (audioRef.current) audioRef.current.srcObject = null; setStatus("ended"); }
      else if (callRef.current) callRef.current.handleSignal(m);
    });
    return off;
  }, [conversationId]);

  // Ring the customer while a call is incoming (until they accept/decline).
  React.useEffect(() => {
    if (!window.LoopVoice || !window.LoopVoice.startRing) return;
    if (status === "incoming") window.LoopVoice.startRing(); else window.LoopVoice.stopRing();
    return () => { if (window.LoopVoice && window.LoopVoice.stopRing) window.LoopVoice.stopRing(); };
  }, [status]);

  if (!conversationId || !window.LoopVoice || !window.LoopVoice.supported) return null;

  const accept = () => {
    // Guard re-entrancy: ignore a second Accept tap / duplicate while a call
    // is already being set up, so we don't orphan a PeerConnection + mic.
    if (callRef.current) return;
    setStatus("connecting");
    const call = window.LoopVoice.createCall({
      conversationId, initiator: false,
      send: (msg) => window.LoopData.sendCall(Object.assign({ conversationId }, msg)),
      onState: (s) => { if (s === "connected") setStatus("connected"); if (s === "closed" || s === "failed") { setStatus("ended"); callRef.current = null; } },
      onRemoteStream: (stream) => { if (audioRef.current) { audioRef.current.srcObject = stream; audioRef.current.play().catch(() => {}); } },
    });
    callRef.current = call;
    window.LoopData.sendCall({ conversationId, action: "accept" });
    if (audioRef.current) audioRef.current.play().catch(() => {});
  };
  const decline = () => { window.LoopData.sendCall({ conversationId, action: "decline" }); setStatus("idle"); };
  const hangup = () => { window.LoopData.sendCall({ conversationId, action: "hangup" }); if (callRef.current) { callRef.current.hangup(); callRef.current = null; } if (audioRef.current) audioRef.current.srcObject = null; setStatus("idle"); };
  const toggleMute = () => { const v = !muted; setMuted(v); if (callRef.current) callRef.current.setMuted(v); };
  const label = { incoming: "Incoming voice call", connecting: "Connecting…", connected: "On call with support", ended: "Call ended" }[status];

  return (
    <React.Fragment>
      <audio ref={audioRef} autoPlay playsInline />
      {status !== "idle" && (
        <div className="mx-4 mt-3 rounded-xl border border-lime/30 bg-lime/[0.07] px-3 py-2.5 flex items-center justify-between gap-2">
          <div className="text-[12.5px] text-white/90 flex items-center gap-2"><Icon.Phone size={14} /> {label}</div>
          <div className="flex items-center gap-1.5">
            {status === "incoming" && <button onClick={accept} className="h-8 px-3 rounded-lg bg-lime text-ink-950 text-[12px] font-semibold">Accept</button>}
            {status === "incoming" && <button onClick={decline} className="h-8 px-3 rounded-lg bg-white/[0.08] text-white/70 text-[12px]">Decline</button>}
            {status === "connected" && <button onClick={toggleMute} className={`h-8 w-8 grid place-items-center rounded-lg ${muted ? "bg-amber-400/15 text-amber-300" : "bg-white/[0.08] text-white/70"}`}><Icon.Mic size={14} /></button>}
            {(status === "connecting" || status === "connected") && <button onClick={hangup} className="h-8 px-3 rounded-lg bg-rose-500/20 text-rose-300 text-[12px]">End</button>}
            {status === "ended" && <button onClick={() => setStatus("idle")} className="h-8 px-3 rounded-lg bg-white/[0.08] text-white/70 text-[12px]">Close</button>}
          </div>
        </div>
      )}
    </React.Fragment>
  );
}

function ChatWidget({ initialState = "minimized", offline = false, theme = { brand: "#A6F84A", site: "WINFORLIFE88" }, onClose, aiMode = false }) {
  const [state, setState] = React.useState(offline ? "offline" : initialState);
  const [name, setName] = React.useState("");
  const [username, setUsername] = React.useState("");
  const [concern, setConcern] = React.useState("");
  const [draft, setDraft] = React.useState("");
  const [chat, setChat] = React.useState([
    { who: "agent", t: "Hi! I'm CS Angelo. How can I help you today?", at: "Just now" },
  ]);
  const [typing, setTyping] = React.useState(false);
  const [session, setSession] = React.useState(null);
  const [stars, setStars] = React.useState(0);
  const [thumbs, setThumbs] = React.useState(null);
  const [rated, setRated] = React.useState(false);
  const [showEmoji, setShowEmoji] = React.useState(false);
  const [offlineName, setOfflineName] = React.useState("");
  const [offlineEmail, setOfflineEmail] = React.useState("");
  const [offlineMsg, setOfflineMsg] = React.useState("");
  const [offlineSent, setOfflineSent] = React.useState(false);
  const [aiActive, setAiActive] = React.useState(aiMode);
  const [siteConcerns, setSiteConcerns] = React.useState(null);
  const [sitePrechat, setSitePrechat] = React.useState(null); // { welcome, phone, username }
  const [phone, setPhone] = React.useState("");
  const [closedByAgent, setClosedByAgent] = React.useState(false);
  const [siteAgents, setSiteAgents] = React.useState(null);
  const scrollRef = React.useRef(null);

  const propertySlug = (theme && theme.propertySlug) || "winforlife88";

  React.useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [chat, typing, state]);

  // Fetch per-site concerns as soon as widget opens (before session/chat starts)
  React.useEffect(() => {
    if (state === "minimized" || siteConcerns) return;
    if (!window.LoopData || window.LoopData.mode !== "live") return;
    fetch("/widget/config?site=" + encodeURIComponent(propertySlug))
      .then(r => r.json())
      .then(d => {
        if (d.concerns && d.concerns.length) setSiteConcerns(d.concerns);
        if (d.agents) setSiteAgents(d.agents);
        if (d.prechat) setSitePrechat(d.prechat);
      })
      .catch(() => {});
  }, [state]);

  React.useEffect(() => {
    if (state !== "active") return;
    if (!window.LoopData || window.LoopData.mode !== "live") return;
    let off;
    (async () => {
      const s = await window.LoopData.widgetStart({ propertySlug: theme.propertySlug || "winforlife88", name: name || username, concern, pageUrl: location.href, aiMode, phone, userId: username });
      if (!s || s.simulate) return;
      setSession(s);
      if (s.messages && s.messages.length) {
        setChat(s.messages.map(m => ({ who: m.direction === "inbound" ? "user" : "agent", t: m.body, image: m.image, file: m.file, at: "" })));
      }
      off = window.LoopData.onWidgetReply(s.conversationId, (m) => {
        if (m && m.closed) { setClosedByAgent(true); setState("rating"); return; }
        // The visitor's own messages are already rendered optimistically on send;
        // skip the server's echo of them to avoid showing each message twice.
        if (m.who === "v") return;
        setChat(c => [...c, { who: "agent", t: m.t, image: m.image, file: m.file, at: "now" }]);
      });
    })();
    return () => { off && off(); };
  }, [state]);

  const send = async () => {
    if (!draft.trim()) return;
    const text = draft.trim();
    setChat(c => [...c, { who: "user", t: text, at: "now" }]);
    setDraft("");
    if (session && window.LoopData && window.LoopData.mode === "live") {
      try { await window.LoopData.widgetSend(session, text); } catch (e) { console.warn("widget send failed", e); }
      return;
    }
    setTyping(true);
    const lc = text.toLowerCase();
    const autoReply = lc.match(/withdraw|cash.?out|payout|hindi.*labas|wala.*payout/) ?
      "Nakita ko po ang inyong concern sa withdrawal. Para matulungan kayo nang mas mabilis, pakibigay po ang reference number o ang oras ng transaksyon, at i-attach na rin po ang screenshot ng inyong transaction history sa site." :
      lc.match(/login|locked|password|account|maka.?log/) ?
      "I can help with your account! Please share your username (not your password) and I'll check the status right away." :
      lc.match(/kyc|verif|valid.*id|selfie/) ?
      "For KYC, you'll need: valid government ID + selfie holding the ID + proof of address. You can attach them directly here! 📎" :
      lc.match(/game|bug|crash|laro|spin|stuck|error/) ?
      "Sorry about that! Which game and what happened? A screenshot helps — you can attach it here." :
      "Thank you for reaching out! I'm looking into your concern right now. Could you share a bit more detail so I can help faster? 😊";
    setTimeout(() => {
      setTyping(false);
      setChat(c => [...c, { who: "agent", t: autoReply, at: "now" }]);
    }, 1200 + Math.min(text.length * 12, 900));
  };

  const requestHuman = async () => {
    setAiActive(false);
    setChat(c => [...c, { who: "agent", t: "Connecting you to a human agent... 👋 A CSR will be with you shortly.", at: "now" }]);
    if (session && window.LoopData && window.LoopData.widgetRequestHuman) {
      try { await window.LoopData.widgetRequestHuman(session); } catch (e) { console.warn("handoff error", e); }
    }
  };

  const fileRef = React.useRef(null);
  const pickImage = (e) => {
    const f = e.target.files && e.target.files[0]; if (!f) return;
    const isImg = (f.type || "").startsWith("image/");

    if (isImg) {
      if (f.size > 15000000) { alert("Image is too large (max 15MB)."); e.target.value = ""; return; }
      const reader = new FileReader();
      reader.onerror = () => alert("Could not read image file.");
      reader.onload = (ev) => {
        const img = new Image();
        img.onload = () => {
          try {
            const MAX = 1200;
            const scale = Math.min(1, MAX / Math.max(img.width || 1, img.height || 1));
            const w = Math.max(1, Math.round(img.width * scale));
            const h = Math.max(1, Math.round(img.height * scale));
            const canvas = document.createElement("canvas");
            canvas.width = w; canvas.height = h;
            const ctx = canvas.getContext("2d");
            if (!ctx) { alert("Could not process image."); return; }
            ctx.fillStyle = "#ffffff";
            ctx.fillRect(0, 0, w, h);
            ctx.drawImage(img, 0, 0, w, h);
            const compressed = canvas.toDataURL("image/jpeg", 0.82);
            setChat(c => [...c, { who: "user", t: "", image: compressed, at: "now" }]);
            if (session && window.LoopData && window.LoopData.mode === "live") { try { window.LoopData.widgetSend(session, "", compressed); } catch(e) { console.warn("image send failed", e); } }
          } catch (err) { console.error("Image compress error:", err); alert("Could not process image."); }
        };
        img.onerror = () => alert("Could not load image.");
        img.src = ev.target.result;
      };
      reader.readAsDataURL(f);
    } else {
      if (f.size > 5000000) { alert("File is too large (max 5MB)."); e.target.value = ""; return; }
      const reader = new FileReader();
      reader.onerror = () => alert("Could not read file.");
      reader.onload = () => {
        const file = { name: f.name, type: f.type || "application/octet-stream", data: reader.result };
        setChat(c => [...c, { who: "user", t: "", file, at: "now" }]);
        if (session && window.LoopData && window.LoopData.mode === "live") window.LoopData.widgetSend(session, "", null, file);
      };
      reader.readAsDataURL(f);
    }
    e.target.value = "";
  };

  // Bubble
  if (state === "minimized") {
    return (
      <motion.button
        key="bubble"
        initial={{ scale: 0, y: 20 }} animate={{ scale: 1, y: 0 }} exit={{ scale: 0 }}
        transition={{ type: "spring", stiffness: 360, damping: 22 }}
        onClick={() => setState(offline ? "offline" : session ? "active" : "prechat")}
        className="relative grid place-items-center rounded-full"
        style={{
          width: 60, height: 60,
          background: `linear-gradient(160deg, ${theme.brand} 0%, ${theme.brand}d0 100%)`,
          boxShadow: `0 18px 50px -10px ${theme.brand}80, 0 4px 12px -2px ${theme.brand}50, inset 0 1px 0 rgba(255,255,255,0.35)`,
        }}
      >
        <Icon.Chat size={26} className="text-ink-950" />
        <span className="absolute top-0.5 right-0.5 w-3 h-3 rounded-full bg-lime ring-2 ring-ink-950 dot-online" />
      </motion.button>
    );
  }

  // Card frame
  const isDark = (theme && theme.mode) !== "light";
  return (
    <motion.div
      key="card"
      data-loop-state={state}
      initial={{ y: 16, opacity: 0, scale: 0.96 }}
      animate={{ y: 0, opacity: 1, scale: 1 }}
      exit={{ y: 16, opacity: 0, scale: 0.96 }}
      transition={{ type: "spring", stiffness: 320, damping: 28 }}
      className={`overflow-hidden flex flex-col w-[380px] max-w-[calc(100vw-24px)] rounded-2xl ${state === "active" ? "h-[100dvh]" : ""} max-[480px]:w-screen max-[480px]:max-w-none max-[480px]:rounded-none max-[480px]:h-[100dvh] ${isDark ? "widget-card-dark" : "loop-light bg-white shadow-lg border border-zinc-200"}`}
    >
      {/* Header */}
      <div className={`relative overflow-hidden ${isDark ? "" : "bg-zinc-50 border-b border-zinc-200"}`}>
        <div className="absolute inset-0" style={{
          background: `linear-gradient(135deg, ${theme.brand}${isDark ? "33" : "08"} 0%, ${theme.brand}${isDark ? "05" : "02"} 60%, transparent 100%)`
        }} />
        <div className="relative flex items-start justify-between p-4">
          <div className="flex items-center gap-3">
            <div className="relative">
              {theme.logoUrl ? (
                <img src={theme.logoUrl} alt={theme.site + " logo"} width={40} height={40}
                  onError={(e) => { e.target.style.display = "none"; }}
                  className={`w-10 h-10 rounded-xl object-contain ${isDark ? "bg-white/[0.06]" : "bg-zinc-100"}`} />
              ) : (
                <div className="w-10 h-10 rounded-xl grid place-items-center font-bold" style={{ background: theme.brand, color: isDark ? "#1a1a1a" : "white" }}>
                  {theme.site.slice(0,2)}
                </div>
              )}
              {!offline && <span className={`absolute -bottom-1 -right-1 w-3.5 h-3.5 rounded-full bg-lime ring-2 ${isDark ? "ring-ink-900" : "ring-white"} dot-online`} />}
            </div>
            <div>
              <div className={`text-[14px] font-semibold leading-tight ${isDark ? "text-white/95" : "text-ink-950"}`}>{(theme && theme.title) || `${theme.site} Support`}</div>
              <div className={`text-[11.5px] mt-0.5 flex items-center gap-1.5 ${isDark ? "text-white/55" : "text-zinc-600"}`}>
                {offline ? (
                  <><span className={`w-1.5 h-1.5 rounded-full ${isDark ? "bg-zinc-400" : "bg-zinc-400"}`} /> Currently offline</>
                ) : (
                  <><span className="w-1.5 h-1.5 rounded-full bg-lime" /> {(theme && theme.tagline) || "Replies in < 1 min"}</>
                )}
              </div>
            </div>
          </div>
          <div className="flex items-center gap-1">
            {state === "active" && session && !rated && (
              <button title="Rate this chat" onClick={() => setState("rating")} className="rounded-lg p-1.5 hover:bg-white/[0.08] text-white/60 hover:text-lime">
                <Icon.Star size={15} />
              </button>
            )}
            {state === "prechat" && (
              <button title="Back" onClick={() => onClose ? onClose() : setState("minimized")} className="rounded-lg p-1.5 hover:bg-white/[0.08] text-white/60">
                <Icon.ChevronLeft size={16} />
              </button>
            )}
            <button onClick={() => onClose ? onClose() : setState("minimized")} className="rounded-lg p-1.5 hover:bg-white/[0.08] text-white/60">
              <Icon.Close size={16} />
            </button>
          </div>
        </div>
      </div>

      {/* Body */}
      <motion.div
          key={state}
          initial={{ opacity: 0, y: 6 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.18 }}
          className={state === "active" ? "flex-1 flex flex-col min-h-0" : "overflow-y-auto px-4 pb-4"}
          style={state !== "active" ? { maxHeight: "calc(100dvh - 160px)" } : undefined}
        >
        {state === "prechat" && (
          <React.Fragment>
            {(() => {
              const a = (window.Mock.agents || []).find(x => x.role === "Admin") || (window.Mock.agents || [])[0] || { name: "Admin", color: "#A6F84A" };
              return (
                <div className="flex items-center gap-2.5 mb-3 p-2.5 rounded-xl bg-white/[0.04] border border-white/[0.06]">
                  <div className="relative">
                    <WAvatar name={a.name} color={a.color} size={34} />
                    <span className="absolute -bottom-0.5 -right-0.5 w-3 h-3 rounded-full bg-lime ring-2 ring-ink-900" />
                  </div>
                  <div>
                    <div className="text-[13px] text-white/95 font-semibold leading-tight">{a.name}</div>
                    <div className="text-[11px] text-white/55">Product Expert</div>
                  </div>
                </div>
              );
            })()}
            {(sitePrechat && sitePrechat.welcome)
              ? <div className={`text-[13px] leading-snug mb-3 ${isDark ? "text-white/80" : "text-zinc-700"}`}>{sitePrechat.welcome}</div>
              : <div className={`text-[16px] font-semibold mb-3 ${isDark ? "text-white/95" : "text-ink-950"}`}>Start the conversation</div>}
            <div className="space-y-3">
              <WField label={(sitePrechat && sitePrechat.username) ? "Name" : "Name / User ID"}>
                <WInput value={name} onChange={e => setName(e.target.value)} placeholder={(sitePrechat && sitePrechat.username) ? "Your name" : "Your name or user ID"} />
              </WField>
              {sitePrechat && sitePrechat.phone && (
                <WField label="Phone number">
                  <WInput type="tel" value={phone} onChange={e => setPhone(e.target.value)} placeholder="e.g. 0917 123 4567" />
                </WField>
              )}
              {sitePrechat && sitePrechat.username && (
                <WField label="Username / User ID">
                  <WInput value={username} onChange={e => setUsername(e.target.value)} placeholder="Optional" />
                </WField>
              )}
              <div>
                <div className={`text-[11.5px] uppercase tracking-[0.08em] mb-1.5 ${isDark ? "text-white/45" : "text-zinc-500"}`}>Support Category</div>
                <div className="space-y-1.5">
                  {(siteConcerns || window.Mock.concerns).map(c => (
                    <button key={c.id} type="button" onClick={() => setConcern(c.id)} className={`w-full flex items-center gap-2.5 px-3 py-2 rounded-xl border text-left transition ${concern === c.id ? isDark ? "border-lime/50 bg-lime/10" : "border-lime/50 bg-lime/10" : isDark ? "border-white/[0.07] bg-white/[0.02] hover:bg-white/[0.04]" : "border-zinc-200 bg-zinc-50 hover:bg-zinc-100"}`}>
                      <span className={`w-4 h-4 rounded-full border grid place-items-center ${concern === c.id ? "border-lime" : isDark ? "border-white/30" : "border-zinc-400"}`}>{concern === c.id && <span className="w-2 h-2 rounded-full bg-lime" />}</span>
                      <WCon id={c.id} size={12} />
                      <span className={`text-[13px] ${isDark ? "text-white/90" : "text-ink-950"}`}>{c.label}</span>
                    </button>
                  ))}
                </div>
              </div>
              <button disabled={!name || !concern || (sitePrechat && sitePrechat.phone && !phone.trim())} onClick={() => setState("active")} className="btn-lime w-full h-11 rounded-xl text-[13.5px] font-semibold disabled:opacity-40 disabled:cursor-not-allowed">
                Start the chat
              </button>
              <div className={`text-[10.5px] text-center flex items-center justify-center gap-1.5 ${isDark ? "text-white/40" : "text-zinc-500"}`}>
                <Icon.Lock size={11} /> Encrypted · GDPR · DPA Compliant
              </div>
            </div>
          </React.Fragment>
        )}
        {state === "rating" && (
          <React.Fragment>
            {rated ? (
              <div className="py-10 text-center">
                <div className="text-[16px] text-white/95 font-semibold">Maraming Salamat! ✨</div>
                <div className="text-[12px] text-white/55 mt-1">Your feedback helps us improve.</div>
                {!closedByAgent && (
                  <button onClick={() => setState("active")} className="mt-4 h-10 px-4 rounded-xl border border-white/[0.08] text-[12.5px] text-white/70 hover:bg-white/[0.05]">← Back to chat</button>
                )}
              </div>
            ) : (
              <div className="space-y-3">
                <div className="text-[10.5px] uppercase tracking-wider text-white/40">{closedByAgent ? "Support has closed the chat" : "Rate your support experience"}</div>
                <div className="text-[14px] text-white/90 font-medium">How would you rate this chat?</div>
                <div className="flex items-center gap-1">
                  {[1, 2, 3, 4, 5].map(n => (
                    <button key={n} type="button" onClick={() => setStars(n)} className={n <= stars ? "text-lime" : "text-white/25"}><Icon.Star size={26} /></button>
                  ))}
                </div>
                <div className="flex items-center gap-3">
                  <button type="button" onClick={() => setThumbs("up")} className={`h-10 w-10 grid place-items-center rounded-xl border text-[18px] ${thumbs === "up" ? "border-lime/50 bg-lime/10" : "border-white/[0.08]"}`}>👍</button>
                  <button type="button" onClick={() => setThumbs("down")} className={`h-10 w-10 grid place-items-center rounded-xl border text-[18px] ${thumbs === "down" ? "border-rose-400/50 bg-rose-400/10" : "border-white/[0.08]"}`}>👎</button>
                </div>
                <button disabled={!stars && !thumbs} onClick={async () => { if (session) await window.LoopData.widgetRate(session, { stars, thumbs }); setRated(true); }} className="btn-lime w-full h-11 rounded-xl text-[13.5px] font-semibold disabled:opacity-40">Submit rating</button>
                {!closedByAgent && (
                  <button onClick={() => setState("active")} className="w-full h-10 rounded-xl border border-white/[0.08] text-[12.5px] text-white/70 hover:bg-white/[0.05]">← Back to chat</button>
                )}
              </div>
            )}
          </React.Fragment>
        )}

        {state === "active" && (
          <React.Fragment>
            <WidgetVoiceCall conversationId={session && session.conversationId} />
            <div ref={scrollRef} className="flex-1 min-h-0 overflow-y-auto px-4 py-3 space-y-3">
              <div className="text-center">
                <span className="text-[10.5px] uppercase tracking-wider text-white/35">Today · 2:42 PM</span>
              </div>
              {chat.map((m, i) => (
                <div key={i} className={`flex gap-2 ${m.who === "user" ? "justify-end" : "justify-start"}`}>
                  {m.who === "agent" && <WAvatar name="CS Angelo" color="#A6F84A" size={26} />}
                  <div className={`max-w-[75%] px-3.5 py-2 rounded-2xl text-[13px] leading-relaxed ${
                    m.who === "user"
                      ? "bg-lime text-ink-950 rounded-br-md"
                      : "bg-white/[0.06] text-white/90 rounded-bl-md border border-white/[0.05]"
                  }`}>{m.image && <img src={m.image} alt="" className="rounded-lg max-w-[200px] mb-1 block"/>}{m.file && (<a href={m.file.data} download={m.file.name} className={`mb-1 flex items-center gap-2 px-2.5 py-1.5 rounded-lg text-[12px] ${m.who==="user"?"bg-ink-950/15 text-ink-950":"bg-white/10 text-white/90"}`}><Icon.Paperclip size={13}/><span className="truncate max-w-[160px]">{m.file.name}</span></a>)}{m.t}</div>
                </div>
              ))}
              {typing && (
                <div className="flex gap-2 items-end">
                  <WAvatar name="CS Angelo" color="#A6F84A" size={26} />
                  <div className="bg-white/[0.06] border border-white/[0.05] rounded-2xl rounded-bl-md px-3.5 py-2.5 flex items-center gap-1">
                    <span className="typing-dot w-1.5 h-1.5 rounded-full bg-white/60" />
                    <span className="typing-dot w-1.5 h-1.5 rounded-full bg-white/60" />
                    <span className="typing-dot w-1.5 h-1.5 rounded-full bg-white/60" />
                  </div>
                </div>
              )}
            </div>

            <div className="border-t border-white/[0.06] p-2.5 shrink-0">
              {showEmoji && (
                <div className="mb-2 rounded-xl bg-white/[0.05] border border-white/[0.08] p-2 max-h-[140px] overflow-y-auto" style={{ display: "flex", flexWrap: "wrap", gap: "2px" }}>
                  {WIDGET_EMOJIS.map((em, i) => (
                    <button key={i} onClick={() => { setDraft(d => d + em); setShowEmoji(false); }} style={{ width: 32, height: 32, display: "grid", placeItems: "center", fontSize: 18, borderRadius: 8, flexShrink: 0 }} className="hover:bg-white/[0.1]">{em}</button>
                  ))}
                </div>
              )}
              <div className="flex items-end gap-2">
                <input type="file" ref={fileRef} onChange={pickImage} style={{display:"none"}}/>
                <button onClick={() => fileRef.current && fileRef.current.click()} className="h-9 w-9 grid place-items-center rounded-lg hover:bg-white/[0.05] text-white/55"><Icon.Paperclip size={16} /></button>
                <button onClick={() => setShowEmoji(s => !s)} className={`h-9 w-9 grid place-items-center rounded-lg ${showEmoji ? "bg-lime/15 text-lime" : "hover:bg-white/[0.05] text-white/55"}`}><Icon.Smile size={16} /></button>
                <textarea
                  rows={1}
                  value={draft}
                  onChange={e => setDraft(e.target.value)}
                  onKeyDown={e => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); send(); } }}
                  placeholder="Type a message…"
                  className="flex-1 resize-none bg-transparent outline-none text-[13.5px] text-white/90 placeholder:text-white/30 py-2 max-h-24"
                />
                <button
                  onClick={send}
                  disabled={!draft.trim()}
                  className="h-9 w-9 grid place-items-center rounded-lg btn-lime disabled:opacity-40"
                >
                  <Icon.Send size={15} />
                </button>
              </div>
              <div className="flex items-center justify-between px-1 pt-1.5">
                <div className="text-[10.5px] text-white/35">Powered by <span className="text-white/55 font-medium">Loop</span></div>
                <div className="text-[10.5px] text-white/35 flex items-center gap-1.5"><Icon.Lock size={10}/> End-to-end</div>
              </div>
              {aiActive && (
                <button onClick={requestHuman} className="w-full mt-1 text-center text-[11px] text-white/40 hover:text-lime/70 transition flex items-center justify-center gap-1.5 py-0.5">
                  <Icon.Headset size={11}/> Talk to a real person
                </button>
              )}
            </div>
          </React.Fragment>
        )}

        {state === "offline" && (
          <React.Fragment>
            <div className="rounded-xl border border-white/[0.06] bg-white/[0.02] p-4 mb-3">
              <div className="flex items-center gap-2 mb-2">
                <span className="grid place-items-center w-7 h-7 rounded-lg bg-white/[0.05]"><Icon.Moon size={14} className="text-white/70" /></span>
                <span className="text-[13px] font-medium text-white/90">We're offline right now</span>
              </div>
              <p className="text-[12px] text-white/55 leading-relaxed">Our team is back online at <span className="text-white/85 font-medium">8:00 AM PHT</span>. Drop us a message — we'll reply by email within 4 hours.</p>
            </div>

            {offlineSent ? (
              <div className="py-8 text-center space-y-2">
                <div className="text-3xl">✅</div>
                <div className="text-[15px] text-white/95 font-semibold">Message sent!</div>
                <div className="text-[12px] text-white/50">We'll reply to <span className="text-white/75">{offlineEmail || "you"}</span> within 4 hours.</div>
              </div>
            ) : (
              <div className="space-y-3">
                <WField label="Your name"><WInput value={offlineName} onChange={e => setOfflineName(e.target.value)} placeholder="Marisol Cruz" /></WField>
                <WField label="Email"><WInput type="email" value={offlineEmail} onChange={e => setOfflineEmail(e.target.value)} placeholder="you@example.com" /></WField>
                <WField label="How can we help?">
                  <textarea rows={3} value={offlineMsg} onChange={e => setOfflineMsg(e.target.value)} className="w-full px-3 py-2.5 rounded-xl bg-white/[0.03] border border-white/[0.07] focus:border-lime/60 outline-none text-[13px] resize-none text-white/90 placeholder:text-white/30" placeholder="Describe your concern…" />
                </WField>
                <WBtn variant="primary" className="w-full" size="lg" disabled={!offlineName || !offlineMsg} onClick={async () => {
                  try {
                    if (window.LoopData && window.LoopData.mode === "live") {
                      const s = await window.LoopData.widgetStart({ propertySlug: theme.propertySlug || "winforlife88", name: offlineName, concern: "others", pageUrl: location.href });
                      if (s && !s.simulate) await window.LoopData.widgetSend(s, (offlineEmail ? "[Email: " + offlineEmail + "] " : "") + offlineMsg);
                    }
                  } catch (e) { console.warn("offline send", e); }
                  setOfflineSent(true);
                }}>Send message</WBtn>
                <div className="text-[10.5px] text-white/40 text-center">We'll reply to your email — usually within 4h.</div>
              </div>
            )}
          </React.Fragment>
        )}
        </motion.div>
    </motion.div>
  );
}

window.ChatWidget = ChatWidget;
