/* global React, Reveal */
const {
  useState: useStateContact,
  useEffect: useEffectContact,
  useRef: useRefContact,
} = React;

const CONTACT_TOPICS = [
  { value: 'services', label: 'Services' },
  { value: 'frameworks', label: 'Frameworks' },
  { value: 'engagement', label: 'Engagement' },
  { value: 'partnership', label: 'Partnership' },
  { value: 'insights', label: 'Insights' },
  { value: 'other', label: 'Other' },
  { value: 'case-studies', label: 'Case Studies' },
];

function ContactPage({ go }) {
  const [form, setForm] = useStateContact({ name: '', org: '', email: '', topic: '', message: '', website: '' });
  const [status, setStatus] = useStateContact('idle'); // idle | submitting | success | error
  const [submitError, setSubmitError] = useStateContact('');
  const [topicOpen, setTopicOpen] = useStateContact(false);
  const [topicError, setTopicError] = useStateContact(false);
  const topicDropdownRef = useRefContact(null);
  const topicButtonRef = useRefContact(null);
  const topicOptionRefs = useRefContact([]);
  const successDialogRef = useRefContact(null);
  const submitButtonRef = useRefContact(null);
  const startedAtRef = useRefContact(Date.now());

  useEffectContact(() => {
    if (!topicOpen) return undefined;
    const closeOnOutsidePress = (event) => {
      if (!topicDropdownRef.current?.contains(event.target)) setTopicOpen(false);
    };
    document.addEventListener('pointerdown', closeOnOutsidePress);
    return () => document.removeEventListener('pointerdown', closeOnOutsidePress);
  }, [topicOpen]);

  useEffectContact(() => {
    if (status === 'success' && !successDialogRef.current?.open) {
      successDialogRef.current?.showModal();
    }
  }, [status]);

  const focusTopicOption = (index) => {
    requestAnimationFrame(() => topicOptionRefs.current[index]?.focus({ preventScroll: true }));
  };

  const openTopicList = (index = Math.max(0, CONTACT_TOPICS.findIndex((option) => option.value === form.topic))) => {
    setTopicOpen(true);
    focusTopicOption(index);
  };

  const chooseTopic = (option) => {
    setForm((current) => ({ ...current, topic: option.value }));
    setTopicError(false);
    document.getElementById('f-topic')?.setCustomValidity('');
    setTopicOpen(false);
    if (status === 'error') {
      setStatus('idle');
      setSubmitError('');
    }
    requestAnimationFrame(() => topicButtonRef.current?.focus({ preventScroll: true }));
  };

  const handleTopicButtonKeyDown = (event) => {
    if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
      event.preventDefault();
      const selectedIndex = CONTACT_TOPICS.findIndex((option) => option.value === form.topic);
      openTopicList(event.key === 'ArrowUp'
        ? (selectedIndex >= 0 ? selectedIndex : CONTACT_TOPICS.length - 1)
        : Math.max(0, selectedIndex));
    } else if (event.key === 'Escape' && topicOpen) {
      event.preventDefault();
      setTopicOpen(false);
    }
  };

  const handleTopicOptionKeyDown = (event, index) => {
    if (event.key === 'Escape') {
      event.preventDefault();
      setTopicOpen(false);
      requestAnimationFrame(() => topicButtonRef.current?.focus({ preventScroll: true }));
      return;
    }
    const movement = {
      ArrowDown: (index + 1) % CONTACT_TOPICS.length,
      ArrowUp: (index - 1 + CONTACT_TOPICS.length) % CONTACT_TOPICS.length,
      Home: 0,
      End: CONTACT_TOPICS.length - 1,
    }[event.key];
    if (movement !== undefined) {
      event.preventDefault();
      focusTopicOption(movement);
    }
  };

  const submit = async (e) => {
    e.preventDefault();
    const topicControl = e.currentTarget.elements.namedItem('f-topic');
    const messageControl = e.currentTarget.elements.namedItem('message');
    if (!form.topic) {
      setTopicError(true);
      if (window.matchMedia('(max-width: 640px)').matches) {
        setTopicOpen(true);
        requestAnimationFrame(() => topicButtonRef.current?.focus({ preventScroll: true }));
      } else {
        topicControl?.setCustomValidity('Please select a topic.');
        topicControl?.reportValidity();
        topicControl?.focus({ preventScroll: true });
      }
      return;
    }
    topicControl?.setCustomValidity('');
    if (form.message.trim().length < 5) {
      messageControl?.setCustomValidity('Please enter your message—at least 5 characters.');
      messageControl?.reportValidity();
      messageControl?.focus({ preventScroll: true });
      return;
    }
    messageControl?.setCustomValidity('');

    setStatus('submitting');
    setSubmitError('');

    try {
      const response = await fetch('/api/contact', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          ...form,
          startedAt: startedAtRef.current,
        }),
      });
      const result = await response.json().catch(() => ({}));
      if (!response.ok) throw new Error(result.message || 'Your enquiry could not be sent. Please try again.');

      setForm({ name: '', org: '', email: '', topic: '', message: '', website: '' });
      setTopicError(false);
      startedAtRef.current = Date.now();
      setStatus('success');
    } catch (error) {
      setSubmitError(error.message || 'Your enquiry could not be sent. Please try again.');
      setStatus('error');
    }
  };

  const update = (k) => (e) => {
    const value = e.target.value;
    setForm((current) => ({ ...current, [k]: value }));
    if (k === 'topic') {
      setTopicError(false);
      e.currentTarget.setCustomValidity('');
    }
    if (status === 'error') {
      setStatus('idle');
      setSubmitError('');
    }
  };

  const closeSuccessDialog = () => {
    successDialogRef.current?.close();
  };

  const handleSuccessDialogClose = () => {
    setStatus('idle');
    requestAnimationFrame(() => submitButtonRef.current?.focus({ preventScroll: true }));
  };

  return (
    <div className="page-enter" data-screen-label="Contact">
      {/* HEADER */}
      <section className="page-header">
        <div className="container">
          <span className="label page-locator">Contact · Direct conversation</span>
          <div className="page-header-grid">
            <h1 className="display-1">
              Let's have a<br />
              <em>direct</em> conversation.
            </h1>
            <p className="page-header-lede lede">
              We're open to direct conversations with people working on interesting problems. No long forms. No sales process. Just a straightforward exchange about whether we can be useful.
            </p>
          </div>
        </div>
      </section>

      {/* CONTACT */}
      <Reveal as="section" className="section">
        <div className="container">
          <div className="contact-panel">
            <div className="contact-panel-intro">
              <h2 className="contact-panel-heading">
                Send a message by submitting this form or <em>reach out directly.</em>
              </h2>
              <p>
                A short email is just as welcome as a polished enquiry. Tell us what you're working on, what's making it difficult, and whether you're looking for a sounding board or something more. If we can help, we'll say so clearly. If we can't, we'll say that too — and suggest who might.
              </p>
            </div>

            <div className="contact-section-rule" aria-hidden="true" />

            <form className="contact-form" onSubmit={submit} aria-busy={status === 'submitting'}>
              <div className="form-honeypot" aria-hidden="true">
                <label htmlFor="f-website">Website</label>
                <input
                  id="f-website"
                  name="website"
                  type="text"
                  tabIndex="-1"
                  autoComplete="off"
                  value={form.website}
                  onChange={update('website')}
                />
              </div>

              <div className="form-field">
                <label className="form-label" htmlFor="f-name">Name</label>
                <input
                  id="f-name"
                  name="name"
                  className="form-input"
                  type="text"
                  autoComplete="name"
                  maxLength="120"
                  placeholder="Your name"
                  value={form.name}
                  onChange={update('name')}
                  required
                />
              </div>

              <div className="form-field">
                <label className="form-label" htmlFor="f-org">Organisation (optional)</label>
                <input
                  id="f-org"
                  name="organisation"
                  className="form-input"
                  type="text"
                  autoComplete="organization"
                  maxLength="160"
                  placeholder="Where you work"
                  value={form.org}
                  onChange={update('org')}
                />
              </div>

              <div className="form-field">
                <label className="form-label" htmlFor="f-email">Email</label>
                <input
                  id="f-email"
                  name="email"
                  className="form-input"
                  type="email"
                  autoComplete="email"
                  maxLength="254"
                  placeholder="you@organisation.com"
                  value={form.email}
                  onChange={update('email')}
                  required
                />
              </div>

              <div className="form-field">
                <label id="f-topic-label" className="form-label" htmlFor="f-topic">Enquiry topic</label>
                <select
                  id="f-topic"
                  name="topic"
                  className="form-select form-select--native"
                  value={form.topic}
                  onChange={update('topic')}
                  aria-required="true"
                  aria-invalid={topicError || undefined}
                  aria-describedby={topicError ? 'f-topic-error' : undefined}
                >
                  <option value="" disabled>Select a topic</option>
                  {CONTACT_TOPICS.map((option) => (
                    <option value={option.value} key={option.value}>{option.label}</option>
                  ))}
                </select>
                <div className="form-topic-mobile" ref={topicDropdownRef}>
                  <button
                    id="f-topic-button"
                    ref={topicButtonRef}
                    type="button"
                    className={`form-topic-button ${topicOpen ? 'is-open' : ''} ${form.topic ? '' : 'is-placeholder'}`}
                    aria-labelledby="f-topic-label f-topic-button"
                    aria-haspopup="listbox"
                    aria-expanded={topicOpen}
                    aria-controls="f-topic-list"
                    aria-required="true"
                    aria-invalid={topicError || undefined}
                    aria-describedby={topicError ? 'f-topic-error' : undefined}
                    onClick={() => (topicOpen ? setTopicOpen(false) : openTopicList())}
                    onKeyDown={handleTopicButtonKeyDown}
                  >
                    <span>{CONTACT_TOPICS.find((option) => option.value === form.topic)?.label || 'Select a topic'}</span>
                    <span className="form-topic-chevron" aria-hidden="true">⌄</span>
                  </button>
                  <ul
                    id="f-topic-list"
                    className="form-topic-list"
                    role="listbox"
                    aria-labelledby="f-topic-label"
                    hidden={!topicOpen}
                  >
                    {CONTACT_TOPICS.map((option, index) => (
                      <li role="none" key={option.value}>
                        <button
                          ref={(element) => { topicOptionRefs.current[index] = element; }}
                          type="button"
                          className="form-topic-option"
                          role="option"
                          aria-selected={form.topic === option.value}
                          onClick={() => chooseTopic(option)}
                          onKeyDown={(event) => handleTopicOptionKeyDown(event, index)}
                        >
                          <span>{option.label}</span>
                          {form.topic === option.value && <span aria-hidden="true">✓</span>}
                        </button>
                      </li>
                    ))}
                  </ul>
                </div>
                {topicError && <span id="f-topic-error" className="form-field-error" role="alert">Please select a topic.</span>}
              </div>

              <div className="form-field form-field--message">
                <label className="form-label" htmlFor="f-msg">What are you working on?</label>
                <textarea
                  id="f-msg"
                  name="message"
                  className="form-textarea"
                  minLength="5"
                  maxLength="5000"
                  placeholder="A few sentences is plenty — enough that we know whether this is something we can help with."
                  value={form.message}
                  onChange={update('message')}
                  onInvalid={(event) => event.currentTarget.setCustomValidity('Please enter your message—at least 5 characters.')}
                  onInput={(event) => event.currentTarget.setCustomValidity('')}
                  required
                />
              </div>

              <div className="form-submit-row">
                <button
                  ref={submitButtonRef}
                  type="submit"
                  className="btn btn-primary btn-gold"
                  disabled={status === 'submitting'}
                >
                  {status === 'submitting' ? 'Sending…' : 'Submit'} <span className="arrow" aria-hidden="true">→</span>
                </button>
                <span id="form-delivery-note" className="form-status" role="status" aria-live="polite" aria-atomic="true">
                  {status === 'submitting' ? 'Sending your enquiry securely.' : ''}
                </span>
              </div>
              {status === 'error' && (
                <p className="form-submit-error" role="alert">
                  {submitError} You can also <a href="mailto:contact@ideligoconsulting.com">send us an email</a>.
                </p>
              )}
            </form>

            <div className="contact-section-rule" aria-hidden="true" />

            <div className="contact-direct">
                <div className="contact-direct-row">
                  <span className="contact-direct-label">Email</span>
                  <span className="contact-direct-val">
                    <a href="mailto:contact@ideligoconsulting.com">Send us an email</a>
                  </span>
                </div>
                <div className="contact-direct-row">
                  <span className="contact-direct-label">LinkedIn</span>
                  <span className="contact-direct-val">
                    <a href="https://www.linkedin.com/in/irina-dunayevsky-mba-pmp/" target="_blank" rel="noopener noreferrer">Connect on LinkedIn ↗</a>
                  </span>
                </div>
                <div className="contact-direct-row">
                  <span className="contact-direct-label">Response</span>
                  <span className="contact-direct-val contact-direct-val--plain">
                    Within two working days.
                  </span>
                </div>
                <div className="contact-direct-row">
                  <span className="contact-direct-label">Hours</span>
                  <span className="contact-direct-val contact-direct-val--plain">
                    Melbourne time (AEST/AEDT) · Mon–Thu, 09:00–17:00
                  </span>
                </div>
            </div>

          </div>
        </div>
      </Reveal>

      <dialog
        ref={successDialogRef}
        className="contact-success-dialog"
        aria-labelledby="contact-success-title"
        onCancel={(event) => {
          event.preventDefault();
          closeSuccessDialog();
        }}
        onClose={handleSuccessDialogClose}
      >
        <button
          type="button"
          className="contact-success-close"
          onClick={closeSuccessDialog}
          aria-label="Close confirmation"
        >
          ×
        </button>
        <span className="label">Enquiry sent</span>
        <h2 id="contact-success-title">Thank you. Your message is on its way.</h2>
        <p>We will respond within two working days.</p>
        <button type="button" className="btn btn-primary btn-gold" onClick={closeSuccessDialog}>
          Close
        </button>
      </dialog>

    </div>
  );
}

window.ContactPage = ContactPage;
