/* contact.jsx — contact form (Name, Email, Message) + footer */
const { useState: useStateContact } = React;

const FORM_ENDPOINT = 'https://formsubmit.co/ajax/muteebnasir9@gmail.com';

function ContactForm() {
  const { Button } = window.MacnitechDesignSystem_13fddf;
  const [data, setData] = useStateContact({ name: '', email: '', message: '' });
  const [errors, setErrors] = useStateContact({});
  const [sent, setSent] = useStateContact(false);
  const [sending, setSending] = useStateContact(false);
  const [serverError, setServerError] = useStateContact('');

  const set = (k) => (e) => setData((d) => ({ ...d, [k]: e.target.value }));

  const submit = async (e) => {
    e.preventDefault();
    const err = {};
    if (!data.name.trim()) err.name = true;
    if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(data.email)) err.email = true;
    if (!data.message.trim()) err.message = true;
    setErrors(err);
    if (Object.keys(err).length > 0) return;

    setSending(true);
    setServerError('');
    try {
      const res = await fetch(FORM_ENDPOINT, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
        body: JSON.stringify({ name: data.name, email: data.email, message: data.message }),
      });
      const json = await res.json();
      if (json.success === 'true' || json.success === true) {
        setSent(true);
      } else {
        setServerError('Something went wrong. Please try again or email us directly.');
      }
    } catch {
      setServerError('Network error. Please try again or email us directly.');
    } finally {
      setSending(false);
    }
  };

  if (sent) {
    return (
      <div className="form form__ok" role="status">
        <div className="form__ok-mark"><Icon name="check" size={30} stroke={2.4} /></div>
        <h3 style={{ color: 'var(--cream)', fontSize: '1.6rem', margin: '0 0 0.4rem' }}>Thanks, {data.name.split(' ')[0]}.</h3>
        <p style={{ color: 'rgba(240,234,228,0.72)', margin: 0 }}>
          We've got your message. Expect a reply within one business day — with a free growth audit attached.
        </p>
      </div>
    );
  }

  return (
    <form className="form" onSubmit={submit} noValidate>
      <div className="field">
        <label htmlFor="cf-name">Name</label>
        <input id="cf-name" value={data.name} onChange={set('name')} placeholder="Jane Cooper"
               style={errors.name ? { borderColor: 'var(--bloodstone)' } : null} />
      </div>
      <div className="field">
        <label htmlFor="cf-email">Email</label>
        <input id="cf-email" type="email" value={data.email} onChange={set('email')} placeholder="jane@company.com"
               style={errors.email ? { borderColor: 'var(--bloodstone)' } : null} />
      </div>
      <div className="field">
        <label htmlFor="cf-message">Message</label>
        <textarea id="cf-message" value={data.message} onChange={set('message')} placeholder="Tell us about your business and what you're trying to grow."
                  style={errors.message ? { borderColor: 'var(--bloodstone)' } : null} />
      </div>
      <Button type="submit" variant="primary" size="lg" fullWidth
              iconRight={sending ? null : <Icon name="arrowRight" size={18} />}
              disabled={sending}>
        {sending ? 'Sending…' : 'Request my free audit'}
      </Button>
      {Object.keys(errors).length > 0 && (
        <p style={{ color: 'var(--bloodstone)', fontSize: 'var(--text-sm)', margin: '0.9rem 0 0', textAlign: 'center' }}>
          Please complete the highlighted fields.
        </p>
      )}
      {serverError && (
        <p style={{ color: 'var(--bloodstone)', fontSize: 'var(--text-sm)', margin: '0.9rem 0 0', textAlign: 'center' }}>
          {serverError}
        </p>
      )}
    </form>
  );
}

function Contact() {
  return (
    <section className="section contact" id="contact" data-screen-label="Contact">
      <div className="contact__glow" />
      <div className="mt-container contact__inner">
        <div className="reveal">
          <span className="eyebrow eyebrow--tick" style={{ color: 'var(--bloodstone)' }}>Start here</span>
          <h2 style={{ marginTop: '0.6rem' }}>Start with a free audit — no pitch, just clarity.</h2>
          <p className="contact__lead">
            Tell us what you're trying to grow. We'll send back a Digital Growth Audit showing
            exactly where the opportunities are.
          </p>
          <ul className="contact__points">
            <li><Icon name="mail" size={20} /><span>muteebnasir9@gmail.com</span></li>
            <li><Icon name="phone" size={20} /><span>+966 572 501 100</span></li>
            <li><Icon name="mapPin" size={20} /><span>United Kingdom · Working globally</span></li>
            <li><Icon name="clock" size={20} /><span>Reply within one business day</span></li>
          </ul>
        </div>
        <div className="reveal"><ContactForm /></div>
      </div>
    </section>
  );
}

const FBASE = window.NAV_BASE || '';
const FOOTER_COLS = [
  { h: 'Services', links: [['SEO', FBASE + 'pages/seo.html'], ['Web Development', FBASE + 'pages/web-development.html'], ['AI Automation', FBASE + 'pages/ai-automation.html']] },
  { h: 'Company', links: [['Work', FBASE + 'index.html#portfolio'], ['Pricing', FBASE + 'index.html#pricing'], ['Results', FBASE + 'index.html#testimonials'], ['Contact', FBASE + 'index.html#contact']] },
  { h: 'Get started', links: [['Free audit', FBASE + 'index.html#contact'], ['Book a call', FBASE + 'index.html#contact']] },
];

function Footer() {
  return (
    <footer className="footer">
      <div className="mt-container">
        <div className="footer__top">
          <div>
            <img className="footer__logo" src={FBASE + 'assets/macnitech_logo_light.png'} alt="Macnitech" />
            <p className="footer__blurb">
              The digital growth engine for ambitious businesses — the visibility to be found,
              the credibility to be chosen, and the automation to scale.
            </p>
          </div>
          {FOOTER_COLS.map((c) => (
            <div className="footer__col" key={c.h}>
              <h5>{c.h}</h5>
              <ul>{c.links.map(([t, h]) => <li key={t}><a href={h}>{t}</a></li>)}</ul>
            </div>
          ))}
        </div>
        <div className="footer__bottom">
          <span>© {new Date().getFullYear()} Macnitech. Outcomes, not outputs.</span>
          <div className="footer__social">
            <a href="#" aria-label="LinkedIn"><Icon name="linkedin" size={17} /></a>
            <a href="#" aria-label="Twitter"><Icon name="twitter" size={17} /></a>
            <a href="#" aria-label="GitHub"><Icon name="github" size={17} /></a>
          </div>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, { Contact, Footer });
