function CollabHeading() {
  const wrapRef = React.useRef(null);
  const lineRef = React.useRef(null);

  React.useEffect(() => {
    const wrap = wrapRef.current, line = lineRef.current;
    if (!wrap || !line) return;
    if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) return;

    // Was an unconditional infinite rAF loop -- a forced
    // getBoundingClientRect() every frame for the page's entire
    // lifetime, even while scrolling through sections nowhere near
    // Contact (measured as the single largest idle contributor site-
    // wide). Now gated by an IntersectionObserver so it only runs while
    // this heading is anywhere near the viewport.
    let rafId = null;
    const update = () => {
      const rect = wrap.getBoundingClientRect();
      const vh = window.innerHeight;
      const start = vh * 0.95, end = vh * 0.35;
      let progress = (start - rect.top) / (start - end);
      progress = Math.max(0, Math.min(1, progress));
      const offset = (1 - progress) * 220;
      line.style.transform = `translateX(${offset}px)`;
      line.style.opacity = 0.25 + 0.75 * progress;
      rafId = requestAnimationFrame(update);
    };
    const startLoop = () => { if (rafId === null) rafId = requestAnimationFrame(update); };
    const stopLoop = () => { if (rafId !== null) { cancelAnimationFrame(rafId); rafId = null; } };

    const io = new IntersectionObserver((entries) => {
      if (entries[0].isIntersecting) startLoop(); else stopLoop();
    }, { rootMargin: '50% 0px 50% 0px' });
    io.observe(wrap);

    return () => { stopLoop(); io.disconnect(); };
  }, []);

  return (
    <h2 className="h2 collab-heading" ref={wrapRef}>
      <span className="collab-line">Let's Build Something</span>
      <span className="collab-line collab-line2" ref={lineRef}>Amazing Together.</span>
    </h2>
  );
}

function Contact() {
  const { Input, Button } = window.ArnelBiscarraDesignSystem_2766cb;
  const [sent, setSent] = React.useState(false);
  const [form, setForm] = React.useState({ name: '', email: '', phone: '', subject: '', message: '' });
  const [copied, setCopied] = React.useState(false);
  const copyTimerRef = React.useRef(null);

  const copyEmail = (email) => (e) => {
    e.preventDefault(); // the row's value is otherwise just a mailto link — this button copies instead of opening the mail app
    const done = () => {
      setCopied(true);
      clearTimeout(copyTimerRef.current);
      copyTimerRef.current = setTimeout(() => setCopied(false), 1800);
    };
    if (navigator.clipboard && navigator.clipboard.writeText) {
      navigator.clipboard.writeText(email).then(done).catch(() => fallbackCopy(email, done));
    } else {
      fallbackCopy(email, done);
    }
  };
  // Fallback for browsers/contexts without the async Clipboard API
  // (e.g. non-HTTPS): a temporary offscreen textarea + execCommand.
  const fallbackCopy = (text, done) => {
    const ta = document.createElement('textarea');
    ta.value = text;
    ta.style.position = 'fixed';
    ta.style.left = '-9999px';
    document.body.appendChild(ta);
    ta.select();
    try { document.execCommand('copy'); done(); } catch (err) {}
    document.body.removeChild(ta);
  };

  const update = (k) => (e) => setForm((f) => ({ ...f, [k]: e.target.value }));
  const submit = (e) => {
    e.preventDefault();
    const subject = form.subject ? `Portfolio inquiry: ${form.subject}` : 'Portfolio inquiry';
    const body = `Name: ${form.name}\nEmail: ${form.email}\nPhone: ${form.phone}\n\n${form.message}`;
    window.location.href = `mailto:arnelbiscarra@gmail.com?subject=${encodeURIComponent(subject)}&body=${encodeURIComponent(body)}`;
    setSent(true);
  };

  return (
    <section id="contact" className="section container" data-screen-label="Contact">
      <Reveal><div className="eyebrow"><b>/</b> CONTACT</div></Reveal>
      <Reveal><CollabHeading /></Reveal>
      <Reveal><p className="lede">Have a project in mind? Send a few details and I'll get back to you shortly.</p></Reveal>

      <div className="contact-grid">
        <Reveal>
          <form onSubmit={submit}>
            <div className="form-row">
              <div className="form-field">
                <label>Name</label>
                <Input placeholder="Your name" value={form.name} onChange={update('name')} />
              </div>
              <div className="form-field">
                <label>Email</label>
                <Input type="email" placeholder="you@email.com" value={form.email} onChange={update('email')} />
              </div>
            </div>
            <div className="form-row">
              <div className="form-field">
                <label>Phone</label>
                <Input placeholder="Optional" value={form.phone} onChange={update('phone')} />
              </div>
              <div className="form-field">
                <label>Subject</label>
                <Input placeholder="Project type" value={form.subject} onChange={update('subject')} />
              </div>
            </div>
            <div className="form-field" style={{ marginBottom: 16 }}>
              <label>Message</label>
              <textarea placeholder="Tell me about your project" value={form.message} onChange={update('message')}></textarea>
            </div>
            <Button variant="accent" arrow size="lg">Send Message</Button>
            {sent && <div className="form-success">Thanks! Your email app should open with the message ready to send.</div>}
          </form>
        </Reveal>

        <Reveal delay={100}>
          <div className="contact-info-list">
            {window.SITE_DATA.contactInfo.map((c) => (
              <div className="contact-info-row" key={c.label}>
                <span className="contact-info-label">{c.label}</span>
                <span className="contact-info-value">
                  {c.href ? <a href={c.href} target="_blank" rel="noopener noreferrer">{c.value}</a> : <span>{c.value}</span>}
                  {c.label === 'Email' && (
                    <button
                      type="button"
                      className={`contact-copy-btn ${copied ? 'is-copied' : ''}`}
                      onClick={copyEmail(c.value)}
                      aria-label="Copy email address"
                      title="Copy email address"
                    >
                      {copied ? (
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12"></polyline></svg>
                      ) : (
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="9" y="9" width="12" height="12" rx="2"></rect><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path></svg>
                      )}
                      <span className="contact-copy-tip">{copied ? 'Copied!' : 'Copy'}</span>
                    </button>
                  )}
                </span>
              </div>
            ))}
          </div>
        </Reveal>
      </div>
    </section>
  );
}

window.Contact = Contact;
