/* Alpago — shared UI components */
/* All shared globals exported at the bottom */

const { useState, useEffect, useRef, useMemo } = React;

const PROJECTS = window.AlpagoData.projects;
const I18N = window.AlpagoData.i18n;
const LEADERS = window.AlpagoData.leaders;
const VALUES_DATA = window.AlpagoData.values;
const PARTNERS = window.AlpagoData.partners;
const AWARDS = window.AlpagoData.awards;

function useT(lang) { return I18N[lang]; }

// ---- Logo ----
function Wordmark({ light, size = 1 }) {
  const color = light ? "#FFFDF8" : "#101013";
  const accent = light ? "rgba(255,253,248,.7)" : "#9C7F4E";
  return (
    <svg viewBox="0 0 360 64" width={360 * size} height={64 * size} aria-label="Alpago Properties" style={{ display: "block" }}>
      <text x="0" y="34" fontFamily="'Cormorant Garamond', serif" fontSize="40" fontWeight="500" letterSpacing="6" fill={color}>ALPAGO</text>
      <text x="2" y="56" fontFamily="'Inter', sans-serif" fontSize="11" fontWeight="400" letterSpacing="7.5" fill={accent}>P R O P E R T I E S</text>
    </svg>
  );
}

// ---- Nav ----
function Nav({ route, setRoute, lang, setLang, onCta, transparent, withFlag }) {
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 60);
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  const t = useT(lang);
  const solid = !transparent || scrolled;
  return (
    <nav className={`nav ${solid ? "solid" : "transparent"} ${withFlag ? "with-flag" : ""}`}>
      <div className="container nav-inner">
        <button onClick={() => setRoute({ name: "home" })} aria-label="Alpago — Home" style={{ display: "flex", alignItems: "center" }}>
          <span style={{ transform: "scale(.6)", transformOrigin: lang === "ar" ? "right center" : "left center" }}>
            <Wordmark light={!solid} />
          </span>
        </button>
        <div className="nav-links" role="navigation">
          <button className={route.name === "home" ? "active" : ""} onClick={() => setRoute({ name: "home" })}>{t.nav.home}</button>
          <button className={route.name === "projects" || route.name === "project" ? "active" : ""} onClick={() => setRoute({ name: "projects" })}>{t.nav.projects}</button>
          <button className={route.name === "about" ? "active" : ""} onClick={() => setRoute({ name: "about" })}>{t.nav.about}</button>
          <button className={route.name === "contact" ? "active" : ""} onClick={() => setRoute({ name: "contact" })}>{t.nav.contact}</button>
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 28 }}>
          <div className="lang-switch">
            <button className={lang === "en" ? "active" : ""} onClick={() => setLang("en")}>EN</button>
            <span className="sep">/</span>
            <button className={lang === "ar" ? "active" : ""} onClick={() => setLang("ar")}>AR</button>
            <span className="sep" style={{ marginInline: 6, opacity: .25 }}>·</span>
            <button onClick={() => setLang("ru")} style={{ opacity: .35 }}>RU</button>
            <span className="sep">/</span>
            <button onClick={() => setLang("zh")} style={{ opacity: .35 }}>中</button>
          </div>
          <button className="nav-cta" onClick={onCta}>
            <span>{t.nav.cta}</span>
            <span className="arrow">→</span>
          </button>
        </div>
      </div>
    </nav>
  );
}

// ---- Footer ----
function Footer({ lang, setRoute, onCta }) {
  const t = useT(lang);
  return (
    <footer className="footer">
      <div className="container">
        <div className="footer-grid">
          <div>
            <div style={{ marginBottom: 20 }}><Wordmark light /></div>
            <p className="tagline">{t.footer.tagline}</p>
            <button className="btn ghost-light" onClick={onCta} style={{ marginTop: 8 }}>
              {t.nav.cta} <span className="arrow">→</span>
            </button>
          </div>
          <div>
            <h4>{t.footer.projects_h}</h4>
            <ul>
              {PROJECTS.slice(0, 5).map(p => (
                <li key={p.slug}><button onClick={() => setRoute({ name: "project", slug: p.slug })}>{p.name}</button></li>
              ))}
            </ul>
          </div>
          <div>
            <h4>{t.footer.explore}</h4>
            <ul>
              <li><button onClick={() => setRoute({ name: "projects" })}>{t.nav.projects}</button></li>
              <li><button onClick={() => setRoute({ name: "about" })}>{t.footer.about}</button></li>
              <li><button onClick={() => setRoute({ name: "contact" })}>{t.footer.contact_l}</button></li>
            </ul>
          </div>
          <div>
            <h4>{t.footer.contact_h}</h4>
            <ul>
              <li>+971 4 263 0022</li>
              <li>info@alpagoproperties.com</li>
              <li style={{ color: "rgba(255,255,255,.55)" }}>Office 2603, Boulevard Plaza Tower 1, Downtown Dubai</li>
              <li style={{ color: "rgba(255,255,255,.55)", fontSize: 12, marginTop: 8 }}>{t.footer.socials}</li>
            </ul>
          </div>
        </div>
        <div className="footer-bottom">
          <div>{t.footer.rights}</div>
          <div style={{ display: "flex", gap: 24 }}>
            <span>RERA · DLD compliant</span>
            <span>Privacy</span>
            <span>Terms</span>
          </div>
        </div>
      </div>
    </footer>
  );
}

// ---- Register Interest Modal ----
function RegisterModal({ open, onClose, lang, defaultProject }) {
  const t = useT(lang);
  const [tab, setTab] = useState(0);
  const [submitted, setSubmitted] = useState(false);
  const [form, setForm] = useState({
    first: "", last: "", email: "", phone: "", country: "",
    project: defaultProject || "palm-flower",
    interest: "Full-floor residence",
    budget: "", message: "", consent: false
  });
  useEffect(() => {
    if (open) {
      setSubmitted(false);
      setForm(f => ({ ...f, project: defaultProject || f.project }));
    }
  }, [open, defaultProject]);

  useEffect(() => {
    const onEsc = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onEsc);
    return () => window.removeEventListener("keydown", onEsc);
  }, [onClose]);

  const onSubmit = (e) => { e.preventDefault(); setSubmitted(true); };
  const tabKeys = ["interest","eoi","brochure","viewing"];
  const titlesByTab = lang === "ar"
    ? ["تسجيل اهتمام","عرض شراء","تنزيل الكتيب","حجز زيارة خاصة"]
    : ["Register interest","Expression of interest","Request the brochure","Book a private viewing"];

  const projectImg = PROJECTS.find(p => p.slug === form.project)?.cover || "media/asset-29.webp";

  return (
    <div className={`modal-backdrop ${open ? "open" : ""}`} onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        <div className="left" style={{ backgroundImage: `url(${projectImg})`, backgroundSize: "cover", backgroundPosition: "center" }}>
          <div style={{ position: "absolute", inset: 0, background: "linear-gradient(180deg, rgba(16,22,21,.6), rgba(16,22,21,.92))" }} />
          <div className="inner">
            <div className="eyebrow on-dark"><span className="dot" />{t.form.eyebrow}</div>
            <h3>{t.form.sub.split(".")[0]}.</h3>
            <p className="sub">{t.form.sub}</p>
          </div>
          <div className="meta">
            <div>+971 4 263 0022</div>
            <div>info@alpagoproperties.com</div>
            <div style={{ opacity: .65 }}>Boulevard Plaza Tower 1, Downtown Dubai</div>
          </div>
        </div>
        <div className="right">
          <button className="close" onClick={onClose} aria-label="Close">×</button>
          {!submitted ? (
            <form onSubmit={onSubmit}>
              <div className="form-eyebrow">{t.form.eyebrow}</div>
              <h2>{titlesByTab[tab]}</h2>
              <div className="tabs" role="tablist">
                {t.form.tabs.map((tt, i) => (
                  <button key={tabKeys[i]} type="button" className={tab === i ? "active" : ""} onClick={() => setTab(i)}>{tt}</button>
                ))}
              </div>
              <div className="row">
                <div className="field">
                  <label>{t.form.first}</label>
                  <input required value={form.first} onChange={(e) => setForm({ ...form, first: e.target.value })} />
                </div>
                <div className="field">
                  <label>{t.form.last}</label>
                  <input required value={form.last} onChange={(e) => setForm({ ...form, last: e.target.value })} />
                </div>
              </div>
              <div className="row">
                <div className="field">
                  <label>{t.form.email}</label>
                  <input type="email" required value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })} />
                </div>
                <div className="field">
                  <label>{t.form.phone}</label>
                  <input type="tel" value={form.phone} onChange={(e) => setForm({ ...form, phone: e.target.value })} />
                </div>
              </div>
              <div className="row">
                <div className="field">
                  <label>{t.form.country}</label>
                  <input value={form.country} onChange={(e) => setForm({ ...form, country: e.target.value })} placeholder="e.g. United Kingdom" />
                </div>
                <div className="field">
                  <label>{t.form.project}</label>
                  <select value={form.project} onChange={(e) => setForm({ ...form, project: e.target.value })}>
                    {PROJECTS.map(p => <option key={p.slug} value={p.slug}>{p.name}</option>)}
                  </select>
                </div>
              </div>
              {tab !== 2 && (
                <div className="field">
                  <label>{t.form.message}</label>
                  <textarea rows="2" value={form.message} onChange={(e) => setForm({ ...form, message: e.target.value })} />
                </div>
              )}
              <label className="checks">
                <input type="checkbox" required checked={form.consent} onChange={(e) => setForm({ ...form, consent: e.target.checked })} />
                <span>{t.form.consent}</span>
              </label>
              <button className="btn submit" type="submit">{t.form.submit} <span className="arrow">→</span></button>
            </form>
          ) : (
            <div className="success">
              <div className="check">✓</div>
              <h2 style={{ marginBottom: 8 }}>{t.form.success_t}</h2>
              <p style={{ color: "var(--muted)", maxWidth: 36 + "ch", margin: "0 auto" }}>{t.form.success_b}</p>
              <button className="btn ghost" onClick={onClose} style={{ marginTop: 28 }}>Close</button>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

// ---- WhatsApp FAB ----
function WhatsAppFab({ onClick }) {
  return (
    <button className="wa-fab" onClick={onClick} title="WhatsApp" aria-label="WhatsApp">
      <svg width="22" height="22" viewBox="0 0 24 24" fill="currentColor">
        <path d="M19.05 4.91A10 10 0 0 0 4.42 18.6L3 22l3.5-.92A10 10 0 1 0 19.05 4.91Zm-7.05 15.2a8.2 8.2 0 0 1-4.15-1.13l-.3-.18-2.07.55.55-2.02-.2-.31a8.18 8.18 0 1 1 6.17 3.09Zm4.5-6.13c-.25-.13-1.47-.73-1.7-.81-.23-.08-.4-.13-.56.13-.17.25-.65.81-.8.97-.15.17-.3.19-.55.06-.25-.13-1.05-.39-2-1.24-.74-.66-1.24-1.46-1.38-1.71-.15-.25-.02-.39.11-.51.12-.12.25-.3.38-.45.13-.15.17-.25.25-.42.08-.17.04-.31-.02-.45-.06-.13-.55-1.34-.76-1.83-.2-.48-.4-.41-.55-.42-.14-.01-.31-.01-.48-.01s-.42.06-.64.31c-.22.25-.85.83-.85 2.03 0 1.2.87 2.36.99 2.52.13.17 1.72 2.62 4.16 3.67.58.25 1.04.4 1.39.51.58.18 1.11.16 1.53.1.47-.07 1.47-.6 1.68-1.18.21-.58.21-1.08.15-1.18-.06-.1-.23-.16-.48-.29Z" />
      </svg>
    </button>
  );
}

// ---- Sticky bottom CTA ----
function StickyCta({ show, label, title, onPrimary, onSecondary, primaryLabel, secondaryLabel }) {
  return (
    <div className={`sticky-cta ${show ? "show" : ""}`}>
      <div className="info">
        <div className="label">{label}</div>
        <div className="title">{title}</div>
      </div>
      <div style={{ display: "flex", gap: 8 }}>
        {onSecondary && <button className="btn ghost-light" style={{ borderColor: "rgba(255,255,255,.4)", color: "#fff", padding: "12px 18px" }} onClick={onSecondary}>{secondaryLabel}</button>}
        <button className="btn" style={{ padding: "12px 18px" }} onClick={onPrimary}>{primaryLabel} <span className="arrow">→</span></button>
      </div>
    </div>
  );
}

// ---- Lightbox ----
function Lightbox({ images, open, index, setIndex, onClose }) {
  useEffect(() => {
    if (!open) return;
    const onKey = (e) => {
      if (e.key === "Escape") onClose();
      if (e.key === "ArrowRight") setIndex(i => (i + 1) % images.length);
      if (e.key === "ArrowLeft") setIndex(i => (i - 1 + images.length) % images.length);
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open, images.length, onClose, setIndex]);
  if (!images || images.length === 0) return null;
  return (
    <div className={`lightbox ${open ? "open" : ""}`} onClick={onClose}>
      <button className="close" onClick={onClose}>Close</button>
      <button className="nav-arrow prev" onClick={(e) => { e.stopPropagation(); setIndex((index - 1 + images.length) % images.length); }}>‹</button>
      <img src={images[index]} alt="" onClick={(e) => e.stopPropagation()} />
      <button className="nav-arrow next" onClick={(e) => { e.stopPropagation(); setIndex((index + 1) % images.length); }}>›</button>
    </div>
  );
}

// ---- Flag strip ----
function FlagStrip({ lang }) {
  const t = useT(lang);
  return (
    <div className="flag-strip">
      <strong>※</strong>&nbsp;&nbsp;{t.flag}
    </div>
  );
}

Object.assign(window, {
  React, Wordmark, Nav, Footer, RegisterModal, WhatsAppFab, StickyCta, Lightbox, FlagStrip,
  PROJECTS, I18N, LEADERS, VALUES_DATA, PARTNERS, AWARDS, useT
});
