/* global React */
const { useState, useEffect, useCallback } = React;

// ─── Backend ─────────────────────────────────────────────────────────
// Same Supabase Edge Functions used by the production eoma.ai landing.
const API_BASE = "https://jkoqttcselznnnuljfxf.supabase.co/functions/v1";
const ANON_KEY =
  "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Imprb3F0dGNzZWx6bm5udWxqZnhmIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTk1Mjk3MjQsImV4cCI6MjA3NTEwNTcyNH0.VB95wx8_iW71skpLwBdmxRvfBWcG4bXAQP0R92jkOLo";
const headers = { "Content-Type": "application/json", apikey: ANON_KEY };

const USER_TZ = Intl.DateTimeFormat().resolvedOptions().timeZone;

// ─── i18n ────────────────────────────────────────────────────────────
const DEMO_I18N = {
  en: {
    step1: {
      title: "Book a Demo",
      sub: "Tell us a bit about yourself and your company.",
      name: "Full Name",
      email: "Work Email",
      company: "Company",
      phone: "Phone Number",
      optional: "(optional)",
      next: "Next",
      errName: "Name is required.",
      errEmail: "Please enter a valid email.",
      errCompany: "Company name is required.",
    },
    step2: {
      title: "Pick a Date & Time",
      sub: "Weekdays, 10:00–17:00 Istanbul time. Shown in your local time.",
      book: "Book Demo",
      booking: "Booking…",
      loadFail: "Failed to fetch available slots.",
      conflict: "This time slot was just taken. Please pick another.",
      duplicate: "You already have an active demo booking.",
      genericFail: "Booking failed. Please try again.",
    },
    step3: {
      title: (name) => `Thank you, ${name}!`,
      sub: "Your demo is confirmed.",
      dateLabel: "Date & Time",
      emailLabel: "Confirmation Email",
      emailDesc: "Check your inbox for a confirmation with Google Calendar invite.",
      foot: "We'll send you a meeting link before the call. If you need to reschedule, just reply to the confirmation email.",
      done: "Done",
    },
    days: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
    locale: "en-US",
    close: "Close",
  },
  tr: {
    step1: {
      title: "Demo Ayarla",
      sub: "Kendin ve şirketin hakkında biraz bilgi ver.",
      name: "Ad Soyad",
      email: "İş E-postası",
      company: "Şirket",
      phone: "Telefon",
      optional: "(isteğe bağlı)",
      next: "İleri",
      errName: "İsim gerekli.",
      errEmail: "Geçerli bir e-posta gir.",
      errCompany: "Şirket adı gerekli.",
    },
    step2: {
      title: "Tarih & Saat Seç",
      sub: "Hafta içi 10:00–17:00 İstanbul saati. Yerel saatinde gösterilir.",
      book: "Demoyu Ayarla",
      booking: "Ayarlanıyor…",
      loadFail: "Uygun saatler yüklenemedi.",
      conflict: "Bu saat az önce başkası tarafından alındı. Başka bir saat seç.",
      duplicate: "Zaten aktif bir demo randevun var.",
      genericFail: "Randevu oluşturulamadı. Tekrar dene.",
    },
    step3: {
      title: (name) => `Teşekkürler, ${name}!`,
      sub: "Demo randevun onaylandı.",
      dateLabel: "Tarih & Saat",
      emailLabel: "Onay E-postası",
      emailDesc: "Google Calendar davetli onay e-postası için gelen kutunu kontrol et.",
      foot: "Görüşmeden önce sana bir toplantı linki göndereceğiz. Saati değiştirmek istersen onay e-postasını yanıtlaman yeterli.",
      done: "Tamam",
    },
    days: ["Paz", "Pzt", "Sal", "Çar", "Per", "Cum", "Cmt"],
    locale: "tr-TR",
    close: "Kapat",
  },
};

// ─── Date helpers ────────────────────────────────────────────────────
function formatDateHeader(date, locale) {
  return date.toLocaleDateString(locale, {
    weekday: "long",
    month: "long",
    day: "numeric",
  });
}
function formatTimeSlot(isoString, locale) {
  return new Date(isoString).toLocaleTimeString(locale, {
    hour: "numeric",
    minute: "2-digit",
    timeZone: USER_TZ,
  });
}
function formatConfirmation(isoString, locale) {
  return new Date(isoString).toLocaleString(locale, {
    weekday: "long",
    month: "long",
    day: "numeric",
    hour: "numeric",
    minute: "2-digit",
    timeZone: USER_TZ,
    timeZoneName: "short",
  });
}
function isSameDay(a, b) {
  return (
    a.getFullYear() === b.getFullYear() &&
    a.getMonth() === b.getMonth() &&
    a.getDate() === b.getDate()
  );
}
function groupSlotsByDate(slots) {
  const map = new Map();
  for (const iso of slots) {
    const d = new Date(iso);
    const key = new Date(d.toLocaleString("en-US", { timeZone: USER_TZ }));
    const dayKey = `${key.getFullYear()}-${key.getMonth()}-${key.getDate()}`;
    if (!map.has(dayKey)) map.set(dayKey, { date: key, slots: [] });
    map.get(dayKey).slots.push(iso);
  }
  return map;
}
function buildCalendarGrid(year, month) {
  const firstDay = new Date(year, month, 1).getDay();
  const daysInMonth = new Date(year, month + 1, 0).getDate();
  const grid = [];
  for (let i = 0; i < firstDay; i++) grid.push(null);
  for (let d = 1; d <= daysInMonth; d++) grid.push(new Date(year, month, d));
  return grid;
}

// ─── Inline icons (replaces lucide-react) ────────────────────────────
function IconX(p) {
  return (
    <svg
      {...p}
      width="18"
      height="18"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
    >
      <line x1="18" y1="6" x2="6" y2="18" />
      <line x1="6" y1="6" x2="18" y2="18" />
    </svg>
  );
}
function IconChevronLeft(p) {
  return (
    <svg
      {...p}
      width="18"
      height="18"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
    >
      <polyline points="15 18 9 12 15 6" />
    </svg>
  );
}
function IconChevronRight(p) {
  return (
    <svg
      {...p}
      width="18"
      height="18"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
    >
      <polyline points="9 18 15 12 9 6" />
    </svg>
  );
}
function IconLoader() {
  return (
    <svg
      className="dm-spin"
      width="18"
      height="18"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
    >
      <line x1="12" y1="2" x2="12" y2="6" />
      <line x1="12" y1="18" x2="12" y2="22" />
      <line x1="4.93" y1="4.93" x2="7.76" y2="7.76" />
      <line x1="16.24" y1="16.24" x2="19.07" y2="19.07" />
      <line x1="2" y1="12" x2="6" y2="12" />
      <line x1="18" y1="12" x2="22" y2="12" />
      <line x1="4.93" y1="19.07" x2="7.76" y2="16.24" />
      <line x1="16.24" y1="7.76" x2="19.07" y2="4.93" />
    </svg>
  );
}
function IconCheckCircle() {
  return (
    <svg
      width="32"
      height="32"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
    >
      <path d="M22 11.08V12a10 10 0 1 1-5.93-9.14" />
      <polyline points="22 4 12 14.01 9 11.01" />
    </svg>
  );
}
function IconMail() {
  return (
    <svg
      width="16"
      height="16"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
    >
      <path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z" />
      <polyline points="22,6 12,13 2,6" />
    </svg>
  );
}
function IconCalendar() {
  return (
    <svg
      width="16"
      height="16"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
    >
      <rect x="3" y="4" width="18" height="18" rx="2" ry="2" />
      <line x1="16" y1="2" x2="16" y2="6" />
      <line x1="8" y1="2" x2="8" y2="6" />
      <line x1="3" y1="10" x2="21" y2="10" />
    </svg>
  );
}

// ─── Analytics shims (gtag + fbq are global from the page <head>) ────
function safeGtag() {
  if (typeof window !== "undefined" && typeof window.gtag === "function") {
    window.gtag.apply(null, arguments);
  }
}
function safeFbq() {
  if (typeof window !== "undefined" && typeof window.fbq === "function") {
    window.fbq.apply(null, arguments);
  }
}
function extractDomain(company = "") {
  const trimmed = company.trim().toLowerCase();
  const match = trimmed.match(/[a-z0-9-]+\.[a-z]{2,}/);
  return match ? match[0] : "";
}
function trackDemoModalOpened(source) {
  safeGtag("event", "demo_modal_opened", { method: "modal", source });
}
function trackDemoModalDismissed(step) {
  safeGtag("event", "demo_modal_dismissed", { step });
}
function trackDemoStepUserInfo() {
  safeGtag("event", "demo_step_user_info");
}
function trackDemoStepSlotSelected() {
  safeGtag("event", "demo_step_slot_selected");
}
function trackBookingError(stage, status, message) {
  safeGtag("event", "demo_booking_error", { stage, status, message });
}
function trackBookADemo({ scheduledAt, company }) {
  safeGtag("event", "book_a_demo", {
    method: "modal",
    scheduled_at: scheduledAt,
    timezone: USER_TZ,
    company_domain: extractDomain(company),
  });
  safeFbq("track", "Lead", {
    content_name: "book_a_demo",
    content_category: "demo_booking",
  });
}

// ─── Step 1 ──────────────────────────────────────────────────────────
function StepUserInfo({ form, setField, onNext, t }) {
  const [error, setError] = useState("");
  const handleNext = () => {
    if (!form.name.trim()) return setError(t.step1.errName);
    if (!form.email.trim() || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email))
      return setError(t.step1.errEmail);
    if (!form.company.trim()) return setError(t.step1.errCompany);
    setError("");
    trackDemoStepUserInfo();
    onNext();
  };
  return (
    <div className="dm-stack">
      <div>
        <h3 className="dm-h">{t.step1.title}</h3>
        <p className="dm-sub">{t.step1.sub}</p>
      </div>
      <div className="dm-fields">
        <Field
          label={t.step1.name}
          required
          value={form.name}
          onChange={(v) => setField("name", v)}
          placeholder="John Doe"
        />
        <Field
          label={t.step1.email}
          required
          type="email"
          value={form.email}
          onChange={(v) => setField("email", v)}
          placeholder="you@company.com"
        />
        <Field
          label={t.step1.company}
          required
          value={form.company}
          onChange={(v) => setField("company", v)}
          placeholder="Acme Inc."
        />
        <Field
          label={t.step1.phone}
          optional
          optionalLabel={t.step1.optional}
          type="tel"
          value={form.phone}
          onChange={(v) => setField("phone", v)}
          placeholder="+1 (555) 000-0000"
        />
      </div>
      {error && <p className="dm-err">{error}</p>}
      <button onClick={handleNext} className="dm-cta">
        {t.step1.next}
      </button>
    </div>
  );
}

function Field({
  label,
  required,
  optional,
  optionalLabel,
  type = "text",
  value,
  onChange,
  placeholder,
}) {
  return (
    <div className="dm-field">
      <label className="dm-label">
        {label}
        {required && <span className="dm-req"> *</span>}
        {optional && <span className="dm-opt"> {optionalLabel}</span>}
      </label>
      <input
        type={type}
        value={value}
        onChange={(e) => onChange(e.target.value)}
        placeholder={placeholder}
        className="dm-input"
      />
    </div>
  );
}

// ─── Step 2 ──────────────────────────────────────────────────────────
function StepDatePicker({ onBack, onBook, slots, slotsLoading, slotsError, t }) {
  const today = new Date();
  const [viewMonth, setViewMonth] = useState(today.getMonth());
  const [viewYear, setViewYear] = useState(today.getFullYear());
  const [selectedDate, setSelectedDate] = useState(null);
  const [selectedSlot, setSelectedSlot] = useState(null);
  const [booking, setBooking] = useState(false);
  const [bookError, setBookError] = useState("");

  const grouped = groupSlotsByDate(slots);
  const grid = buildCalendarGrid(viewYear, viewMonth);

  const hasSlots = (date) => {
    if (!date) return false;
    const key = `${date.getFullYear()}-${date.getMonth()}-${date.getDate()}`;
    return grouped.has(key);
  };
  const getSlotsForDate = (date) => {
    if (!date) return [];
    const key = `${date.getFullYear()}-${date.getMonth()}-${date.getDate()}`;
    return grouped.get(key)?.slots || [];
  };

  const prevMonth = () => {
    if (viewMonth === 0) {
      setViewMonth(11);
      setViewYear(viewYear - 1);
    } else setViewMonth(viewMonth - 1);
  };
  const nextMonth = () => {
    if (viewMonth === 11) {
      setViewMonth(0);
      setViewYear(viewYear + 1);
    } else setViewMonth(viewMonth + 1);
  };

  const handleBook = async () => {
    if (!selectedSlot) return;
    setBooking(true);
    setBookError("");
    trackDemoStepSlotSelected();
    try {
      await onBook(selectedSlot);
    } catch (err) {
      setBookError(err.message);
      setBooking(false);
    }
  };

  const monthLabel = new Date(viewYear, viewMonth).toLocaleDateString(t.locale, {
    month: "long",
    year: "numeric",
  });

  return (
    <div className="dm-stack">
      <div className="dm-step2-head">
        <button className="dm-back" onClick={onBack} aria-label="Back">
          <IconChevronLeft />
        </button>
        <div>
          <h3 className="dm-h">{t.step2.title}</h3>
          <p className="dm-sub">{t.step2.sub}</p>
        </div>
      </div>
      {slotsLoading ? (
        <div className="dm-loading">
          <IconLoader />
        </div>
      ) : slotsError ? (
        <p className="dm-err dm-err-center">{slotsError}</p>
      ) : (
        <>
          <div>
            <div className="dm-month-row">
              <button onClick={prevMonth} aria-label="Previous month" className="dm-iconbtn">
                <IconChevronLeft />
              </button>
              <span className="dm-month-label">{monthLabel}</span>
              <button onClick={nextMonth} aria-label="Next month" className="dm-iconbtn">
                <IconChevronRight />
              </button>
            </div>
            <div className="dm-day-row">
              {t.days.map((d) => (
                <div key={d} className="dm-day-name">
                  {d}
                </div>
              ))}
            </div>
            <div className="dm-day-grid">
              {grid.map((date, i) => {
                if (!date) return <div key={`b-${i}`} />;
                const available = hasSlots(date);
                const isSelected = selectedDate && isSameDay(date, selectedDate);
                const isPast =
                  date < new Date(today.getFullYear(), today.getMonth(), today.getDate());
                const isWeekend = date.getDay() === 0 || date.getDay() === 6;
                const disabled = !available || isPast || isWeekend;
                return (
                  <button
                    key={date.toISOString()}
                    disabled={disabled}
                    onClick={() => {
                      setSelectedDate(date);
                      setSelectedSlot(null);
                      setBookError("");
                    }}
                    className={`dm-day ${isSelected ? "is-sel" : ""} ${disabled ? "is-disabled" : ""}`}
                  >
                    {date.getDate()}
                  </button>
                );
              })}
            </div>
          </div>
          {selectedDate && (
            <div>
              <p className="dm-date-header">{formatDateHeader(selectedDate, t.locale)}</p>
              <div className="dm-slots">
                {getSlotsForDate(selectedDate).map((iso) => (
                  <button
                    key={iso}
                    onClick={() => {
                      setSelectedSlot(iso);
                      setBookError("");
                    }}
                    className={`dm-slot ${selectedSlot === iso ? "is-sel" : ""}`}
                  >
                    {formatTimeSlot(iso, t.locale)}
                  </button>
                ))}
              </div>
            </div>
          )}
          {bookError && <p className="dm-err">{bookError}</p>}
          <button onClick={handleBook} disabled={!selectedSlot || booking} className="dm-cta">
            {booking && (
              <span className="dm-cta-spin">
                <IconLoader />
              </span>
            )}
            {booking ? t.step2.booking : t.step2.book}
          </button>
        </>
      )}
    </div>
  );
}

// ─── Step 3 ──────────────────────────────────────────────────────────
function StepConfirmation({ bookedSlot, userName, onClose, t }) {
  return (
    <div className="dm-confirm">
      <div className="dm-check">
        <IconCheckCircle />
      </div>
      <div>
        <h3 className="dm-h dm-h-lg">{t.step3.title(userName.split(" ")[0])}</h3>
        <p className="dm-sub">{t.step3.sub}</p>
      </div>
      <div className="dm-card">
        <div className="dm-card-row">
          <span className="dm-card-icon">
            <IconCalendar />
          </span>
          <div>
            <p className="dm-card-l">{t.step3.dateLabel}</p>
            <p className="dm-card-v">{formatConfirmation(bookedSlot, t.locale)}</p>
          </div>
        </div>
        <div className="dm-card-row">
          <span className="dm-card-icon">
            <IconMail />
          </span>
          <div>
            <p className="dm-card-l">{t.step3.emailLabel}</p>
            <p className="dm-card-d">{t.step3.emailDesc}</p>
          </div>
        </div>
      </div>
      <p className="dm-foot">{t.step3.foot}</p>
      <button onClick={onClose} className="dm-cta">
        {t.step3.done}
      </button>
    </div>
  );
}

// ─── Modal shell ─────────────────────────────────────────────────────
function DemoBookingModal({ open, onClose, source, lang = "en" }) {
  const t = DEMO_I18N[lang] || DEMO_I18N.en;
  const [step, setStep] = useState(1);
  const [form, setForm] = useState({
    name: "",
    email: "",
    company: "",
    phone: "",
  });
  const [slots, setSlots] = useState([]);
  const [slotsLoading, setSlotsLoading] = useState(false);
  const [slotsError, setSlotsError] = useState("");
  const [bookedSlot, setBookedSlot] = useState(null);

  const setField = (key, value) => setForm((prev) => ({ ...prev, [key]: value }));

  const reset = useCallback(() => {
    setStep(1);
    setForm({ name: "", email: "", company: "", phone: "" });
    setSlots([]);
    setSlotsLoading(false);
    setSlotsError("");
    setBookedSlot(null);
  }, []);

  const handleClose = () => {
    if (step !== 3) trackDemoModalDismissed(step);
    onClose();
    setTimeout(reset, 200);
  };

  // Fetch slots when entering step 2
  useEffect(() => {
    if (!open || step !== 2) return;
    let cancelled = false;
    setSlotsLoading(true);
    setSlotsError("");
    fetch(`${API_BASE}/available-slots?days=30`, { headers })
      .then((r) => {
        if (!r.ok) throw new Error(t.step2.loadFail);
        return r.json();
      })
      .then((data) => {
        if (!cancelled) setSlots(data.slots || []);
      })
      .catch((err) => {
        if (!cancelled) setSlotsError(err.message || t.step2.loadFail);
      })
      .finally(() => {
        if (!cancelled) setSlotsLoading(false);
      });
    return () => {
      cancelled = true;
    };
  }, [step, open]);

  // Body scroll lock
  useEffect(() => {
    if (open) document.body.style.overflow = "hidden";
    else document.body.style.overflow = "";
    return () => {
      document.body.style.overflow = "";
    };
  }, [open]);

  // ESC to close
  useEffect(() => {
    if (!open) return;
    const onKey = (e) => {
      if (e.key === "Escape") handleClose();
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open, step]);

  // Track open
  useEffect(() => {
    if (open) trackDemoModalOpened(source);
  }, [open, source]);

  const handleBook = async (slotIso) => {
    const res = await fetch(`${API_BASE}/book-demo`, {
      method: "POST",
      headers,
      body: JSON.stringify({
        email: form.email.trim(),
        name: form.name.trim(),
        scheduled_at: slotIso,
        timezone: USER_TZ,
        phone: form.phone.trim() || undefined,
        company: form.company.trim() || undefined,
      }),
    });
    if (!res.ok) {
      const body = await res.json().catch(() => ({}));
      trackBookingError("submit", res.status, body.error || `HTTP ${res.status}`);
      if (res.status === 409) {
        const msg = (body.error || "").toLowerCase();
        if (msg.includes("email") || msg.includes("duplicate")) throw new Error(t.step2.duplicate);
        throw new Error(t.step2.conflict);
      }
      throw new Error(body.error || t.step2.genericFail);
    }
    setBookedSlot(slotIso);
    trackBookADemo({ scheduledAt: slotIso, company: form.company });
    setStep(3);
  };

  if (!open) return null;

  return (
    <div className="dm-root" role="dialog" aria-modal="true">
      <div className="dm-backdrop" onClick={handleClose} />
      <div className="dm-dialog" onClick={(e) => e.stopPropagation()}>
        <button className="dm-close" onClick={handleClose} aria-label={t.close}>
          <IconX />
        </button>
        <div className="dm-steps">
          {[1, 2, 3].map((s) => (
            <div key={s} className={`dm-step ${s <= step ? "is-active" : ""}`} />
          ))}
        </div>
        {step === 1 && (
          <StepUserInfo form={form} setField={setField} onNext={() => setStep(2)} t={t} />
        )}
        {step === 2 && (
          <StepDatePicker
            onBack={() => setStep(1)}
            onBook={handleBook}
            slots={slots}
            slotsLoading={slotsLoading}
            slotsError={slotsError}
            t={t}
          />
        )}
        {step === 3 && (
          <StepConfirmation
            bookedSlot={bookedSlot}
            userName={form.name}
            onClose={handleClose}
            t={t}
          />
        )}
      </div>
    </div>
  );
}

Object.assign(window, { DemoBookingModal });
