import { createPortal } from "react-dom";
import { useEffect, useRef, useState, type ReactNode } from "react";
import { addBalance } from "@/lib/wallet";
import { ArrowLeft, Headphones, Globe, Wallet, Banknote, Gift, CircleHelp, Send, QrCode, Crown, Gem, Dices, Star } from "lucide-react";

type Kind = "Deposit" | "Withdrawal" | "Bonus Offers" | "Other Help";
type Msg = { id: number; from: "me" | "bot"; kind?: Kind | "welcome"; text?: string; time: string };

const time = () => new Date().toLocaleTimeString("en-IN", { hour: "2-digit", minute: "2-digit", hour12: false });
const OFFERS = [
  { n: "WELCOME OFFER", d: "5,000", b: "2,000", I: Crown },
  { n: "HIGH ROLLER PACK", d: "10,000", b: "5,000", I: Gem },
  { n: "NOBLE WHEEL PACK", d: "25,000", b: "8,000", I: Dices },
  { n: "REGAL VIP PACK", d: "50,000", b: "15,000", I: Star },
];
const AMTS = [300, 500, 1000, 1500, 2000, 2500, 3000];
const QUICK: { k: Kind; hi: string; I: typeof Wallet }[] = [
  { k: "Deposit", hi: "डिपॉज़िट", I: Wallet },
  { k: "Withdrawal", hi: "निकासी", I: Banknote },
  { k: "Bonus Offers", hi: "बोनस ऑफ़र", I: Gift },
  { k: "Other Help", hi: "अन्य मदद", I: CircleHelp },
];

/** Full-screen customer support chat opened from the floating headset button. */
export function SupportChat({ onClose }: { onClose: () => void }) {
  const [hi, setHi] = useState(false);
  const [msgs, setMsgs] = useState<Msg[]>([{ id: 0, from: "bot", kind: "welcome", time: time() }]);
  const [typing, setTyping] = useState(false);
  const [sel, setSel] = useState<Kind | null>(null);
  const [text, setText] = useState("");
  const box = useRef<HTMLDivElement>(null);
    const id = useRef(1);

  useEffect(() => { box.current?.scrollTo({ top: box.current.scrollHeight, behavior: "smooth" }); }, [msgs, typing]);

  const ask = (label: string, kind: Kind) => {
    setMsgs([{ id: id.current++, from: "me", text: label, time: time() }]);
    setTyping(true);
    setTimeout(() => { setTyping(false); setMsgs((m) => [...m, { id: id.current++, from: "bot", kind, time: time() }]); }, 1200);
  };
  const botSay = (t: string) => {
    setTyping(true);
    setTimeout(() => { setTyping(false); setMsgs((m) => [...m, { id: id.current++, from: "bot", text: t, time: time() }]); }, 900);
  };
  const payNow = (a: number) => {
    setMsgs((m) => [...m, { id: id.current++, from: "me", text: `Pay deposit ₹${a}`, time: time() }]);
    addBalance(a);
    botSay(`✅ ₹${a.toLocaleString("en-IN")} deposit successful! Amount added to your wallet (demo).`);
  };
  const claim = (n: string, d: string, b: string) => {
    setMsgs((m) => [...m, { id: id.current++, from: "me", text: n, time: time() }]);
    const dep = Number(d.replace(/,/g, "")), bon = Number(b.replace(/,/g, ""));
    addBalance(dep + bon);
    botSay(`🎁 ${n} activated! ₹${d} deposit + ₹${b} bonus added to your wallet (demo).`);
  };
  const send = () => { const t = text.trim(); if (!t) return; setText(""); ask(t, "Deposit"); };

  const T = (en: ReactNode, h: ReactNode) => (hi ? h : en);
  const body = (k: Msg["kind"]) => {
    switch (k) {
      case "welcome": return T("Hello Rahul! Welcome to LOTUS Support. How can we assist you with your deposit, withdrawal, or account today?", "नमस्ते राहुल! LOTUS सपोर्ट में आपका स्वागत है। डिपॉज़िट, निकासी या अकाउंट में हम आपकी क्या मदद कर सकते हैं?");
      case "Deposit": return (<>
        <b>WELCOME TO LOTUS !!!</b>
        <p className="mt-3">• {T("Minimum Deposit", "न्यूनतम डिपॉज़िट")}: <b>₹300</b> | {T("Maximum Deposit", "अधिकतम डिपॉज़िट")}: <b>₹1,00,000</b><br />• {T(<>Deposit will be credited to your game wallet <b>instantly</b> without entering any UTR ID.</>, <>डिपॉज़िट बिना UTR ID के <b>तुरंत</b> आपके गेम वॉलेट में जुड़ जाएगा।</>)}</p>
        <p className="mt-3">{T("Select an amount below to deposit instantly:", "तुरंत डिपॉज़िट के लिए राशि चुनें:")}</p>
        <div className="mt-3 space-y-2">{AMTS.map((a) => (
          <button key={a} onClick={() => payNow(a)} className="flex w-full items-center justify-center gap-2 rounded-lg bg-gold py-3 text-xs font-extrabold text-gold-foreground shadow-md active:scale-[.98]">
            <QrCode className="size-4" /> PAY DEPOSIT ₹{a} NOW</button>))}</div>
      </>);
      case "Withdrawal": return (<>
        <b>WELCOME TO LOTUS !!!</b>
        <p className="mt-3">• {T("Minimum Withdrawal", "न्यूनतम निकासी")}: <b>₹200</b> | {T("Maximum Withdrawal", "अधिकतम निकासी")}: <b>₹1,00,000</b><br />• {T(<>You can withdraw <b>unlimited times</b> per day.</>, <>आप दिन में <b>असीमित बार</b> निकासी कर सकते हैं।</>)}<br />• {T(<>Payout is processed directly to your Bank Account or UPI within <b>5 to 7 minutes</b>.</>, <>भुगतान <b>5 से 7 मिनट</b> में आपके बैंक या UPI में भेजा जाता है।</>)}</p>
      </>);
      case "Bonus Offers": return (<>
        <b>WELCOME TO LOTUS VIP BONUSES !!!</b>
        <p className="mt-3">{T("Exclusive deposit bonus packages available today. Choose your pack below to claim extra bonus instantly:", "आज के खास डिपॉज़िट बोनस पैक। अतिरिक्त बोनस पाने के लिए पैक चुनें:")}</p>
        <div className="mt-3 space-y-2">{OFFERS.map(({ n, d, b, I }) => (
          <button key={n} onClick={() => claim(n, d, b)} className="flex w-full items-center gap-2.5 rounded-lg border border-border bg-lobby p-2.5 text-left">
            <span className="grid size-8 place-items-center rounded-md border border-gold/60 bg-gold/10"><I className="size-4 text-gold" /></span>
            <span className="flex-1"><b className="block text-[11px]">{n}</b><span className="text-[9px] text-muted-foreground">Deposit ₹{d} Get ₹{b} Bonus</span></span>
            <span className="rounded bg-gold px-1.5 py-1 text-[10px] font-extrabold text-gold-foreground">+₹{b}</span>
          </button>))}</div>
      </>);
      case "Other Help": return (<>
        <b>WELCOME TO LOTUS !!!</b>
        <p className="mt-3">{T("If you need further assistance or personal account help, you can chat directly with our official customer support on Telegram.", "अगर आपको और मदद या अकाउंट से जुड़ी सहायता चाहिए, तो Telegram पर हमारे आधिकारिक सपोर्ट से सीधे बात करें।")}</p>
        <a href="https://t.me/lotus365support" target="_blank" rel="noreferrer" className="mt-3 flex items-center justify-center gap-2 rounded-lg bg-telegram py-3 text-xs font-extrabold text-foreground shadow-md">
          <Send className="size-4" /> CHAT WITH ADMIN ON TELEGRAM</a>
      </>);
      default: return null;
    }
  };

  return createPortal(
    <div className="fixed inset-0 z-50 mx-auto flex max-w-[430px] animate-intro-fade flex-col bg-lobby">
      <header className="flex items-center gap-3 bg-lobby-deep px-3 py-3">
        <button onClick={onClose} aria-label="Back" className="grid size-9 place-items-center rounded-lg bg-lobby-card"><ArrowLeft className="size-4" /></button>
        <span className="relative grid size-10 place-items-center rounded-full bg-lobby-card"><Headphones className="size-5 text-gold" /><span className="absolute bottom-0.5 right-0.5 size-2 rounded-full bg-win" /></span>
        <div className="flex-1"><p className="text-sm font-extrabold">Customer Support</p><p className="flex items-center gap-1 text-[10px] font-bold text-win"><span className="size-1.5 rounded-full bg-win" /> Active Now</p></div>
        <button onClick={() => setHi((v) => !v)} className="flex items-center gap-1 rounded-lg bg-gold px-3 py-2 text-xs font-extrabold text-gold-foreground"><Globe className="size-3.5" /> {hi ? "English" : "हिंदी"}</button>
      </header>
      <div className="grid grid-cols-2 gap-2 px-3 py-3">
        {QUICK.map(({ k, hi: h, I }) => (
          <button key={k} onClick={() => { setSel(k); ask(hi ? h : k, k); }}
            className={`flex items-center justify-center gap-2 rounded-lg border bg-lobby-deep py-2.5 text-xs font-bold transition ${sel === k ? "border-gold" : "border-border"}`}>
            <I className="size-4 text-gold" /> {hi ? h : k}</button>
        ))}
      </div>
      <div ref={box} className="no-scrollbar flex-1 space-y-3 overflow-y-auto px-3 pb-3">
        {msgs.map((m) => m.from === "me" ? (
          <div key={m.id} className="flex animate-pop flex-col items-end">
            <span className="rounded-2xl rounded-br-sm bg-gold px-3 py-2 text-xs font-bold text-gold-foreground">{m.text}</span>
            <span className="mt-1 text-[9px] text-muted-foreground">{m.time}</span>
          </div>
        ) : (
          <div key={m.id} className="animate-pop">
            <div className="max-w-[85%] rounded-2xl rounded-tl-sm border border-border bg-lobby-deep p-3 text-[11px] leading-relaxed">{m.text ?? body(m.kind)}</div>
            <span className="mt-1 block text-[9px] text-muted-foreground">{m.time}</span>
          </div>
        ))}
        {typing && <p className="flex items-center gap-1 text-[10px] text-muted-foreground"><span className="animate-pulse text-gold">● ● ●</span> Support is typing...</p>}
      </div>
      <form onSubmit={(e) => { e.preventDefault(); send(); }} className="flex gap-2 bg-lobby-deep p-3">
        <input value={text} onChange={(e) => setText(e.target.value)} placeholder={hi ? "अपना सवाल लिखें..." : "Type your query..."} className="flex-1 rounded-lg border border-border bg-lobby px-3 py-2.5 text-xs outline-none placeholder:text-muted-foreground" />
        <button aria-label="Send" className="grid size-10 place-items-center rounded-lg bg-gold text-gold-foreground"><Send className="size-4" /></button>
      </form>
    </div>,
    document.body,
  );
}
