/* WhatsApp Smart Widget — Lawyerit
 * Floating button, qualifying questions, pre-filled WhatsApp message
 * Tal number: 0547975288, wa.me/972547975288
 */

const WHATSAPP_NUMBER = "972547975288";

const TOPICS = [
  { id: "dpo",       label_he: "פרטיות / DPO",      label_en: "Privacy / DPO",        msg_he: "פרטיות ו-DPO",      msg_en: "Privacy & DPO" },
  { id: "gc",        label_he: "ייעוץ משפטי / GC",   label_en: "Legal / GC",           msg_he: "ייעוץ משפטי",       msg_en: "Legal advisory" },
  { id: "compliance",label_he: "ציות פיננסי",       label_en: "Financial Compliance",  msg_he: "ציות פיננסי",       msg_en: "Financial compliance" },
  { id: "ai-act",    label_he: "AI Act / רגולציה",  label_en: "AI Act / Regulation",   msg_he: "AI Act ורגולציה",   msg_en: "AI Act & regulation" },
  { id: "other",     label_he: "אחר",               label_en: "Other",                msg_he: "נושא אחר",          msg_en: "Other" },
];

function WhatsAppWidget() {
  var lang = useLang();
  var isOpen = React.useState(false);
  var setIsOpen = isOpen[1];
  isOpen = isOpen[0];
  var stepArr = React.useState(0);
  var step = stepArr[0], setStep = stepArr[1];
  var topicArr = React.useState(null);
  var selectedTopic = topicArr[0], setSelectedTopic = topicArr[1];
  var nameArr = React.useState("");
  var companyName = nameArr[0], setCompanyName = nameArr[1];
  var hintArr = React.useState(false);
  var showHint = hintArr[0], setShowHint = hintArr[1];

  React.useEffect(function() {
    var timer = setTimeout(function() {
      if (!isOpen) setShowHint(true);
    }, 5000);
    return function() { clearTimeout(timer); };
  }, [isOpen]);

  var isEn = lang === "en";

  function buildMessage() {
    var topic = TOPICS.find(function(t) { return t.id === selectedTopic; });
    var topicText = isEn ? (topic ? topic.msg_en : "") : (topic ? topic.msg_he : "");
    var greeting = isEn ? "Hi Tal, I came through your website" : "היי טל, הגעתי דרך האתר";
    var interest = isEn ? "I am interested in: " + topicText : "מעניין אותי: " + topicText;
    var company = companyName.trim() ? (isEn ? "Company: " + companyName.trim() : "חברה: " + companyName.trim()) : "";
    return encodeURIComponent([greeting, interest, company].filter(Boolean).join("\n"));
  }

  function openWhatsApp() {
    var msg = buildMessage();
    window.open("https://wa.me/" + WHATSAPP_NUMBER + "?text=" + msg, "_blank");
    setIsOpen(false);
    setStep(0);
    setSelectedTopic(null);
    setCompanyName("");
  }

  function handleClose() {
    setIsOpen(false);
    setStep(0);
    setSelectedTopic(null);
    setCompanyName("");
  }

  var svgPath = "M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51l-.57-.01c-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.71.306 1.263.489 1.694.625.712.227 1.36.195 1.872.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z";

  return (
    <React.Fragment>
      {!isOpen && (
        <div style={{ position: "fixed", bottom: 24, insetInlineEnd: 24, zIndex: 9998, display: "flex", alignItems: "flex-end", gap: 10 }}>
          {showHint && (
            <div style={{ background: "#fff", borderRadius: 14, padding: "12px 16px", boxShadow: "0 4px 20px rgba(0,0,0,0.12)", fontSize: 14, color: "#1C1E21", maxWidth: 220, lineHeight: 1.45, position: "relative", cursor: "pointer", animation: "fadeInUp 0.3s ease" }} onClick={function() { setIsOpen(true); setShowHint(false); }}>
              {isEn ? "Got a question? Let us chat on WhatsApp" : "יש שאלה? בואו נדבר בווטסאפ"}
              <span style={{ position: "absolute", insetInlineEnd: -6, bottom: 18, width: 12, height: 12, background: "#fff", transform: "rotate(45deg)", boxShadow: "2px -2px 4px rgba(0,0,0,0.05)" }} />
            </div>
          )}
          <button onClick={function() { setIsOpen(true); setShowHint(false); }} aria-label="WhatsApp" style={{ width: 56, height: 56, borderRadius: "50%", background: "#25D366", border: "none", cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center", boxShadow: "0 4px 16px rgba(37,211,102,0.4)", transition: "transform 0.2s, box-shadow 0.2s", zIndex: 9999 }}>
            <svg width="28" height="28" viewBox="0 0 24 24" fill="white"><path d={svgPath} /></svg>
          </button>
        </div>
      )}

      {isOpen && (
        <React.Fragment>
          <div onClick={handleClose} style={{ position: "fixed", inset: 0, background: "rgba(0,0,0,0.4)", zIndex: 99999, animation: "fadeIn 0.2s ease" }} />
          <div style={{ position: "fixed", bottom: 24, insetInlineEnd: 24, width: "min(360px, calc(100vw - 48px))", background: "#fff", borderRadius: 16, boxShadow: "0 12px 40px rgba(0,0,0,0.15)", zIndex: 100000, overflow: "hidden", animation: "slideUp 0.25s cubic-bezier(0.4,0,0.2,1)" }}>
            <div style={{ background: "#25D366", padding: "20px 22px 18px", color: "#fff", display: "flex", alignItems: "center", gap: 12 }}>
              <div style={{ width: 42, height: 42, borderRadius: "50%", background: "rgba(255,255,255,0.2)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
                <svg width="24" height="24" viewBox="0 0 24 24" fill="white"><path d={svgPath} /></svg>
              </div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 16, fontWeight: 600 }}>{isEn ? "Chat with Tal" : "לצ" + String.fromCharCode(39) + "וט עם טל"}</div>
                <div style={{ fontSize: 12, opacity: 0.85, marginTop: 2 }}>{isEn ? "Typically replies within a few hours" : "בדרך כלל עונה תוך כמה שעות"}</div>
              </div>
              <button onClick={handleClose} aria-label={isEn ? "Close" : "סגור"} style={{ background: "rgba(255,255,255,0.2)", border: "none", color: "#fff", width: 30, height: 30, borderRadius: "50%", cursor: "pointer", fontSize: 16, display: "flex", alignItems: "center", justifyContent: "center" }}>{"×"}</button>
            </div>

            <div style={{ padding: "22px 22px 20px" }}>
              {step === 0 && (
                <React.Fragment>
                  <div style={{ fontSize: 15, fontWeight: 600, marginBottom: 4, color: "#1C1E21" }}>{isEn ? "What can we help with?" : "במה אפשר לעזור?"}</div>
                  <div style={{ fontSize: 13, color: "#667781", marginBottom: 16 }}>{isEn ? "Select a topic so Tal knows the context" : "בחרו נושא כדי שטל תדע במה מדובר"}</div>
                  <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                    {TOPICS.map(function(topic) {
                      return (
                        <button key={topic.id} onClick={function() { setSelectedTopic(topic.id); setStep(1); }} style={{ display: "flex", alignItems: "center", gap: 10, padding: "12px 14px", borderRadius: 10, border: "1px solid #E9ECEF", background: "#fff", cursor: "pointer", fontSize: 14, color: "#1C1E21", textAlign: "start", transition: "all 0.15s" }}>
                          <span style={{ width: 32, height: 32, borderRadius: 8, background: "#F0F2F5", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 16, flexShrink: 0 }}>
                            {topic.id === "dpo" ? "\uD83D\uDD12" : topic.id === "gc" ? "\uD83D\uDCCB" : topic.id === "compliance" ? "\u2696\uFE0F" : topic.id === "ai-act" ? "\uD83E\uDD16" : "\uD83D\uDCAC"}
                          </span>
                          {isEn ? topic.label_en : topic.label_he}
                        </button>
                      );
                    })}
                  </div>
                </React.Fragment>
              )}

              {step === 1 && (
                <React.Fragment>
                  <div style={{ fontSize: 15, fontWeight: 600, marginBottom: 4, color: "#1C1E21" }}>{isEn ? "What is the company name?" : "מה שם החברה?"}</div>
                  <div style={{ fontSize: 13, color: "#667781", marginBottom: 16 }}>{isEn ? "Optional - helps Tal prepare" : "אופציונלי - עוזר לטל להתכונן"}</div>
                  <input type="text" value={companyName} onChange={function(e) { setCompanyName(e.target.value); }} onKeyDown={function(e) { if (e.key === "Enter") openWhatsApp(); }} placeholder={isEn ? "Company name" : "שם החברה"} autoFocus style={{ width: "100%", padding: "12px 14px", borderRadius: 10, border: "1px solid #E9ECEF", fontSize: 14, outline: "none", boxSizing: "border-box", fontFamily: "inherit" }} />
                  <div style={{ display: "flex", gap: 8, marginTop: 16 }}>
                    <button onClick={function() { setStep(0); }} style={{ padding: "10px 16px", borderRadius: 10, border: "1px solid #E9ECEF", background: "#fff", cursor: "pointer", fontSize: 14, color: "#667781" }}>{isEn ? "Back" : "חזור"}</button>
                    <button onClick={openWhatsApp} style={{ flex: 1, padding: "10px 16px", borderRadius: 10, border: "none", background: "#25D366", color: "#fff", cursor: "pointer", fontSize: 14, fontWeight: 600, display: "flex", alignItems: "center", justifyContent: "center", gap: 8 }}>
                      <svg width="18" height="18" viewBox="0 0 24 24" fill="white"><path d={svgPath} /></svg>
                      {isEn ? "Start WhatsApp Chat" : "פתיחת צ" + String.fromCharCode(39) + "אט בווטסאפ"}
                    </button>
                  </div>
                </React.Fragment>
              )}
            </div>

            <div style={{ padding: "10px 22px", background: "#F0F2F5", fontSize: 12, color: "#667781", textAlign: "center" }}>
              {isEn ? "Your message goes directly to Tal on WhatsApp" : "ההודעה מגיעה ישירות לטל בווטסאפ"}
            </div>
          </div>
        </React.Fragment>
      )}

      <style>{"@keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } } @keyframes fadeInUp { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: translateY(0); } } @keyframes slideUp { from { opacity: 0; transform: translateY(20px); } to { opacity: 1; transform: translateY(0); } }"}</style>
    </React.Fragment>
  );
}

Object.assign(window, { WhatsAppWidget: WhatsAppWidget });
