/* WhatsAppDemo — WhatsApp-styled chat where the realtor plays the LEAD,
   and Wastafy AI's bot replies via window.claude.complete. */

const SUGGESTIONS_EN = [
  "Hi, saw a 2-bed in Downtown for 2.5M — still available?",
  "What's the service charge on Marina apartments?",
  "Looking for 3-bed villa, Palm or Emirates Hills, under 12M",
  "Can I view this weekend?",
];
const SUGGESTIONS_AR = [
  "مرحبًا، شفت شقة غرفتين في وسط دبي بـ٢.٥ مليون — لسا متاحة؟",
  "كم رسوم الخدمة في شقق المارينا؟",
  "أبحث عن فيلا ٣ غرف، النخلة أو الإمارات هيلز، تحت ١٢ مليون",
  "هل يمكنني المعاينة في عطلة نهاية الأسبوع؟",
];

const WhatsAppDemo = ({ lang }) => {
  const isAR = lang === "ar";
  const [messages, setMessages] = React.useState(() => isAR ? [
    { who: "bot", text: "السلام عليكم 👋 أنا وستفي AI من Realty Dubai. كيف أقدر أساعدك اليوم؟", time: "10:42" },
  ] : [
    { who: "bot", text: "Hi 👋 I'm Wastafy AI from Realty Dubai. What kind of property are you looking for today?", time: "10:42" },
  ]);
  const [input, setInput] = React.useState("");
  const [typing, setTyping] = React.useState(false);
  const scrollRef = React.useRef(null);

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

  const send = async (textOverride) => {
    const text = (textOverride ?? input).trim();
    if (!text || typing) return;
    setInput("");
    const now = new Date();
    const time = `${String(now.getHours()).padStart(2,"0")}:${String(now.getMinutes()).padStart(2,"0")}`;
    setMessages(m => [...m, { who: "lead", text, time }]);
    setTyping(true);

    try {
      const sys = isAR
        ? "أنت 'وستفي AI'، مساعد عقاري ذكي لوكيل عقارات في دبي اسمه Realty Dubai. أنت ترد على عميل محتمل عبر واتساب. كن ودودًا، احترافيًا، مختصرًا (٢-٣ جمل). اطرح سؤالاً متابعًا واحدًا. اقترح موعد معاينة عندما يكون مناسبًا. استخدم الدرهم. لا تخترع أسعارًا غير واقعية. لا تستخدم رموز Markdown."
        : "You are 'Wastafy AI', a real-estate concierge for a Dubai realtor called Realty Dubai. You're chatting with a prospective lead on WhatsApp. Be warm, professional, and concise (2-3 sentences max). Ask one helpful follow-up question. Offer to book a viewing when appropriate. Use AED. Don't invent unrealistic prices. Plain text only — no markdown.";
      const history = messages.slice(-6).map(m => `${m.who === "bot" ? "Wastafy" : "Lead"}: ${m.text}`).join("\n");
      const prompt = `${sys}\n\nConversation so far:\n${history}\nLead: ${text}\nWastafy:`;
      const reply = await window.claude.complete(prompt);
      const t2 = new Date();
      const time2 = `${String(t2.getHours()).padStart(2,"0")}:${String(t2.getMinutes()).padStart(2,"0")}`;
      setMessages(m => [...m, { who: "bot", text: (reply || "").trim() || (isAR ? "عذرًا، حصل خطأ. جرّب مرة ثانية." : "Sorry, hit an error. Try again."), time: time2 }]);
    } catch (e) {
      setMessages(m => [...m, { who: "bot", text: isAR ? "تعذّر الاتصال. حاول مرة أخرى." : "Couldn't connect. Try again.", time }]);
    } finally {
      setTyping(false);
    }
  };

  const suggestions = isAR ? SUGGESTIONS_AR : SUGGESTIONS_EN;

  return (
    <div className="wa-demo">
      <div className="wa-side">
        <div className="vd-eye eyebrow">{isAR ? "اختبر روبوت الدردشة" : "Test the chat bot"}</div>
        <p className="wa-explain">
          {isAR
            ? "هذا ما سيراه عميلك على واتساب. اكتب رسالة كأنك مشترٍ — وستفي تردّ كأنها فريقك، بنبرة وكالتك."
            : "This is what your lead sees on WhatsApp. Type as if you're the buyer — Wastafy AI replies in your agency's voice, around the clock."}
        </p>
        <div className="wa-suggestions">
          <div className="wa-sugg-title mono">{isAR ? "جرّب:" : "Try:"}</div>
          {suggestions.map((s, i) => (
            <button key={i} className="wa-sugg" onClick={() => send(s)} disabled={typing}>
              "{s}"
            </button>
          ))}
        </div>
        <div className="wa-bullets mono">
          <div>↳ {isAR ? "ردود فورية ٢٤/٧" : "Instant replies, 24/7"}</div>
          <div>↳ {isAR ? "يحجز معاينات في تقويمك" : "Books viewings on your calendar"}</div>
          <div>↳ {isAR ? "ينقل العميل ساخنًا إليك" : "Hands off hot leads to you"}</div>
        </div>
      </div>

      <div className="wa-phone">
        <div className="wa-shell">
          <div className="wa-header">
            <div className="wa-back">‹</div>
            <div className="wa-pic">RD</div>
            <div className="wa-meta">
              <div className="wa-name">Realty Dubai</div>
              <div className="wa-status">{typing ? (isAR ? "يكتب..." : "typing…") : (isAR ? "متصل" : "online")}</div>
            </div>
            <div className="wa-icons">
              <span>📹</span><span>📞</span>
            </div>
          </div>

          <div className="wa-body" ref={scrollRef}>
            <div className="wa-date mono">{isAR ? "اليوم" : "TODAY"}</div>
            {messages.map((m, i) => (
              <div key={i} className={`wa-bubble ${m.who}`}>
                <div className="wa-bubble-text">{m.text}</div>
                <div className="wa-bubble-time mono">
                  {m.time}
                  {m.who === "lead" && <span className="wa-tick">✓✓</span>}
                </div>
              </div>
            ))}
            {typing && (
              <div className="wa-bubble bot wa-typing">
                <span></span><span></span><span></span>
              </div>
            )}
          </div>

          <div className="wa-input-row">
            <span className="wa-emoji">😊</span>
            <input
              className="wa-input"
              placeholder={isAR ? "اكتب رسالة" : "Type a message"}
              value={input}
              onChange={e => setInput(e.target.value)}
              onKeyDown={e => { if (e.key === "Enter") send(); }}
              disabled={typing}
            />
            <button className="wa-send" onClick={() => send()} disabled={!input.trim() || typing}>
              <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor"><path d="M2 21l21-9L2 3v7l15 2-15 2v7z"/></svg>
            </button>
          </div>
        </div>
        <div className="vd-disclaimer mono">
          {isAR ? "هذا عرض حي — وستفي AI يكتب الردود فعلًا." : "This is live — Wastafy AI is generating these replies in real time."}
        </div>
      </div>

      <style>{`
        .wa-demo {
          display: grid;
          grid-template-columns: 1fr 1.2fr;
          gap: 64px;
          align-items: start;
        }
        .wa-side .vd-eye { margin-bottom: 16px; }
        .wa-explain {
          font-family: var(--serif);
          font-style: italic;
          font-size: 22px;
          line-height: 1.4;
          color: var(--ink);
          margin: 0 0 32px 0;
          max-width: 30ch;
        }
        .wa-sugg-title { font-size: 10px; color: var(--muted); letter-spacing: 0.14em; margin-bottom: 12px; text-transform: uppercase; }
        .wa-suggestions { display: flex; flex-direction: column; gap: 8px; margin-bottom: 32px; }
        .wa-sugg {
          all: unset;
          padding: 12px 16px;
          border: 1px solid var(--rule-2);
          border-radius: 14px;
          font-family: var(--serif);
          font-style: italic;
          font-size: 14px;
          color: var(--ink-2);
          cursor: pointer;
          line-height: 1.4;
          transition: all .25s var(--ease);
        }
        .wa-sugg:hover:not(:disabled) { background: var(--ink); color: var(--bg); border-color: var(--ink); }
        .wa-sugg:disabled { opacity: 0.5; cursor: wait; }
        .wa-bullets {
          padding-top: 24px;
          border-top: 1px solid var(--rule);
          font-size: 11px;
          color: var(--muted);
          letter-spacing: 0.08em;
          text-transform: uppercase;
          display: flex;
          flex-direction: column;
          gap: 10px;
        }

        /* WhatsApp shell */
        .wa-shell {
          width: 100%;
          max-width: 420px;
          margin: 0 auto;
          background: #efeae2;
          border-radius: 24px;
          overflow: hidden;
          box-shadow: var(--shadow);
          border: 1px solid var(--rule-2);
          display: flex;
          flex-direction: column;
          height: 620px;
        }
        [data-theme="dark"] .wa-shell { background: #0b141a; }

        .wa-header {
          display: grid;
          grid-template-columns: auto auto 1fr auto;
          align-items: center;
          gap: 12px;
          padding: 12px 14px;
          background: #075e54;
          color: #fff;
        }
        .wa-back { font-size: 22px; line-height: 1; }
        .wa-pic {
          width: 36px; height: 36px; border-radius: 50%;
          background: linear-gradient(135deg, var(--accent), #ff8a5c);
          color: #fff;
          display: flex; align-items: center; justify-content: center;
          font-family: var(--mono); font-size: 12px; font-weight: 600;
          letter-spacing: 0.05em;
        }
        .wa-name { font-size: 14px; font-weight: 600; }
        .wa-status { font-size: 11px; opacity: 0.8; }
        .wa-icons { display: flex; gap: 12px; opacity: 0.85; font-size: 16px; }

        .wa-body {
          flex: 1;
          padding: 14px 12px;
          overflow-y: auto;
          background:
            repeating-linear-gradient(45deg, transparent 0 22px, rgba(0,0,0,0.015) 22px 23px),
            repeating-linear-gradient(-45deg, transparent 0 22px, rgba(0,0,0,0.015) 22px 23px),
            #efeae2;
          display: flex;
          flex-direction: column;
          gap: 6px;
        }
        [data-theme="dark"] .wa-body {
          background: #0b141a;
        }
        .wa-date {
          align-self: center;
          font-size: 9px;
          color: #555;
          background: rgba(255,255,255,0.85);
          padding: 4px 10px;
          border-radius: 6px;
          margin: 4px 0 12px;
        }
        [data-theme="dark"] .wa-date { color: #aaa; background: rgba(0,0,0,0.4); }
        .wa-bubble {
          max-width: 78%;
          padding: 7px 10px 6px 12px;
          border-radius: 8px;
          font-size: 14px;
          line-height: 1.35;
          position: relative;
          color: #111;
          animation: bubbleIn .25s var(--ease);
        }
        @keyframes bubbleIn { from { opacity: 0; transform: translateY(4px); } }
        .wa-bubble.bot { background: #fff; align-self: flex-start; border-radius: 8px 8px 8px 2px; }
        .wa-bubble.lead { background: #d9fdd3; align-self: flex-end; border-radius: 8px 8px 2px 8px; }
        [data-theme="dark"] .wa-bubble.bot { background: #1f2c33; color: #e9edef; }
        [data-theme="dark"] .wa-bubble.lead { background: #005c4b; color: #e9edef; }
        .wa-bubble-text { white-space: pre-wrap; word-wrap: break-word; }
        .wa-bubble-time {
          font-size: 9px;
          color: rgba(0,0,0,0.45);
          text-align: right;
          margin-top: 2px;
          display: flex;
          justify-content: flex-end;
          gap: 4px;
          align-items: center;
        }
        [data-theme="dark"] .wa-bubble-time { color: rgba(255,255,255,0.5); }
        .wa-tick { color: #4fc3f7; font-size: 11px; }

        .wa-typing { padding: 10px 14px; display: flex; gap: 4px; }
        .wa-typing span {
          width: 6px; height: 6px; border-radius: 50%; background: #999;
          animation: typingDot 1.2s var(--ease) infinite;
        }
        .wa-typing span:nth-child(2) { animation-delay: 0.2s; }
        .wa-typing span:nth-child(3) { animation-delay: 0.4s; }
        @keyframes typingDot {
          0%, 60%, 100% { transform: translateY(0); opacity: 0.5; }
          30% { transform: translateY(-4px); opacity: 1; }
        }

        .wa-input-row {
          display: grid;
          grid-template-columns: auto 1fr auto;
          align-items: center;
          gap: 8px;
          padding: 8px 10px;
          background: #f0f2f5;
        }
        [data-theme="dark"] .wa-input-row { background: #1f2c33; }
        .wa-emoji { font-size: 22px; opacity: 0.7; }
        .wa-input {
          all: unset;
          background: #fff;
          border-radius: 999px;
          padding: 10px 16px;
          font-family: var(--grotesk);
          font-size: 14px;
          color: #111;
        }
        [data-theme="dark"] .wa-input { background: #2a3942; color: #e9edef; }
        .wa-input::placeholder { color: #999; }
        .wa-send {
          all: unset;
          width: 40px; height: 40px;
          border-radius: 50%;
          background: #075e54;
          color: #fff;
          display: flex;
          align-items: center;
          justify-content: center;
          cursor: pointer;
          transition: transform .25s var(--ease);
        }
        .wa-send:hover:not(:disabled) { transform: scale(1.05); }
        .wa-send:disabled { opacity: 0.4; cursor: not-allowed; }

        @media (max-width: 980px) {
          .wa-demo { grid-template-columns: 1fr; gap: 48px; }
        }
      `}</style>
    </div>
  );
};

window.WhatsAppDemo = WhatsAppDemo;
