/* Contact form — sales enquiries via the LexInTosh API. */
const { Button, Label } = window.LexInToshDesignSystem_e187a4;
const Icon = window.Icon;
const SITE = window.SITE;
const FORM = SITE.contactForm;
const RECAPTCHA = SITE.recaptcha;

const FIELD_LIMITS = {
  name: 120,
  organization: 200,
  email: 254,
  phone: 30,
  message: 5000
};

function validateContactForm(form) {
  const errors = {};
  const name = form.name.trim();
  const email = form.email.trim();
  const message = form.message.trim();
  const phone = form.phone.trim();
  const organization = form.organization.trim();

  if (!name) errors.name = "Name is required.";
  else if (name.length < 2) errors.name = "Name must be at least 2 characters.";
  else if (name.length > FIELD_LIMITS.name) errors.name = `Name must be ${FIELD_LIMITS.name} characters or fewer.`;

  if (!email) errors.email = "Email is required.";
  else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) errors.email = "Please enter a valid email address.";
  else if (email.length > FIELD_LIMITS.email) errors.email = "Email is too long.";

  if (phone && !/^[+\d\s().-]{7,30}$/.test(phone)) {
    errors.phone = "Please enter a valid phone number.";
  }

  if (organization && organization.length > FIELD_LIMITS.organization) {
    errors.organization = `Organization must be ${FIELD_LIMITS.organization} characters or fewer.`;
  }

  if (!message) errors.message = "Message is required.";
  else if (message.length < 10) errors.message = "Message must be at least 10 characters.";
  else if (message.length > FIELD_LIMITS.message) errors.message = `Message must be ${FIELD_LIMITS.message} characters or fewer.`;

  if (!FORM.roles.includes(form.role)) errors.role = "Please select a valid role.";
  if (!FORM.interests.includes(form.interest)) errors.interest = "Please select a valid interest.";

  return errors;
}

function ContactField({ id, label, required, error, children }) {
  return (
    <div className={"contact__field" + (error ? " contact__field--invalid" : "")}>
      <Label htmlFor={id}>{label}{required ? " *" : ""}</Label>
      {children}
      {error ? <span className="contact__error" role="alert">{error}</span> : null}
    </div>
  );
}

function ContactInput({ id, error, className = "", ...rest }) {
  return (
    <input
      id={id}
      className={"contact__input" + (error ? " contact__input--invalid" : "") + (className ? " " + className : "")}
      aria-invalid={error ? "true" : "false"}
      {...rest}
    />
  );
}

function Contact() {
  const [form, setForm] = React.useState({
    role: FORM.roles[0],
    name: "",
    organization: "",
    email: "",
    phone: "",
    interest: FORM.interests[0],
    message: ""
  });
  const [errors, setErrors] = React.useState({});
  const [status, setStatus] = React.useState({ type: "", text: "" });
  const [sending, setSending] = React.useState(false);

  function updateField(key, value) {
    setForm((prev) => ({ ...prev, [key]: value }));
    if (errors[key]) {
      setErrors((prev) => {
        const next = { ...prev };
        delete next[key];
        return next;
      });
    }
  }

  async function executeRecaptcha(attempt = 1) {
    if (!window.grecaptcha?.enterprise) {
      throw new Error("reCAPTCHA not loaded. Please refresh and try again.");
    }
    return new Promise((resolve, reject) => {
      window.grecaptcha.enterprise.ready(async () => {
        try {
          const token = await window.grecaptcha.enterprise.execute(RECAPTCHA.siteKey, {
            action: RECAPTCHA.action
          });
          resolve(token);
        } catch (err) {
          if (attempt < 3) {
            setTimeout(() => {
              executeRecaptcha(attempt + 1).then(resolve).catch(reject);
            }, 400 * attempt);
            return;
          }
          reject(err);
        }
      });
    });
  }

  async function handleSubmit(e) {
    e.preventDefault();
    setStatus({ type: "", text: "" });

    const nextErrors = validateContactForm(form);
    if (Object.keys(nextErrors).length) {
      setErrors(nextErrors);
      setStatus({ type: "err", text: "Please fix the highlighted fields and try again." });
      return;
    }

    setErrors({});
    setSending(true);

    try {
      const token = await executeRecaptcha();
      const payload = {
        name: form.name.trim(),
        email: form.email.trim(),
        organization: form.organization.trim(),
        phone: form.phone.trim(),
        role: form.role,
        interest: form.interest,
        message: form.message.trim(),
        token,
        action: RECAPTCHA.action
      };

      const response = await fetch(`${SITE.apiBase}/api/contact`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload)
      });
      const data = await response.json();

      if (response.ok) {
        setStatus({ type: "ok", text: data.message || "Your message has been sent successfully!" });
        setForm({
          role: FORM.roles[0],
          name: "",
          organization: "",
          email: "",
          phone: "",
          interest: FORM.interests[0],
          message: ""
        });
      } else {
        setStatus({ type: "err", text: data.error || "Failed to send message." });
      }
    } catch (err) {
      console.error(err);
      setStatus({
        type: "err",
        text: err.message || "Error while sending. Please try again later."
      });
    } finally {
      setSending(false);
    }
  }

  return (
    <section className="section section--white" id="contact">
      <div className="wrap">
        <div className="contact__grid">
          <div className="contact__copy">
            <window.SectionHead
              eyebrow="Contact"
              title={<>Talk to the <span className="accent-serif">LexInTosh</span> team.</>}
              lead="Ask about MeroCase, the LegalTech API, or a partnership across Nepal's legal ecosystem. We reply within three working days."
            />
            <window.Reveal delay={160}>
              <ul className="ticks ticks--lg">
                {FORM.points.map((point) => (
                  <li key={point}><Icon name="check" size={18} />{point}</li>
                ))}
              </ul>
            </window.Reveal>
            <window.Reveal delay={220}>
              <div className="contact__aside">
                <a href={SITE.contact.mailto} className="contact__aside-link">
                  <Icon name="mail" size={16} /> {SITE.contact.email}
                </a>
                <a href={SITE.contact.linkedin} target="_blank" rel="noopener noreferrer" className="contact__aside-link">
                  <Icon name="linkedin" size={16} /> LinkedIn
                </a>
              </div>
            </window.Reveal>
          </div>

          <window.Reveal delay={100}>
            <form className="contact__form" onSubmit={handleSubmit} noValidate>
              <ContactField id="contact-role" label="I am writing as" required error={errors.role}>
                <div className="contact__radios">
                  {FORM.roles.map((role) => (
                    <label key={role} className={"contact__radio" + (form.role === role ? " contact__radio--on" : "")}>
                      <input
                        type="radio"
                        name="role"
                        value={role}
                        checked={form.role === role}
                        onChange={() => updateField("role", role)}
                      />
                      {role}
                    </label>
                  ))}
                </div>
              </ContactField>

              <div className="contact__row">
                <ContactField id="contact-name" label="Name" required error={errors.name}>
                  <ContactInput
                    id="contact-name"
                    type="text"
                    required
                    maxLength={FIELD_LIMITS.name}
                    placeholder="Full name"
                    value={form.name}
                    error={errors.name}
                    onChange={(e) => updateField("name", e.target.value)}
                  />
                </ContactField>
                <ContactField id="contact-org" label="Organization" error={errors.organization}>
                  <ContactInput
                    id="contact-org"
                    type="text"
                    maxLength={FIELD_LIMITS.organization}
                    placeholder="Firm, company, or institution"
                    value={form.organization}
                    error={errors.organization}
                    onChange={(e) => updateField("organization", e.target.value)}
                  />
                </ContactField>
              </div>

              <div className="contact__row">
                <ContactField id="contact-email" label="Email" required error={errors.email}>
                  <ContactInput
                    id="contact-email"
                    type="email"
                    required
                    maxLength={FIELD_LIMITS.email}
                    placeholder="name@example.com"
                    value={form.email}
                    error={errors.email}
                    onChange={(e) => updateField("email", e.target.value)}
                  />
                </ContactField>
                <ContactField id="contact-phone" label="Phone" error={errors.phone}>
                  <ContactInput
                    id="contact-phone"
                    type="tel"
                    maxLength={FIELD_LIMITS.phone}
                    placeholder="+977"
                    value={form.phone}
                    error={errors.phone}
                    onChange={(e) => updateField("phone", e.target.value)}
                  />
                </ContactField>
              </div>

              <ContactField id="contact-interest" label="I am interested in" required error={errors.interest}>
                <select
                  id="contact-interest"
                  className={"contact__select" + (errors.interest ? " contact__input--invalid" : "")}
                  value={form.interest}
                  onChange={(e) => updateField("interest", e.target.value)}
                  required
                  aria-invalid={errors.interest ? "true" : "false"}
                >
                  {FORM.interests.map((item) => <option key={item} value={item}>{item}</option>)}
                </select>
              </ContactField>

              <ContactField id="contact-message" label="Message" required error={errors.message}>
                <textarea
                  id="contact-message"
                  className={"contact__textarea" + (errors.message ? " contact__input--invalid" : "")}
                  required
                  rows={5}
                  maxLength={FIELD_LIMITS.message}
                  placeholder="Tell us what you are building, the size of your firm, or the timeline you have in mind."
                  value={form.message}
                  onChange={(e) => updateField("message", e.target.value)}
                  aria-invalid={errors.message ? "true" : "false"}
                />
              </ContactField>

              {status.text ? (
                <div className={"contact__status contact__status--" + status.type} role="status" aria-live="polite">
                  {status.type === "ok" ? <Icon name="check" size={16} /> : <Icon name="x" size={16} />}
                  {status.text}
                </div>
              ) : null}

              <div className="contact__submit">
                {/* <p className="contact__note">We do not share your message. We do not sell your address.</p> */}
                <Button type="submit" disabled={sending} style={{ ...window.CTA_LG, minWidth: 168 }}>
                  {sending ? "Sending..." : "Send message"}
                  {!sending ? <Icon name="arrow-right" size={18} /> : null}
                </Button>
              </div>

              <p className="contact__captcha">
                This site is protected by reCAPTCHA and the Google{" "}
                <a href="https://policies.google.com/privacy" target="_blank" rel="noopener noreferrer">Privacy Policy</a> and{" "}
                <a href="https://policies.google.com/terms" target="_blank" rel="noopener noreferrer">Terms of Service</a> apply.
              </p>
            </form>
          </window.Reveal>
        </div>
      </div>
    </section>
  );
}

window.Contact = Contact;
