/* === CONTACT — /contact === */

const { useState: ctState } = React;

/* Web3Forms access key. Get yours at https://web3forms.com/ — they email
   it after you enter your email address. Submissions arrive at the email
   you registered with (set up to land at allionresurs@gmail.com). */
const WEB3FORMS_ACCESS_KEY = "32800025-eb3e-4956-91be-ba5e63a9e3fb";

const CONTACT_SERVICES = [
"AI-агентские системы",
"Корпоративные сайты и веб-платформы",
"Мобильные приложения",
"CRM, ERP и бизнес-автоматизация",
"Интеграция AI в бизнес-процессы",
"Future Home — умные пространства",
"Международные поставки оборудования",
"Консультация"];


function ContactPage() {
  const [form, setForm] = ctState({ name: "", email: "", company: "", service: "", message: "" });
  const [loading, setLoading] = ctState(false);
  const [submitted, setSubmitted] = ctState(false);
  const [error, setError] = ctState(null);
  const titleRef = window.useReveal("reveal");
  const brand = window.SITE_DATA.brand;

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError(null);
    setLoading(true);
    try {
      const payload = {
        access_key: WEB3FORMS_ACCESS_KEY,
        subject: `Заявка с allion.group — ${form.name}${form.company ? " · " + form.company : ""}`,
        from_name: form.name,
        email: form.email,
        company: form.company || "—",
        service: form.service || "—",
        message: form.message,
        botcheck: "",
      };
      const res = await fetch("https://api.web3forms.com/submit", {
        method: "POST",
        headers: { "Content-Type": "application/json", "Accept": "application/json" },
        body: JSON.stringify(payload),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok || !data.success) {
        throw new Error(data.message || `Ошибка ${res.status}`);
      }
      setSubmitted(true);
    } catch (err) {
      setError(err.message || "Не удалось отправить. Попробуйте позже или напишите нам на " + brand.email);
    } finally {
      setLoading(false);
    }
  };

  return (
    <section style={{
      padding: "140px 32px 140px",
      background: "#f8f7f4",
      position: "relative",
      overflow: "hidden",
      minHeight: "100vh"
    }}>
      <window.AnimatedBlob size={620} gradient="linear-gradient(135deg, #0a6ef5, #05b89c)" style={{ top: "-15%", right: "-10%" }} opacity={0.12} />
      <window.AnimatedBlob size={420} gradient="linear-gradient(135deg, #e85d00, #f5a623)" style={{ bottom: "-25%", left: "-5%" }} opacity={0.08} />
      <window.FloatingShape kind="diamond" size={70} color="#0a6ef5" style={{ top: "20%", left: "8%", opacity: 0.15 }} speed={20} />
      <window.FloatingShape kind="ring" size={120} color="#05b89c" style={{ bottom: "20%", right: "8%", opacity: 0.18 }} speed={28} />
      <div className="grid-bg" style={{ position: "absolute", inset: 0, opacity: 0.4, pointerEvents: "none" }} />

      <div ref={titleRef} style={{ maxWidth: 1680, margin: "0 auto", position: "relative" }}>
        <window.Breadcrumb items={[{ to: "/", label: "Главная" }, { label: "Контакты" }]} />
        <window.SectionTag>Работа с нами</window.SectionTag>
        <h1 style={{
          fontFamily: "Syne, sans-serif",
          fontSize: "clamp(44px, 5.6vw, 100px)",
          fontWeight: 800,
          color: "#0d0d0d",
          letterSpacing: "-0.035em",
          lineHeight: 0.98,
          marginTop: 24,
          marginBottom: 60,
          maxWidth: 1320
        }}>
          Построим что-то<br />
          <span className="text-gradient-blue">экстраординарное</span>
        </h1>

        <div style={{
          display: "grid",
          gridTemplateColumns: "1fr 1.4fr",
          gap: 60,
          alignItems: "start"
        }} className="contact-grid">
          {/* Left — info */}
          <div>
            <p style={{
              fontFamily: "Inter, sans-serif",
              fontSize: 17, lineHeight: 1.75, color: "#3a3a3a",
              marginBottom: 48
            }}>
              Расскажите про вашу задачу. Отвечаем в течение 24 часов —
              сразу с архитектурным мнением и предложением следующих шагов.
            </p>

            <div style={{ display: "flex", flexDirection: "column", gap: 22, marginBottom: 52 }}>
              {/* Email */}
              <ContactRow icon={window.I.Mail} label="Email">
                <a href={`mailto:${brand.email}`} style={{ fontSize: 15, fontWeight: 500, color: "#0d0d0d" }} className="link-anim">
                  {brand.email}
                </a>
              </ContactRow>

              {/* Phones — multiple with WA + TG */}
              {brand.phones.map((p, i) =>
              <ContactRow key={i} icon={window.I.Phone} label={`${p.label} · WhatsApp / Telegram`}>
                  <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
                    <a href={`tel:${p.number.replace(/\s/g, "")}`} style={{ fontSize: 15, fontWeight: 500, color: "#0d0d0d", letterSpacing: "0.01em" }} className="link-anim">
                      {p.number}
                    </a>
                    <div style={{ display: "flex", gap: 10 }}>
                      <a href={`https://wa.me/${p.wa}`} target="_blank" rel="noreferrer" style={{
                      fontSize: 11, fontWeight: 600, letterSpacing: "0.06em", textTransform: "uppercase",
                      color: "#05b89c", padding: "3px 10px", borderRadius: 100,
                      background: "rgba(5,184,156,0.08)", border: "1px solid rgba(5,184,156,0.2)"
                    }}>WhatsApp</a>
                      <a href={`https://t.me/+${p.tg}`} target="_blank" rel="noreferrer" style={{
                      fontSize: 11, fontWeight: 600, letterSpacing: "0.06em", textTransform: "uppercase",
                      color: "#0a6ef5", padding: "3px 10px", borderRadius: 100,
                      background: "rgba(10,110,245,0.08)", border: "1px solid rgba(10,110,245,0.2)"
                    }}>Telegram</a>
                    </div>
                  </div>
                </ContactRow>
              )}

              {/* Instagram */}
              <ContactRow icon={window.I.Globe} label="Instagram">
                <a href={brand.instagramUrl} target="_blank" rel="noreferrer" style={{ fontSize: 15, fontWeight: 500, color: "#0d0d0d" }} className="link-anim">
                  @{brand.instagram}
                </a>
              </ContactRow>

              {/* Location — Bishkek, no fixed office */}
              <ContactRow icon={window.I.MapPin} label="Базируемся">
                <div style={{ fontSize: 15, fontWeight: 500, color: "#0d0d0d" }}>
                  {brand.hqCity}, {brand.hqCountry}
                </div>
                <div style={{ fontSize: 12, color: "#7a7a7a", marginTop: 2 }}>

                </div>
              </ContactRow>
            </div>

            <window.Tilt max={3} scale={1.005}>
              <div style={{
                padding: 24,
                background: "#ffffff",
                borderRadius: 20,
                border: "1px solid rgba(0,0,0,0.06)",
                boxShadow: "0 12px 40px rgba(0,0,0,0.04)"
              }}>
                <div style={{
                  display: "inline-flex", alignItems: "center", gap: 8,
                  padding: "4px 12px", borderRadius: 100,
                  background: "rgba(5,184,156,0.1)",
                  border: "1px solid rgba(5,184,156,0.2)",
                  marginBottom: 16
                }}>
                  <span className="pulse-dot" style={{
                    width: 6, height: 6, borderRadius: "50%", background: "#05b89c"
                  }} />
                  <span style={{ fontSize: 10, fontWeight: 700, letterSpacing: "0.1em", textTransform: "uppercase", color: "#05b89c" }}>
                    Принимаем запросы
                  </span>
                </div>
                <div style={{
                  fontFamily: "Syne, sans-serif",
                  fontSize: 17, fontWeight: 700,
                  color: "#0d0d0d", letterSpacing: "-0.015em",
                  marginBottom: 12
                }}>
                  Почему стоит написать
                </div>
                {[
                "Ответ в течение 24 часов",
                "NDA предоставим по запросу",
                "Сразу с инженером, без sales-менеджеров",
                "Discovery как отдельный продукт за фикс"].
                map((it, i) =>
                <div key={i} style={{
                  display: "flex", gap: 10, alignItems: "center",
                  padding: "8px 0",
                  fontSize: 13, color: "#3a3a3a",
                  borderTop: i === 0 ? "none" : "1px dashed rgba(0,0,0,0.06)"
                }}>
                    <window.I.Check size={13} color="#05b89c" />
                    {it}
                  </div>
                )}
              </div>
            </window.Tilt>
          </div>

          {/* Right — form */}
          <div>
            {submitted ?
            <div style={{
              padding: "80px 40px",
              background: "#fff",
              borderRadius: 28,
              border: "1px solid rgba(0,0,0,0.06)",
              textAlign: "center",
              boxShadow: "0 16px 60px rgba(0,0,0,0.06)"
            }}>
                <div style={{
                width: 80, height: 80, borderRadius: "50%",
                background: "rgba(5,184,156,0.1)",
                border: "2px solid rgba(5,184,156,0.3)",
                display: "flex", alignItems: "center", justifyContent: "center",
                margin: "0 auto 24px",
                animation: "fade-in-up 0.6s ease both"
              }}>
                  <window.I.Check size={36} color="#05b89c" strokeWidth={2.2} />
                </div>
                <h3 style={{
                fontFamily: "Syne, sans-serif",
                fontSize: 28, fontWeight: 700, color: "#0d0d0d",
                letterSpacing: "-0.02em", marginBottom: 16
              }}>
                  Сообщение получено
                </h3>
                <p style={{ fontSize: 15, color: "#5a5a5a", lineHeight: 1.7, maxWidth: 380, margin: "0 auto" }}>
                  Мы свяжемся с вами в течение 24 часов. До встречи!
                </p>
              </div> :

            <form onSubmit={handleSubmit} style={{
              padding: 44,
              background: "#fff",
              borderRadius: 28,
              border: "1px solid rgba(0,0,0,0.06)",
              boxShadow: "0 16px 60px rgba(0,0,0,0.06)"
            }}>
                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16, marginBottom: 16 }} className="form-row">
                  <Field label="Имя" required value={form.name} onChange={(v) => setForm({ ...form, name: v })} placeholder="Александр Иванов" />
                  <Field label="Email" required type="email" value={form.email} onChange={(v) => setForm({ ...form, email: v })} placeholder="alex@company.com" />
                </div>
                <Field label="Компания" value={form.company} onChange={(v) => setForm({ ...form, company: v })} placeholder="Acme Corp" />
                <FieldSelect label="Услуга, которая интересует" value={form.service} onChange={(v) => setForm({ ...form, service: v })} options={CONTACT_SERVICES} />
                <Field
                label="Расскажите о проекте"
                required textarea rows={5}
                value={form.message}
                onChange={(v) => setForm({ ...form, message: v })}
                placeholder="Опишите задачу, цели, сроки, бюджет…" />
              

                {error && (
                  <div style={{
                    marginBottom: 14,
                    padding: "12px 14px",
                    borderRadius: 12,
                    background: "rgba(232,93,0,0.08)",
                    border: "1px solid rgba(232,93,0,0.25)",
                    color: "#a33800",
                    fontSize: 13,
                    lineHeight: 1.5,
                  }}>
                    {error}
                  </div>
                )}

                <button
                type="submit"
                disabled={loading}
                style={{
                  width: "100%",
                  padding: "16px",
                  borderRadius: 14,
                  background: loading ? "#7a7a7a" : "linear-gradient(135deg, #0a6ef5, #0552c7)",
                  color: "#fff",
                  border: "none",
                  cursor: loading ? "not-allowed" : "pointer",
                  fontFamily: "Inter, sans-serif",
                  fontSize: 15, fontWeight: 600,
                  display: "flex", alignItems: "center", justifyContent: "center", gap: 10,
                  boxShadow: loading ? "none" : "0 12px 36px rgba(10,110,245,0.3)",
                  transition: "all 0.25s ease",
                  marginTop: 8
                }}
                onMouseEnter={(e) => {if (!loading) {e.currentTarget.style.transform = "translateY(-2px)";e.currentTarget.style.boxShadow = "0 16px 48px rgba(10,110,245,0.4)";}}}
                onMouseLeave={(e) => {e.currentTarget.style.transform = "translateY(0)";e.currentTarget.style.boxShadow = loading ? "none" : "0 12px 36px rgba(10,110,245,0.3)";}}>
                
                  {loading ?
                <>
                      <span style={{
                    width: 16, height: 16,
                    border: "2px solid rgba(255,255,255,0.3)",
                    borderTop: "2px solid #fff",
                    borderRadius: "50%",
                    animation: "spin-slow 0.8s linear infinite"
                  }} />
                      Отправляем…
                    </> :

                <>Отправить сообщение <window.I.ArrowRight size={15} color="#fff" /></>
                }
                </button>
              </form>
            }
          </div>
        </div>
      </div>

      <style>{`
        @media (max-width: 900px){
          .contact-grid{ grid-template-columns: 1fr !important; gap: 40px !important; }
          .form-row{ grid-template-columns: 1fr !important; }
        }
      `}</style>
    </section>);

}

function Field({ label, required, type = "text", textarea, rows, value, onChange, placeholder }) {
  const [focus, setFocus] = ctState(false);
  const baseStyle = {
    width: "100%",
    padding: "13px 16px",
    borderRadius: 12,
    border: focus ? "1.5px solid #0a6ef5" : "1.5px solid rgba(0,0,0,0.1)",
    fontFamily: "Inter, sans-serif",
    fontSize: 14,
    color: "#0d0d0d",
    outline: "none",
    background: "#f8f7f4",
    transition: "border-color 0.2s ease",
    resize: textarea ? "vertical" : "none"
  };
  return (
    <div style={{ marginBottom: 16 }}>
      <label style={{
        display: "block",
        fontSize: 12, fontWeight: 600, color: "#3a3a3a",
        marginBottom: 8, letterSpacing: "0.04em"
      }}>
        {label}{required && " *"}
      </label>
      {textarea ?
      <textarea
        required={required} rows={rows} value={value}
        placeholder={placeholder}
        onChange={(e) => onChange(e.target.value)}
        onFocus={() => setFocus(true)} onBlur={() => setFocus(false)}
        style={baseStyle} /> :


      <input
        required={required} type={type} value={value}
        placeholder={placeholder}
        onChange={(e) => onChange(e.target.value)}
        onFocus={() => setFocus(true)} onBlur={() => setFocus(false)}
        style={baseStyle} />

      }
    </div>);

}

function FieldSelect({ label, value, onChange, options }) {
  const [focus, setFocus] = ctState(false);
  return (
    <div style={{ marginBottom: 16 }}>
      <label style={{
        display: "block",
        fontSize: 12, fontWeight: 600, color: "#3a3a3a",
        marginBottom: 8, letterSpacing: "0.04em"
      }}>
        {label}
      </label>
      <select
        value={value}
        onChange={(e) => onChange(e.target.value)}
        onFocus={() => setFocus(true)} onBlur={() => setFocus(false)}
        style={{
          width: "100%",
          padding: "13px 16px",
          borderRadius: 12,
          border: focus ? "1.5px solid #0a6ef5" : "1.5px solid rgba(0,0,0,0.1)",
          fontFamily: "Inter, sans-serif",
          fontSize: 14,
          color: value ? "#0d0d0d" : "#7a7a7a",
          outline: "none",
          background: "#f8f7f4",
          cursor: "pointer",
          appearance: "none",
          transition: "border-color 0.2s ease"
        }}>
        
        <option value="">Выберите услугу…</option>
        {options.map((o) => <option key={o} value={o}>{o}</option>)}
      </select>
    </div>);

}

window.ContactPage = ContactPage;

function ContactRow({ icon: Ic, label, children }) {
  return (
    <div style={{ display: "flex", gap: 16, alignItems: "flex-start" }}>
      <div style={{
        width: 44, height: 44, borderRadius: 12,
        background: "rgba(10,110,245,0.08)",
        border: "1px solid rgba(10,110,245,0.18)",
        display: "flex", alignItems: "center", justifyContent: "center",
        flexShrink: 0
      }}>
        <Ic size={17} color="#0a6ef5" />
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{
          fontSize: 11, fontWeight: 600,
          letterSpacing: "0.08em", textTransform: "uppercase",
          color: "#7a7a7a", marginBottom: 6
        }}>{label}</div>
        {children}
      </div>
    </div>);

}