"use client";

import { useState, useSyncExternalStore, type FormEvent } from "react";
import { adsConversion, api, attributionNow, fallbackMessage, hubspotIdentify } from "./api";
import { Field } from "./Field";
import { LimitedTextarea } from "./LimitedTextarea";

/*
 * /contact: "Ask a question" (POST /api/contact) and "Advertise with us" (POST /api/apply with lead_type
 * "advertiser"). Publishers apply with the application form above.
 * Support links (/contact?topic=support&product=…&cta=…#message) open "Ask a question" as a support form: the product
 * they came from, the issue and an optional site/account reference, without a monetization application (QA26-03).
 */

type Errors = Record<string, string>;
const v = (f: HTMLFormElement, n: string) => ((f.elements.namedItem(n) as HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement | null)?.value ?? "").trim();
const newId = () => (typeof crypto !== "undefined" && crypto.randomUUID ? crypto.randomUUID() : `mz-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`);

/* Brought into view and focused when it replaces the form, so a laptop-height window doesn't leave the visitor
   looking at the footer (CTA QA BUG-09). */
const showDone = (el: HTMLDivElement | null) => {
  if (!el) return;
  el.scrollIntoView({ block: "center", behavior: matchMedia("(prefers-reduced-motion: reduce)").matches ? "auto" : "smooth" });
  el.focus({ preventScroll: true });
};

function Done({ title, children, onReset }: { title: string; children: React.ReactNode; onReset: () => void }) {
  return (
    <div className="login__sent" role="status" tabIndex={-1} ref={showDone}>
      <h3>{title}</h3>
      <p>{children}</p>
      <button type="button" className="login__link" onClick={onReset}>Send another</button>
    </div>
  );
}

/* Room for the message; a support message also carries its product and site lines, within the server's 5,000. */
const MESSAGE_MAX = 4500;

/* Same rule as the server (src/lib/http.ts isEmail): checked before sending (CTA QA BUG-20). */
const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/;

function Honeypot() {
  return (
    <div className="mz-hp" aria-hidden="true">
      <label>Leave this field empty<input name="company_website" type="text" tabIndex={-1} autoComplete="off" /></label>
    </div>
  );
}

const noSubscribe = () => () => {};

function Question() {
  const [errors, setErrors] = useState<Errors>({});
  const [message, setMessage] = useState("");
  const [busy, setBusy] = useState(false);
  const [done, setDone] = useState<string | null>(null);
  /* The page is prerendered, so the URL is read in the browser; the visitor's own choices then take over. */
  const search = useSyncExternalStore(noSubscribe, () => location.search, () => "");
  const q = new URLSearchParams(search);
  const fromUrl = q.get("topic") === "support";
  const [topicChoice, setTopic] = useState<string | null>(null);
  const [productEdit, setProduct] = useState<string | null>(null);
  const topic = topicChoice ?? (fromUrl ? "support" : "general");
  const product = productEdit ?? (fromUrl ? (q.get("product") ?? "").replace(/^Question about:\s*/i, "").slice(0, 160) : "");
  const cta = (fromUrl && q.get("cta")?.slice(0, 80)) || "contact-form";
  const support = topic === "support";

  async function submit(e: FormEvent<HTMLFormElement>) {
    e.preventDefault();
    const f = e.currentTarget;
    const issue = v(f, "message"), ref = support ? v(f, "reference") : "";
    const text = support ? [`Product: ${product.trim() || "Not given"}`, ref ? `Site or account: ${ref}` : "", "", issue].filter((l, i) => l || i === 2).join("\n") : issue;
    const attribution = attributionNow();
    const src = [attribution.conversion_page || location.pathname, cta, support && product.trim() ? `product=${product.trim()}` : ""].filter(Boolean).join(" | ");
    const body = { name: v(f, "name"), email: v(f, "email"), company: v(f, "company"), topic, message: text, source: src, company_website: v(f, "company_website"), attribution };
    const errs: Errors = {};
    if (body.name.length < 2) errs.name = "Enter your name.";
    if (!body.email) errs.email = "Enter your email.";
    else if (!EMAIL.test(body.email)) errs.email = "Enter a valid email, like name@company.com.";
    if (issue.length < 10) errs.message = support ? "Describe the problem or question (at least 10 characters)." : "Write a little more so we can help (at least 10 characters).";
    setErrors(errs);
    setMessage("");
    if (Object.keys(errs).length) return;
    setBusy(true);
    const r = await api("/api/contact", "POST", body);
    setBusy(false);
    if (r.ok) return (hubspotIdentify(body.email), adsConversion(), setDone(body.email));
    setErrors(r.errors ?? {});
    if (!r.errors) setMessage(fallbackMessage(r));
  }

  if (done)
    return (
      <Done title={support ? "Sent to publisher support" : "Message sent"} onReset={() => setDone(null)}>
        Thanks. {support ? "Our publisher support team will" : "We\u2019ll"} reply to <strong>{done}</strong>, and we&rsquo;ve emailed you a copy.
      </Done>
    );
  return (
    <form className="contact-more__form" onSubmit={submit} noValidate aria-label={support ? "Publisher support" : undefined}>
      {support ? (
        <p className="contact-more__full contact-more__note">
          <strong>Publisher support.</strong> Already work with us? Tell us the product and what&rsquo;s happening. This goes to our publisher support team; you don&rsquo;t need to apply.
        </p>
      ) : null}
      <Field label="Name" name="name" autoComplete="name" error={errors.name} />
      <Field label="Email" name="email" type="email" autoComplete="email" error={errors.email} />
      <Field label="Company (optional)" name="company" autoComplete="organization" error={errors.company} />
      <div className="field">
        <label htmlFor="cm-topic">Topic</label>
        <select id="cm-topic" name="topic" value={topic} onChange={(e) => setTopic(e.target.value)}>
          <option value="general">General question</option>
          <option value="support">Publisher support</option>
          <option value="partnership">Partnership</option>
          <option value="press">Press</option>
        </select>
      </div>
      {support ? (
        <>
          <Field label="Product or account type" name="product" value={product} onChange={(e) => setProduct(e.target.value)} placeholder="e.g. Monetize Hub, Monetize Commerce, Underdog Media" maxLength={160} />
          <Field label="Site or account reference (optional)" name="reference" placeholder="example.com or your account ID" maxLength={200} />
        </>
      ) : null}
      <div className={`field contact-more__full${errors.message ? " is-invalid" : ""}`}>
        <label htmlFor="cm-message">{support ? "What do you need help with?" : "Message"}</label>
        <LimitedTextarea
          id="cm-message"
          name="message"
          rows={5}
          max={MESSAGE_MAX}
          placeholder={support ? "For example: I can't sign in, a payment is missing, or a unit isn't showing on my site." : undefined}
          aria-invalid={errors.message ? true : undefined}
          aria-describedby="cm-message-err"
        />
        <p className="field__err" id="cm-message-err">{errors.message ?? ""}</p>
      </div>
      <Honeypot />
      {message ? <p className="form__err" role="alert">{message}</p> : null}
      <button type="submit" className="mz-btn mz-btn--primary mz-btn--lg" disabled={busy}>{busy ? "Sending…" : support ? "Send to support" : "Send message"}</button>
    </form>
  );
}

function Advertiser() {
  const [errors, setErrors] = useState<Errors>({});
  const [message, setMessage] = useState("");
  const [busy, setBusy] = useState(false);
  const [done, setDone] = useState<string | null>(null);
  const [submission, setSubmission] = useState(newId);

  async function submit(e: FormEvent<HTMLFormElement>) {
    e.preventDefault();
    const f = e.currentTarget;
    const body = {
      lead_type: "advertiser",
      name: v(f, "name"), email: v(f, "email"), company: v(f, "company"), property: v(f, "website"),
      property_type: v(f, "kind"), traffic: v(f, "budget"), goal: "unsure", selected_products: v(f, "channels"),
      source: `${attributionNow().conversion_page || location.pathname} | advertiser-form`, submission_id: submission, company_website: v(f, "company_website"),
      attribution: attributionNow(),
    };
    const errs: Errors = {};
    if (body.name.length < 2) errs.name = "Enter your name.";
    if (!body.email) errs.email = "Enter your email.";
    else if (!EMAIL.test(body.email)) errs.email = "Enter a valid email, like name@company.com.";
    if (body.company.length < 2) errs.company = "Enter your company.";
    if (!body.property) errs.property = "Enter your website.";
    if (!body.property_type) errs.property_type = "Select what you advertise.";
    if (!body.traffic) errs.traffic = "Select a budget.";
    setErrors(errs);
    setMessage("");
    if (Object.keys(errs).length) return;
    setBusy(true);
    const r = await api<{ duplicate?: boolean }>("/api/apply", "POST", body);
    setBusy(false);
    if (r.ok) return (hubspotIdentify(body.email), r.duplicate || adsConversion(), setDone(body.email));
    setErrors(r.errors ?? {});
    if (!r.errors) setMessage(fallbackMessage(r));
  }

  if (done) return <Done title="Thanks, we&rsquo;ll be in touch" onReset={() => { setDone(null); setSubmission(newId()); }}>Our advertising team will contact <strong>{done}</strong> about your campaign.</Done>;
  return (
    <form className="contact-more__form" onSubmit={submit} noValidate>
      <Field label="Name" name="name" autoComplete="name" error={errors.name} />
      <Field label="Work email" name="email" type="email" autoComplete="email" error={errors.email} />
      <Field label="Company" name="company" autoComplete="organization" error={errors.company} />
      <Field label="Website" name="website" inputMode="url" placeholder="brand.com" error={errors.property} />
      <div className={`field${errors.property_type ? " is-invalid" : ""}`}>
        <label htmlFor="ad-kind">I&rsquo;m a</label>
        <select id="ad-kind" name="kind" defaultValue="" aria-invalid={errors.property_type ? true : undefined}>
          <option value="">Select</option>
          <option>Brand or advertiser</option>
          <option>Agency</option>
          <option>Ad network</option>
          <option>Other</option>
        </select>
        <p className="field__err">{errors.property_type ?? ""}</p>
      </div>
      <div className={`field${errors.traffic ? " is-invalid" : ""}`}>
        <label htmlFor="ad-budget">Monthly budget</label>
        <select id="ad-budget" name="budget" defaultValue="" aria-invalid={errors.traffic ? true : undefined}>
          <option value="">Select</option>
          <option>Less than $10K</option>
          <option>$10K to $50K</option>
          <option>$50K to $250K</option>
          <option>More than $250K</option>
        </select>
        <p className="field__err">{errors.traffic ?? ""}</p>
      </div>
      <Field label="Channels you're interested in (optional)" name="channels" placeholder="e.g. AI search, CTV, native" />
      <Honeypot />
      {message ? <p className="form__err" role="alert">{message}</p> : null}
      <button type="submit" className="mz-btn mz-btn--primary mz-btn--lg" disabled={busy}>{busy ? "Sending…" : "Talk to our advertising team"}</button>
    </form>
  );
}

export default function ContactForms() {
  const [tab, setTab] = useState<"question" | "advertise">("question");
  return (
    <div className="contact-more">
      <div className="hub-tabs" role="tablist" aria-label="Contact options">
        <button type="button" role="tab" id="cm-tab-q" aria-controls="cm-panel" aria-selected={tab === "question"} className={tab === "question" ? "is-on" : ""} onClick={() => setTab("question")}>Ask a question</button>
        <button type="button" role="tab" id="cm-tab-a" aria-controls="cm-panel" aria-selected={tab === "advertise"} className={tab === "advertise" ? "is-on" : ""} onClick={() => setTab("advertise")}>Advertise with us</button>
      </div>
      <div id="cm-panel" role="tabpanel" aria-labelledby={tab === "question" ? "cm-tab-q" : "cm-tab-a"}>
        {tab === "question" ? <Question /> : <Advertiser />}
      </div>
    </div>
  );
}
