const { useState, useEffect, useRef } = React;

/* =================== NAV =================== */
function Nav() {
  const [open, setOpen] = useState(false);
  const [pinned, setPinned] = useState(false);
  const [mobileOpen, setMobileOpen] = useState(false);
  const closeTimer = useRef(null);
  const menuRef = useRef(null);

  useEffect(() => {
    const handler = (e) => {
      if (menuRef.current && !menuRef.current.contains(e.target)) {
        setPinned(false);
        setOpen(false);
      }
    };
    document.addEventListener('mousedown', handler);
    return () => document.removeEventListener('mousedown', handler);
  }, []);

  const onEnter = () => {clearTimeout(closeTimer.current);setOpen(true);};
  const onLeave = () => {if (!pinned) closeTimer.current = setTimeout(() => setOpen(false), 200);};
  const onClick = () => {const next = !pinned;setPinned(next);setOpen(next);};

  return (
    <header className="nav">
      <a className="brand" href="index.html" aria-label="Quantum Design home">
        <img src="assets/qd-logo.png" alt="Quantum Design" />
      </a>
      <nav className="nav-links">
        <a href="index.html">Home</a>
        <a href="about.html">About</a>
        <div ref={menuRef} className={"has-menu" + (open ? " open" : "")} onMouseEnter={onEnter} onMouseLeave={onLeave}>
          <button className="menu-trigger" onClick={onClick}>
            Services
            <svg width="10" height="10" viewBox="0 0 10 10"><path d="M1 3.5L5 7.5L9 3.5" stroke="currentColor" strokeWidth="1.5" fill="none" strokeLinecap="round" /></svg>
          </button>
          <div className="menu">
            <a href="web-design.html">
              <div className="menu-icon" style={{ background: "var(--accent)" }}>
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="4" width="18" height="14" rx="2" /><path d="M3 10h18" /></svg>
              </div>
              <div>
                <div className="menu-title">Web Design</div>
                <div className="menu-sub">Custom builds that convert</div>
              </div>
            </a>
            <a href="marketing.html">
              <div className="menu-icon" style={{ backgroundColor: "rgb(184, 225, 246)" }}>
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M3 17l6-6 4 4 8-8" /><path d="M21 7v5h-5" /></svg>
              </div>
              <div>
                <div className="menu-title">Marketing &amp; SEO</div>
                <div className="menu-sub">Google + Meta ads, SEO</div>
              </div>
            </a>
            <div className="menu-foot">
              <a href="index.html#pricing" className="menu-foot-link">See packages &amp; pricing →</a>
            </div>
          </div>
        </div>
        <a href="portfolio.html">Portfolio</a>
        <a href="#" className="active">Contact</a>
      </nav>
      <a href="mailto:quantumdesignnz@gmail.com" className="nav-icon-btn" aria-label="Email us">
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
          <rect x="3" y="5" width="18" height="14" rx="2" />
          <path d="M3 7l9 6 9-6" />
        </svg>
      </a>
      <MobileNavToggle onClick={() => setMobileOpen(true)} />
      <MobileNavMenu open={mobileOpen} onClose={() => setMobileOpen(false)} active="contact" />
    </header>);
}



/* =================== MAIN CONTACT =================== */
function ContactSection() {
  const [services, setServices] = useState([]);
  const [honey, setHoney] = useState("");
  const [sent, setSent] = useState(false);
  const [sending, setSending] = useState(false);
  const [error, setError] = useState("");
  const [form, setForm] = useState({ name: "", email: "", business: "", website: "", message: "" });

  // Where enquiries are delivered. FormSubmit forwards to this inbox — no backend needed.
  // First-ever submission triggers a one-time confirmation email to activate the address.
  const FORM_ENDPOINT = "https://formsubmit.co/ajax/quantumdesignnz@gmail.com";

  const SERVICES = ["Website", "Marketing & SEO"];

  const toggleService = (s) => {
    setServices((prev) => prev.includes(s) ? prev.filter((x) => x !== s) : [...prev, s]);
  };

  const update = (k) => (e) => setForm((f) => ({ ...f, [k]: e.target.value }));

  const onSubmit = async (e) => {
    e.preventDefault();
    if (sending) return;
    setError("");
    setSending(true);
    try {
      const res = await fetch(FORM_ENDPOINT, {
        method: "POST",
        headers: { "Content-Type": "application/json", "Accept": "application/json" },
        body: JSON.stringify({
          _honey: honey,
          name: form.name,
          email: form.email,
          business: form.business,
          website: form.website,
          services: services.join(", "),
          message: form.message,
          _subject: `New enquiry from ${form.name || "website"}`,
          _template: "table"
        })
      });
      if (!res.ok) throw new Error("Bad response");
      setSent(true);
      window.scrollTo({ top: 0, behavior: "smooth" });
    } catch (err) {
      setError("Something went wrong sending your message. Please email us directly at quantumdesignnz@gmail.com.");
    } finally {
      setSending(false);
    }
  };

  return (
    <section className="ct-main">
      <div className="ct-inner">
        {/* Left side */}
        <div className="ct-left">
          <div className="ct-eyebrow"><span className="ct-eyebrow-dot"></span> Let's talk</div>
          <h1 className="ct-h1">
            Got a project in mind? <em>Just say hello.</em>
          </h1>
          <p className="ct-sub">

          </p>

          <div className="ct-channels">
            <a className="ct-channel" href="mailto:quantumdesignnz@gmail.com">
              <div className="ct-channel-icon">
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="5" width="18" height="14" rx="2" /><path d="M3 7l9 6 9-6" /></svg>
              </div>
              <div>
                <div className="ct-channel-label">Email</div>
                <div className="ct-channel-value">quantumdesignnz@gmail.com</div>
              </div>
            </a>
            <a className="ct-channel" href="https://www.instagram.com/quantumdesign.co.nz" target="_blank" rel="noopener noreferrer">
              <div className="ct-channel-icon">
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="2" y="2" width="20" height="20" rx="5" /><path d="M16 11.37A4 4 0 1 1 12.63 8 4 4 0 0 1 16 11.37z" /><line x1="17.5" y1="6.5" x2="17.51" y2="6.5" /></svg>
              </div>
              <div>
                <div className="ct-channel-label">Instagram</div>
                <div className="ct-channel-value">@quantumdesign.co.nz</div>
              </div>
            </a>
            <a className="ct-channel" href="https://www.facebook.com/quantumdesignnz" target="_blank" rel="noopener noreferrer">
              <div className="ct-channel-icon">
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M18 2h-3a5 5 0 0 0-5 5v3H7v4h3v8h4v-8h3l1-4h-4V7a1 1 0 0 1 1-1h3z" /></svg>
              </div>
              <div>
                <div className="ct-channel-label">Facebook</div>
                <div className="ct-channel-value">/quantumdesignnz</div>
              </div>
            </a>
          </div>
        </div>

        {/* Right side: form */}
        <div className="ct-form-wrap">
          <span className="ct-form-shimmer" aria-hidden="true"></span>
          {sent ?
          <div className="ct-success">
              <div className="ct-success-icon">
                <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><polyline points="5 12 10 17 19 7" /></svg>
              </div>
              <h3>Thanks — message received.</h3>
              <p>We'll be back to you within 48 hours, usually a lot sooner.<br />If it's urgent, email us directly at <strong>quantumdesignnz@gmail.com</strong>.</p>
            </div> :

          <form onSubmit={onSubmit}>
              <input type="text" name="_honey" value={honey} onChange={(e) => setHoney(e.target.value)} tabIndex="-1" autoComplete="off" aria-hidden="true" style={{ position: "absolute", left: "-9999px", width: "1px", height: "1px", opacity: 0 }}></input>
              <h2 className="ct-form-title">Tell us about your project</h2>
              <p className="ct-form-note">All fields optional except the ones marked. We read every one.</p>

              <div className="ct-row">
                <div className="ct-field">
                  <label className="ct-label" htmlFor="ct-name">Your name *</label>
                  <input className="ct-input" id="ct-name" required value={form.name} onChange={update("name")} placeholder="Sam Whittaker" />
                </div>
                <div className="ct-field">
                  <label className="ct-label" htmlFor="ct-email">Email *</label>
                  <input className="ct-input" id="ct-email" type="email" required value={form.email} onChange={update("email")} placeholder="sam@business.co.nz" />
                </div>
              </div>

              <div className="ct-row">
                <div className="ct-field">
                  <label className="ct-label" htmlFor="ct-business">Business name</label>
                  <input className="ct-input" id="ct-business" value={form.business} onChange={update("business")} placeholder="Quantum Industries Ltd" />
                </div>
                <div className="ct-field">
                  <label className="ct-label" htmlFor="ct-website">Current website</label>
                  <input className="ct-input" id="ct-website" value={form.website} onChange={update("website")} placeholder="example.co.nz (or none)" />
                </div>
              </div>

              <div className="ct-field">
                <span className="ct-label">What do you need?</span>
                <div className="ct-tags">
                  {SERVICES.map((s) =>
                <button
                  type="button"
                  key={s}
                  className={"ct-tag" + (services.includes(s) ? " active" : "")}
                  onClick={() => toggleService(s)}>
                      {s}
                    </button>
                )}
                </div>
              </div>

              <div className="ct-field">
                <label className="ct-label" htmlFor="ct-msg">Tell us about your project *</label>
                <textarea className="ct-textarea" id="ct-msg" required value={form.message} onChange={update("message")} placeholder="What are you building, who's it for, and what's not working yet?" />
              </div>

              <div className="ct-foot">
                <div className="ct-privacy">
                  We'll only use this to reply. No marketing emails.
                </div>
                <button className="ct-submit" type="submit" disabled={sending}>
                  {sending ? "Sending\u2026" : <React.Fragment>Send message <span className="ct-submit-arrow">↗</span></React.Fragment>}
                </button>
              </div>
              {error &&
              <p className="ct-error" role="alert" style={{ marginTop: "16px", color: "#C0341D", fontSize: "14px", lineHeight: 1.5 }}>{error}</p>
              }
            </form>
          }
        </div>
      </div>
    </section>);
}

/* =================== FAQ =================== */
function FAQ() {
  const items = [
  { q: "How long does a website project take?", a: "Most builds wrap in 2 weeks once we have your branding, content, and direction locked in. Larger custom projects can run 2-4 weeks." },
  { q: "Do you work with businesses outside New Zealand?", a: "Yes — most of our clients are NZ-based, but we work remotely with businesses across AU, the UK, and the US too." },
  { q: "Do I need to have my content ready?", a: "Helps, but not required. Our Foundation builds includes copywriting for every page, and we can also recommend photographers if you need imagery." },
  { q: "What happens after launch?", a: "We offer optional Care Plans (hosting + monthly updates) so you don't have to think about maintenance. Or just take the keys and run with it — your call." },
  { q: "Can you help with ads and SEO too?", a: "Yes. We run Google + Meta ad campaigns and handle on-page SEO and Google Business setup. Reporting is monthly, in plain English." }];

  return (
    <section className="ct-faq">
      <div className="ct-faq-inner">
        <h2>Common <em>questions</em>.</h2>
        <div className="ct-faq-list">
          {items.map((it, i) =>
          <details key={i} className="ct-faq-item">
              <summary className="ct-faq-q">
                {it.q}
                <span className="ct-faq-toggle">+</span>
              </summary>
              <div className="ct-faq-a">{it.a}</div>
            </details>
          )}
        </div>
      </div>
    </section>);
}

/* =================== FOOTER =================== */
function Footer() {
  return (
    <footer className="footer">
      <div className="footer-top">
        <div className="footer-brand">
          <div className="brand">
            <img src="assets/qd-logo.png" alt="Quantum Design" style={{ width: "40px", height: "40px" }} />
            <span>Quantum Design</span>
          </div>
          <p className="footer-tag">Design and Marketing for businesses that want to grow.</p>
        </div>
        <div className="footer-cols">
          <div>
            <div className="footer-h" style={{ color: "rgb(31, 169, 240)" }}>Services</div>
            <a href="web-design.html">Web Design</a>
            <a href="marketing.html">Marketing &amp; SEO</a>
          </div>
          <div>
            <div className="footer-h" style={{ color: "rgb(31, 169, 240)" }}>The Studio</div>
            <a href="about.html">About</a>
            <a href="index.html#services">Services</a>
            <a href="portfolio.html">Portfolio</a>
            <a href="contact.html">Contact</a>
          </div>
          <div>
            <div className="footer-h" style={{ color: "rgb(31, 169, 240)" }}>SAY HELLO</div>
            <a href="mailto:quantumdesignnz@gmail.com">QuantumDesignNZ@gmail.com</a>
            <a href="https://www.facebook.com/quantumdesignnz" target="_blank" rel="noopener noreferrer">Facebook</a>
            <a href="https://www.instagram.com/quantumdesign.co.nz" target="_blank" rel="noopener noreferrer">Instagram</a>
          </div>
        </div>
      </div>
      <div className="footer-bot">
        <span>© 2025-2026 Quantum Design</span>
        <span></span>
      </div>
    </footer>);
}

/* =================== APP =================== */
function ContactApp() {
  return (
    <div>
      <Nav />
      <ContactSection />
      <FAQ />
      <Footer />
    </div>);
}

ReactDOM.createRoot(document.getElementById('root')).render(<ContactApp />);