/* ============================================================
   ChatRequest — chat-style servis talep akışı (modal)
   ============================================================ */

const SERVICE_OPTIONS = [
  { id: "kombi-ariza", label: "Kombi arızası", icon: Icon.Flame },
  { id: "kombi-bakim", label: "Kombi bakımı / onarım", icon: Icon.Tool },
  { id: "kazan", label: "Yoğuşmalı kazan", icon: Icon.Spark },
  { id: "hidrofor", label: "Hidrofor", icon: Icon.Droplet },
  { id: "klima", label: "Klima montaj / arıza", icon: Icon.Snowflake },
  { id: "petek", label: "Petek tesisatı yıkama", icon: Icon.Droplet },
  { id: "yedek", label: "Orijinal yedek parça", icon: Icon.Badge },
  { id: "diger", label: "Diğer / emin değilim", icon: Icon.Spark },
];

const URGENCY_OPTIONS = [
  { id: "today", label: "Bugün — kombi çalışmıyor", hot: true },
  { id: "tomorrow", label: "Yarın olabilir" },
  { id: "week", label: "Bu hafta içinde" },
  { id: "flexible", label: "Esnek, planlayalım" },
];

const DISTRICTS = [
  "Kars Merkez", "Selim", "Kağızman",
  "Susuz", "Arpaçay", "Akyaka", "Digor",
];

function ChatRequest({ open, onClose, initialService = null }) {
  const [step, setStep] = React.useState(0);
  const [answers, setAnswers] = React.useState({
    service: null, urgency: null, district: null, brand: "", name: "", phone: "",
  });
  const [typing, setTyping] = React.useState(false);
  const [submitted, setSubmitted] = React.useState(false);
  const scrollRef = React.useRef(null);
  const messagesEndRef = React.useRef(null);

  React.useEffect(() => {
    if (open && initialService) {
      setAnswers((a) => ({ ...a, service: initialService }));
      setStep(1);
    }
  }, [open, initialService]);

  React.useEffect(() => {
    if (!open) {
      // reset on close
      const t = setTimeout(() => {
        setStep(0);
        setAnswers({ service: null, urgency: null, district: null, brand: "", name: "", phone: "" });
        setSubmitted(false);
      }, 250);
      return () => clearTimeout(t);
    }
  }, [open]);

  React.useEffect(() => {
    // simulate typing dot on step change
    setTyping(true);
    const t = setTimeout(() => setTyping(false), 650);
    return () => clearTimeout(t);
  }, [step, open]);

  React.useEffect(() => {
    if (messagesEndRef.current) {
      messagesEndRef.current.scrollIntoView({ behavior: "smooth", block: "end" });
    }
  }, [step, typing, submitted]);

  if (!open) return null;

  const pick = (key, value, autoAdvance = true) => {
    setAnswers((a) => ({ ...a, [key]: value }));
    if (autoAdvance) setTimeout(() => setStep((s) => s + 1), 200);
  };

  const serviceLabel = answers.service ? SERVICE_OPTIONS.find((s) => s.id === answers.service)?.label : null;
  const urgencyLabel = answers.urgency ? URGENCY_OPTIONS.find((s) => s.id === answers.urgency)?.label : null;

  const submit = () => {
    // Build WhatsApp message
    const lines = [
      "Merhaba Taner Elektronik 👋",
      "",
      "Servis talebim:",
      `• Hizmet: ${serviceLabel || "—"}`,
      `• Aciliyet: ${urgencyLabel || "—"}`,
      `• İlçe / Bölge: ${answers.district || "—"}`,
      `• Ad Soyad: ${answers.name}`,
      `• Telefon: ${answers.phone}`,
      "",
      "Geri dönüşünüzü bekliyorum.",
    ];
    const text = encodeURIComponent(lines.join("\n"));
    const waUrl = `https://wa.me/905541939736?text=${text}`;
    window.open(waUrl, "_blank", "noopener,noreferrer");

    setSubmitted(true);
    setStep(5);
  };

  return (
    <div
      role="dialog"
      aria-modal="true"
      aria-label="Servis Talep Et"
      style={{
        position: "fixed", inset: 0, zIndex: 100,
        background: "rgba(15, 30, 25, 0.42)",
        backdropFilter: "blur(6px)",
        display: "flex", alignItems: "flex-end", justifyContent: "center",
        animation: "fadeIn 200ms ease",
      }}
      onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}
    >
      <style>{`
        @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
        @keyframes slideUp { from { transform: translateY(40px); opacity: 0; } to { transform: none; opacity: 1; } }
        @keyframes msgIn { from { transform: translateY(6px); opacity: 0; } to { transform: none; opacity: 1; } }
        @keyframes dot { 0%, 60%, 100% { transform: translateY(0); opacity: 0.4; } 30% { transform: translateY(-3px); opacity: 1; } }
      `}</style>

      <div
        style={{
          width: "min(560px, 100%)",
          maxHeight: "min(720px, 90vh)",
          background: "var(--bg-elev)",
          borderRadius: "var(--r-xl) var(--r-xl) 0 0",
          display: "flex", flexDirection: "column",
          boxShadow: "var(--shadow-lg)",
          animation: "slideUp 320ms cubic-bezier(0.2, 0.7, 0.2, 1)",
          overflow: "hidden",
          margin: "0 12px 0",
        }}
      >
        {/* Header */}
        <div style={{
          padding: "16px 20px", display: "flex", alignItems: "center", gap: 12,
          borderBottom: "1px solid var(--line)",
          background: "linear-gradient(180deg, var(--green-50), transparent)",
        }}>
          <div style={{
            position: "relative",
            width: 40, height: 40, borderRadius: "50%",
            background: "var(--green-700)", color: "#fff",
            display: "grid", placeItems: "center", fontWeight: 800,
          }}>
            T
            <span style={{
              position: "absolute", bottom: 1, right: 1,
              width: 10, height: 10, borderRadius: "50%",
              background: "var(--green-500)",
              border: "2px solid var(--bg-elev)",
            }} />
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ fontWeight: 700, fontSize: 15 }}>{CONTACT_NAME} · Baymak Yetkili Servis</div>
            <div style={{ fontSize: 12, color: "var(--green-700)", display: "flex", alignItems: "center", gap: 6 }}>
              <span style={{ width: 6, height: 6, borderRadius: "50%", background: "var(--green-600)" }} />
              Şu anda çevrimiçi · Tipik yanıt: 2 dk
            </div>
          </div>
          <button
            onClick={onClose}
            aria-label="Kapat"
            style={{
              all: "unset", cursor: "pointer",
              width: 36, height: 36, borderRadius: "50%",
              display: "grid", placeItems: "center",
              color: "var(--ink-soft)",
            }}
            onMouseEnter={(e) => { e.currentTarget.style.background = "var(--green-100)"; }}
            onMouseLeave={(e) => { e.currentTarget.style.background = "transparent"; }}
          >
            <Icon.Close width="20" height="20" />
          </button>
        </div>

        {/* Messages */}
        <div ref={scrollRef} style={{
          flex: 1, overflowY: "auto",
          padding: "20px 20px 8px",
          display: "flex", flexDirection: "column", gap: 14,
          background: "var(--green-50)",
        }}>
          <Bubble from="bot">
            Merhaba! 👋 Servis talebinizi alabilmem için birkaç hızlı soru soracağım.
            <br /><br />
            <strong>Hangi konuda yardıma ihtiyacınız var?</strong>
          </Bubble>

          {step >= 1 && answers.service && (
            <Bubble from="user">{serviceLabel}</Bubble>
          )}

          {step >= 1 && !typing && (
            <Bubble from="bot">
              Anladım. <strong>Ne zaman gelelim?</strong>
            </Bubble>
          )}
          {step >= 2 && answers.urgency && (
            <Bubble from="user">{urgencyLabel}</Bubble>
          )}

          {step >= 2 && !typing && (
            <Bubble from="bot">
              <strong>Hangi ilçede / mahalledesiniz?</strong>
            </Bubble>
          )}
          {step >= 3 && answers.district && (
            <Bubble from="user">{answers.district}</Bubble>
          )}

          {step >= 3 && !typing && (
            <Bubble from="bot">
              Son olarak iletişim için sadece adınız ve telefon numaranız yeterli.
              {answers.urgency === "today" && (
                <><br /><br /><span style={{ color: "var(--green-800)", fontWeight: 600 }}>
                  ⚡ Acil durumlarda 90 dk içinde ekibimiz kapınızda.
                </span></>
              )}
            </Bubble>
          )}

          {step >= 4 && submitted && (
            <>
              <Bubble from="user">
                {answers.name} · <span className="tel">{answers.phone}</span>
              </Bubble>
              <Bubble from="bot" success>
                <strong>Son adım, {answers.name.split(" ")[0]}!</strong>
                <br /><br />
                Mesajınız WhatsApp'ta hazır olarak açıldı. 📲 <strong>"Gönder"</strong>e basmanız yeterli — ekibimiz <strong>{answers.district}</strong> için size dönecek.
                <br /><br />
                <span style={{ color: "var(--ink-mute)", fontSize: 13 }}>WhatsApp açılmadıysa aşağıdan tekrar deneyin:</span>
                <div style={{ marginTop: 10, display: "flex", gap: 8, flexWrap: "wrap" }}>
                  <a href={`https://wa.me/905541939736?text=${encodeURIComponent(`Merhaba Taner Elektronik 👋\n\nServis talebim:\n• Hizmet: ${serviceLabel || "—"}\n• Aciliyet: ${urgencyLabel || "—"}\n• İlçe / Bölge: ${answers.district || "—"}\n• Ad Soyad: ${answers.name}\n• Telefon: ${answers.phone}\n\nGeri dönüşünüzü bekliyorum.`)}`}
                     target="_blank" rel="noreferrer" className="btn btn-wa btn-sm">
                    <Icon.Whatsapp width="14" height="14" /> WhatsApp'ı aç
                  </a>
                  <a href={PHONE_LINK} className="btn btn-primary btn-sm">
                    <Icon.Phone width="14" height="14" /> {PHONE_DISPLAY}
                  </a>
                </div>
              </Bubble>
            </>
          )}

          {typing && step < 5 && <TypingIndicator />}
          <div ref={messagesEndRef} />
        </div>

        {/* Input area — varies by step */}
        <div style={{
          borderTop: "1px solid var(--line)",
          background: "var(--bg-elev)",
          padding: "14px 16px 18px",
          maxHeight: 280, overflowY: "auto",
        }}>
          {step === 0 && (
            <OptionGrid>
              {SERVICE_OPTIONS.map((s) => (
                <OptionChip key={s.id} icon={s.icon} onClick={() => pick("service", s.id)}>
                  {s.label}
                </OptionChip>
              ))}
            </OptionGrid>
          )}
          {step === 1 && (
            <OptionGrid>
              {URGENCY_OPTIONS.map((u) => (
                <OptionChip key={u.id} onClick={() => pick("urgency", u.id)} hot={u.hot}>
                  {u.label}
                </OptionChip>
              ))}
            </OptionGrid>
          )}
          {step === 2 && (
            <OptionGrid>
              {DISTRICTS.map((d) => (
                <OptionChip key={d} onClick={() => pick("district", d)}>{d}</OptionChip>
              ))}
            </OptionGrid>
          )}
          {step === 3 && (
            <ContactForm
              answers={answers}
              setAnswers={setAnswers}
              onSubmit={submit}
            />
          )}
          {step >= 4 && !submitted && (
            <div style={{ textAlign: "center", padding: 12, color: "var(--ink-mute)", fontSize: 13 }}>
              Gönderiliyor...
            </div>
          )}
          {submitted && (
            <button className="btn btn-secondary" onClick={onClose} style={{ width: "100%" }}>
              Kapat
            </button>
          )}
        </div>
      </div>
    </div>
  );
}

function Bubble({ from, success, children }) {
  const isBot = from === "bot";
  return (
    <div style={{
      display: "flex", justifyContent: isBot ? "flex-start" : "flex-end",
      animation: "msgIn 260ms cubic-bezier(0.2, 0.7, 0.2, 1)",
    }}>
      <div style={{
        maxWidth: "82%",
        background: success ? "linear-gradient(180deg, oklch(95% 0.035 155), white)" :
                    isBot ? "var(--bg-elev)" : "var(--green-700)",
        color: isBot ? "var(--ink)" : "#fff",
        padding: "12px 16px",
        borderRadius: isBot ? "16px 16px 16px 4px" : "16px 16px 4px 16px",
        border: success ? "1px solid var(--green-200)" : isBot ? "1px solid var(--line)" : "0",
        fontSize: 15, lineHeight: 1.5,
        boxShadow: isBot ? "var(--shadow-xs)" : "none",
      }}>
        {children}
      </div>
    </div>
  );
}

function TypingIndicator() {
  return (
    <div style={{ display: "flex", justifyContent: "flex-start" }}>
      <div style={{
        background: "var(--bg-elev)", border: "1px solid var(--line)",
        padding: "12px 16px", borderRadius: "16px 16px 16px 4px",
        display: "flex", gap: 4,
      }}>
        {[0, 1, 2].map((i) => (
          <span key={i} style={{
            width: 6, height: 6, borderRadius: "50%",
            background: "var(--ink-mute)",
            animation: `dot 1.2s ${i * 0.15}s ease-in-out infinite`,
          }} />
        ))}
      </div>
    </div>
  );
}

function OptionGrid({ children }) {
  return (
    <div style={{
      display: "flex", flexWrap: "wrap", gap: 8,
      animation: "msgIn 260ms 100ms cubic-bezier(0.2, 0.7, 0.2, 1) both",
    }}>
      {children}
    </div>
  );
}

function OptionChip({ icon: I, onClick, hot, children }) {
  return (
    <button
      onClick={onClick}
      style={{
        all: "unset", cursor: "pointer",
        display: "inline-flex", alignItems: "center", gap: 8,
        padding: "10px 16px", borderRadius: "var(--r-pill)",
        background: hot ? "color-mix(in oklch, var(--accent) 14%, white)" : "var(--bg-elev)",
        border: `1px solid ${hot ? "color-mix(in oklch, var(--accent) 35%, white)" : "var(--line-strong)"}`,
        fontSize: 14, fontWeight: 600, color: hot ? "oklch(38% 0.15 50)" : "var(--ink)",
        transition: "all 150ms ease",
      }}
      onMouseEnter={(e) => {
        e.currentTarget.style.borderColor = "var(--green-600)";
        e.currentTarget.style.background = "var(--green-100)";
        e.currentTarget.style.color = "var(--green-800)";
      }}
      onMouseLeave={(e) => {
        e.currentTarget.style.borderColor = hot ? "color-mix(in oklch, var(--accent) 35%, white)" : "var(--line-strong)";
        e.currentTarget.style.background = hot ? "color-mix(in oklch, var(--accent) 14%, white)" : "var(--bg-elev)";
        e.currentTarget.style.color = hot ? "oklch(38% 0.15 50)" : "var(--ink)";
      }}
    >
      {I && <I width="14" height="14" />}
      {children}
    </button>
  );
}

function ContactForm({ answers, setAnswers, onSubmit }) {
  const valid = answers.name.trim().length >= 2 && /\d{10,}/.test(answers.phone.replace(/\D/g, ""));
  return (
    <form onSubmit={(e) => { e.preventDefault(); if (valid) onSubmit(); }}
          style={{ display: "flex", flexDirection: "column", gap: 10 }}>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
        <input
          className="input"
          placeholder="Adınız Soyadınız"
          value={answers.name}
          onChange={(e) => setAnswers((a) => ({ ...a, name: e.target.value }))}
          autoFocus
          required
        />
        <input
          className="input tel"
          placeholder="0 5__ ___ __ __"
          value={answers.phone}
          inputMode="tel"
          onChange={(e) => setAnswers((a) => ({ ...a, phone: e.target.value }))}
          required
        />
      </div>
      <button type="submit" className="btn btn-primary" disabled={!valid}
              style={{ opacity: valid ? 1 : 0.5, cursor: valid ? "pointer" : "not-allowed", width: "100%" }}>
        <Icon.Send width="16" height="16" /> Talebi Gönder
      </button>
      <div style={{ fontSize: 12, color: "var(--ink-mute)", textAlign: "center" }}>
        KVKK kapsamında bilgileriniz yalnızca servis talebi için kullanılır.
      </div>
    </form>
  );
}

window.ChatRequest = ChatRequest;
