/* Danube Properties — shared components: Navbar, FAB, Modal, Forms, Logo */

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

/* ─── Logo (red wordmark with diamond) ──────────────────── */
function DanubeLogo({ light, scale = 1 }) {
  const wordColor = light ? "#fff" : "#181C24";
  return (
    <svg viewBox="0 0 200 36" style={{ height: 28 * scale, width: "auto", display: "block" }}>
      <g>
        <path d="M4 12 L12 4 L20 12 L12 20 Z" fill="#ED1C24" />
        <text x="26" y="22" fontFamily="Manrope, sans-serif" fontWeight="800" fontSize="20"
          fontStyle="italic" letterSpacing="0.5" fill="#ED1C24">DANUBE</text>
        <text x="26" y="32" fontFamily="JetBrains Mono, monospace" fontWeight="500"
          fontSize="6.4" letterSpacing="2.6" fill={wordColor}>PROPERTIES</text>
      </g>
    </svg>
  );
}

/* ─── Navbar ───────────────────────────────────────────── */
function Navbar({ onNav, onCta, currentView, lang, setLang }) {
  const [scrolled, setScrolled] = useState(false);

  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 60 || currentView !== "home");
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, [currentView]);

  return (
    <nav className={"nav" + (scrolled ? " scrolled" : "")}>
      <div className="nav-logo" onClick={() => onNav("home")}>
        <DanubeLogo light={!scrolled} />
      </div>
      <div className="nav-links">
        <a className="nav-link" onClick={() => onNav("home", "projects")}>Projects</a>
        <a className="nav-link" onClick={() => onNav("home", "plan")}>1% Plan</a>
        <a className="nav-link" onClick={() => onNav("home", "about")}>About</a>
        <a className="nav-link" onClick={() => onNav("home", "contact")}>Contact</a>
      </div>
      <div className="nav-right">
        <div className="lang-toggle">
          {["EN", "AR", "RU", "ZH"].map((l) => (
            <button
              key={l}
              className={lang === l ? "active" : ""}
              onClick={() => setLang(l)}
            >{l}</button>
          ))}
        </div>
        <button className="btn btn-primary btn-sm" onClick={onCta}>
          Register interest
        </button>
      </div>
    </nav>
  );
}

/* ─── WhatsApp FAB ─────────────────────────────────────── */
function WhatsAppFAB() {
  return (
    <a className="fab" href="https://api.whatsapp.com/send?phone=9718005757&text=Hi%20Danube%20Properties%2C%20I%27d%20like%20to%20enquire%20about%20a%20launch."
       target="_blank" rel="noreferrer" aria-label="Chat on WhatsApp">
      <span className="fab-pulse"></span>
      <svg width="26" height="26" viewBox="0 0 24 24" fill="currentColor">
        <path d="M.057 24l1.687-6.163c-1.041-1.804-1.588-3.849-1.587-5.946.003-6.556 5.338-11.891 11.893-11.891 3.181.001 6.167 1.24 8.413 3.488 2.245 2.248 3.481 5.236 3.48 8.414-.003 6.557-5.338 11.892-11.893 11.892-1.99-.001-3.951-.5-5.688-1.448l-6.305 1.654zm6.597-3.807c1.676.995 3.276 1.591 5.392 1.592 5.448 0 9.886-4.434 9.889-9.885.002-5.462-4.415-9.89-9.881-9.892-5.452 0-9.887 4.434-9.889 9.884-.001 2.225.651 3.891 1.746 5.634l-.999 3.648 3.742-.981zm11.387-5.464c-.074-.124-.272-.198-.57-.347-.297-.149-1.758-.868-2.031-.967-.272-.099-.47-.149-.669.149-.198.297-.768.967-.941 1.165-.173.198-.347.223-.644.074-.297-.149-1.255-.462-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.297-.347.446-.521.151-.172.2-.296.3-.495.099-.198.05-.372-.025-.521-.075-.148-.669-1.611-.916-2.206-.242-.579-.487-.501-.669-.51l-.57-.01c-.198 0-.52.074-.792.372s-1.04 1.016-1.04 2.479 1.065 2.876 1.213 3.074c.149.198 2.095 3.2 5.076 4.487.709.306 1.263.489 1.694.626.712.226 1.36.194 1.872.118.571-.085 1.758-.719 2.006-1.413.248-.695.248-1.29.173-1.414z"/>
      </svg>
    </a>
  );
}

/* ─── Modal ────────────────────────────────────────────── */
function Modal({ children, onClose }) {
  useEffect(() => {
    document.body.style.overflow = "hidden";
    const esc = (e) => e.key === "Escape" && onClose();
    window.addEventListener("keydown", esc);
    return () => {
      document.body.style.overflow = "";
      window.removeEventListener("keydown", esc);
    };
  }, [onClose]);
  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        <button className="modal-close" onClick={onClose} aria-label="Close">×</button>
        {children}
      </div>
    </div>
  );
}

/* ─── Lead Capture Form (tri-tab: Interest / Brochure / Viewing) ──── */
function LeadForm({ defaultProject = "Any launch", defaultTab = "interest", compact = false }) {
  const [tab, setTab] = useState(defaultTab);
  const [form, setForm] = useState({
    name: "",
    email: "",
    countryCode: "+971",
    phone: "",
    project: defaultProject,
    budget: "",
    timeline: "",
    nationality: "",
    notes: "",
    consent: false,
  });
  const [errors, setErrors] = useState({});
  const [submitted, setSubmitted] = useState(false);
  const [submitting, setSubmitting] = useState(false);

  const set = (k, v) => setForm((f) => ({ ...f, [k]: v }));

  const validate = () => {
    const e = {};
    if (!form.name.trim()) e.name = "Required";
    if (!form.email.trim()) e.email = "Required";
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)) e.email = "Invalid email";
    if (!form.phone.trim()) e.phone = "Required";
    else if (!/^[\d\s-]{6,}$/.test(form.phone)) e.phone = "Invalid phone";
    if (!form.consent) e.consent = "Please consent";
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  const submit = (ev) => {
    ev.preventDefault();
    if (!validate()) return;
    setSubmitting(true);
    setTimeout(() => {
      setSubmitting(false);
      setSubmitted(true);
    }, 900);
  };

  const tabCopy = {
    interest: {
      title: <>Register your <em>interest</em></>,
      sub: "Direct from the developer. The 1% monthly plan, on enquiry.",
      cta: "Register interest",
    },
    brochure: {
      title: <>Download the <em>brochure</em></>,
      sub: "Renders, residences, amenity plates, and 1%-plan terms (sent by email).",
      cta: "Send me the brochure",
    },
    viewing: {
      title: <>Book a <em>private viewing</em></>,
      sub: "On-site at the sales gallery, or a private video walkthrough.",
      cta: "Book a viewing",
    },
  }[tab];

  if (submitted) {
    return (
      <div className="form-card">
        <div className="form-tabs">
          {["interest", "brochure", "viewing"].map((t) => (
            <button key={t} className={"form-tab" + (t === tab ? " active" : "")} disabled>
              {t === "interest" ? "Interest" : t === "brochure" ? "Brochure" : "Viewing"}
            </button>
          ))}
        </div>
        <div className="form-success">
          <div className="check">✓</div>
          <h4>Thank you, {form.name.split(" ")[0]}.</h4>
          <p style={{ marginTop: 12 }}>
            A senior sales consultant will reach out within 4 hours on <strong>{form.email}</strong>
            {" "}and <strong>{form.countryCode} {form.phone}</strong>.
          </p>
          <p style={{ marginTop: 16, fontSize: 12 }}>
            Reference: <span className="mono">DPR-{Math.floor(Math.random() * 90000 + 10000)}</span>
          </p>
          <button
            className="btn btn-ghost-dark"
            style={{ marginTop: 24 }}
            onClick={() => { setSubmitted(false); setForm((f) => ({ ...f, name: "", email: "", phone: "", notes: "" })); }}
          >Submit another enquiry</button>
        </div>
      </div>
    );
  }

  return (
    <div className="form-card">
      <div className="form-tabs">
        {[
          ["interest", "Interest"],
          ["brochure", "Brochure"],
          ["viewing", "Viewing"],
        ].map(([k, label]) => (
          <button key={k} className={"form-tab" + (k === tab ? " active" : "")} onClick={() => setTab(k)}>
            {label}
          </button>
        ))}
      </div>

      <h3 className="form-h3">{tabCopy.title}</h3>
      <p className="form-sub">{tabCopy.sub}</p>

      <form onSubmit={submit} noValidate>
        <div className="form-field">
          <label className="form-label">Full name</label>
          <input
            className={"form-input" + (errors.name ? " error" : "")}
            value={form.name} onChange={(e) => set("name", e.target.value)}
            placeholder="e.g. Adel Mohammed"
          />
          {errors.name && <div className="form-error">{errors.name}</div>}
        </div>

        <div className="form-2col">
          <div className="form-field">
            <label className="form-label">Email</label>
            <input
              type="email"
              className={"form-input" + (errors.email ? " error" : "")}
              value={form.email} onChange={(e) => set("email", e.target.value)}
              placeholder="you@email.com"
            />
            {errors.email && <div className="form-error">{errors.email}</div>}
          </div>

          <div className="form-field">
            <label className="form-label">Phone (with WhatsApp)</label>
            <div className="form-phone-row">
              <select className="form-select" value={form.countryCode} onChange={(e) => set("countryCode", e.target.value)}>
                <option>+971</option><option>+91</option><option>+86</option>
                <option>+44</option><option>+7</option><option>+966</option><option>+973</option>
              </select>
              <input
                className={"form-input" + (errors.phone ? " error" : "")}
                value={form.phone} onChange={(e) => set("phone", e.target.value)}
                placeholder="00 000 0000"
              />
            </div>
            {errors.phone && <div className="form-error">{errors.phone}</div>}
          </div>
        </div>

        {!compact && (
          <div className="form-2col">
            <div className="form-field">
              <label className="form-label">Project of interest</label>
              <select className="form-select" value={form.project} onChange={(e) => set("project", e.target.value)}>
                <option>Any launch</option>
                {window.DANUBE_DATA.PROJECTS.map((p) => (
                  <option key={p.slug}>{p.name} — {p.community}</option>
                ))}
              </select>
            </div>

            <div className="form-field">
              <label className="form-label">Buyer profile</label>
              <select className="form-select" value={form.timeline} onChange={(e) => set("timeline", e.target.value)}>
                <option value="">Select…</option>
                <option>End-user (own home)</option>
                <option>Investor (yield)</option>
                <option>Investor (capital growth)</option>
                <option>Broker enquiry</option>
              </select>
            </div>
          </div>
        )}

        {tab === "viewing" && (
          <div className="form-field">
            <label className="form-label">Preferred date / window</label>
            <input className="form-input" value={form.notes} onChange={(e) => set("notes", e.target.value)} placeholder="e.g. next Saturday afternoon, or video call" />
          </div>
        )}

        {tab === "interest" && !compact && (
          <div className="form-field">
            <label className="form-label">Notes (optional)</label>
            <textarea className="form-textarea" value={form.notes} onChange={(e) => set("notes", e.target.value)} placeholder="Anything specific — payment plan, unit type, handover, language preference." />
          </div>
        )}

        <label className="form-checkbox">
          <input type="checkbox" checked={form.consent} onChange={(e) => set("consent", e.target.checked)} />
          <span>
            I consent to Danube Properties contacting me about this enquiry by email, phone and WhatsApp. Plan terms (% / months / split) are confirmed per project on enquiry.
          </span>
        </label>
        {errors.consent && <div className="form-error" style={{ marginTop: -16, marginBottom: 12 }}>{errors.consent}</div>}

        <button type="submit" className="form-submit" disabled={submitting}>
          {submitting ? "Sending…" : tabCopy.cta} <span style={{ marginLeft: 8 }}>→</span>
        </button>

        <div className="form-divider">or</div>

        <a
          href="https://api.whatsapp.com/send?phone=9718005757"
          target="_blank" rel="noreferrer"
          className="form-whatsapp"
        >
          <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor">
            <path d="M.057 24l1.687-6.163c-1.041-1.804-1.588-3.849-1.587-5.946.003-6.556 5.338-11.891 11.893-11.891 3.181.001 6.167 1.24 8.413 3.488 2.245 2.248 3.481 5.236 3.48 8.414-.003 6.557-5.338 11.892-11.893 11.892-1.99-.001-3.951-.5-5.688-1.448l-6.305 1.654zm6.597-3.807c1.676.995 3.276 1.591 5.392 1.592 5.448 0 9.886-4.434 9.889-9.885.002-5.462-4.415-9.89-9.881-9.892-5.452 0-9.887 4.434-9.889 9.884-.001 2.225.651 3.891 1.746 5.634l-.999 3.648 3.742-.981z"/>
          </svg>
          Chat on WhatsApp — +971 800 5757
        </a>
      </form>
    </div>
  );
}

/* ─── Partner band (marquee) ─────────────────────── */
function PartnerBand() {
  const items = [
    "RERA / DLD Registered Developer*",
    "Direct from the developer",
    "1% monthly · 0% interest",
    "Up to 80 months payment plan",
    "Sold across UAE · India · China · UK",
    "Part of the Danube Group, since 1993",
  ];
  return (
    <div className="partner-band">
      <div className="partner-track">
        {[...items, ...items].map((t, i) => (
          <span key={i} className="partner-item">{t}</span>
        ))}
      </div>
    </div>
  );
}

window.DanubeComponents = { DanubeLogo, Navbar, WhatsAppFAB, Modal, LeadForm, PartnerBand };
