/* global React */

function Field({ label, type = 'text', placeholder, focused, full, as = 'input', value, onChange, name }) {
  const cls = "field-input" + (focused ? ' is-focused' : '');
  const isControlled = typeof onChange === 'function';
  const inputProps = isControlled
    ? { value: value ?? '', onChange: (e) => onChange(e.target.value) }
    : { defaultValue: value };
  return (
    <div className="field" style={{ gridColumn: full ? '1 / -1' : 'auto' }}>
      <span className="field-label">{label}</span>
      {as === 'textarea' ? (
        <textarea className={cls} name={name} placeholder={placeholder} {...inputProps} />
      ) : (
        <input type={type} className={cls} name={name} placeholder={placeholder} {...inputProps} />
      )}
    </div>
  );
}

const HOURS = [
  { day: 'Monday',    h: '9:00 am – 4:00 pm' },
  { day: 'Tuesday',   h: '9:00 am – 4:00 pm' },
  { day: 'Wednesday', h: '9:00 am – 4:00 pm' },
  { day: 'Thursday',  h: '9:00 am – 4:00 pm' },
  { day: 'Friday',    h: '9:00 am – 4:00 pm' },
  { day: 'Saturday',  h: 'Closed', closed: true },
  { day: 'Sunday',    h: 'Closed', closed: true },
];

function ContactDetails() {
  return (
    <div className="contact-details">
      <div className="contact-block-card">
        <span className="eyebrow" style={{ display: 'block', marginBottom: 14, color: 'var(--solder-bright)' }}>Where to find us</span>
        <div className="addr">
          <div className="addr-name">E-Assembly</div>
          <div className="addr-line">1325 E 1st Ave</div>
          <div className="addr-line">Camas, Washington 98607</div>
        </div>
        <div className="contact-links">
          <a href="tel:+13603534200" className="contact-link">
            <span className="cl-label">Phone</span>
            <span className="cl-value">(360) 353-4200</span>
          </a>
          <a href="mailto:Sales@e-assembly.tech" className="contact-link">
            <span className="cl-label">Email</span>
            <span className="cl-value">Sales@e-assembly.tech</span>
          </a>
        </div>
      </div>

      <div className="contact-block-card">
        <span className="eyebrow" style={{ display: 'block', marginBottom: 14, color: 'var(--solder-bright)' }}>Hours</span>
        <table className="hours-table">
          <tbody>
            {HOURS.map((row) => (
              <tr key={row.day} className={row.closed ? 'is-closed' : ''}>
                <td className="day">{row.day}</td>
                <td className="time">{row.h}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function ContactForm() {
  const [name, setName] = React.useState('');
  const [company, setCompany] = React.useState('');
  const [email, setEmail] = React.useState('');
  const [phone, setPhone] = React.useState('');
  const [what, setWhat] = React.useState('');
  const [message, setMessage] = React.useState('');
  const [whatFocused, setWhatFocused] = React.useState(false);
  const [status, setStatus] = React.useState('idle'); // idle | sending | success | error
  const [errorMsg, setErrorMsg] = React.useState('');
  const hpRef = React.useRef(null);

  React.useEffect(() => {
    const handler = (e) => {
      const v = e && e.detail && e.detail.what;
      if (!v) return;
      setWhat(v);
      setWhatFocused(true);
      window.setTimeout(() => setWhatFocused(false), 1800);
    };
    window.addEventListener('contact-prefill', handler);
    return () => window.removeEventListener('contact-prefill', handler);
  }, []);

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (status === 'sending') return;
    setStatus('sending');
    setErrorMsg('');
    try {
      const r = await fetch('/api/contact', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name, company, email, phone, what, message,
          _hp: hpRef.current ? hpRef.current.value : '',
        }),
      });
      if (r.ok) {
        setStatus('success');
        setName(''); setCompany(''); setEmail(''); setPhone(''); setWhat(''); setMessage('');
      } else {
        const data = await r.json().catch(() => ({}));
        setStatus('error');
        setErrorMsg(data.error || 'Something went wrong. Please try again.');
      }
    } catch (err) {
      setStatus('error');
      setErrorMsg('Network error — please try again.');
    }
  };

  return (
    <form className="form-card" id="contact-form" onSubmit={handleSubmit} noValidate>
      <span className="eyebrow" style={{ display: 'block', marginBottom: 10 }}>Send us a message</span>
      <h3>How can we help?</h3>

      <div className="form-grid-2">
        <Field label="Name" name="name" value={name} onChange={setName} />
        <Field label="Company" name="company" value={company} onChange={setCompany} />
        <Field label="Email" name="email" type="email" value={email} onChange={setEmail} />
        <Field label="Phone" name="phone" type="tel" value={phone} onChange={setPhone} />
        <Field
          label="What do you need?"
          name="what"
          full
          value={what}
          onChange={setWhat}
          focused={whatFocused}
        />
        <Field label="Message" name="message" full as="textarea" value={message} onChange={setMessage} />
      </div>

      {/* honeypot — off-screen, bots tend to fill any input */}
      <input
        ref={hpRef}
        type="text"
        name="website"
        tabIndex="-1"
        autoComplete="off"
        aria-hidden="true"
        style={{ position: 'absolute', left: '-10000px', width: 1, height: 1, opacity: 0 }}
      />

      <div className="form-row-actions" style={{ justifyContent: 'flex-end' }}>
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 10 }}>
          <button type="submit" className="btn btn-primary btn-arrow" disabled={status === 'sending'}>
            {status === 'sending' ? 'Sending…' : 'Send message'}
          </button>
          {status === 'success' && (
            <div className="form-status form-status-success" role="status">Message sent.</div>
          )}
          {status === 'error' && (
            <div className="form-status form-status-error" role="alert">{errorMsg}</div>
          )}
        </div>
      </div>
    </form>
  );
}

function SupportSection() {
  return (
    <section className="support" id="contact">
      <div className="support-inner">
        <div className="section-head" style={{ padding: 0, marginBottom: 48, maxWidth: 'none' }}>
          <div>
            <span className="eyebrow" style={{ display: 'block', marginBottom: 14 }}>Contact us</span>
            <h2>Let's build something — together.</h2>
          </div>
        </div>

        <div className="contact-grid">
          <ContactDetails />
          <ContactForm />
        </div>
      </div>
    </section>
  );
}

window.SupportSection = SupportSection;
window.Field = Field;
