"use client";

import Link from "@/components/Link";
import { useSearchParams } from "next/navigation";
import Breadcrumbs, { type Crumb } from "@/components/Breadcrumbs";
import FormAlerts from "@/components/FormAlerts";
import FormRuntimeGate from "@/components/FormRuntimeGate";
import Icon from "@/components/Icon";
import SiteEffects from "@/components/SiteEffects";
import { budgets, channelBySlug, channels, goals, repBySlug } from "@/lib/channels";
import { formEndpoint, formHoneypot, signupLink, supportPhone, supportPhoneHref } from "@/lib/site";

/**
 * Talk to Sales, set up from ?rep=, ?channel=, ?industry= and ?topic=. It reads the URL in the browser, so the server
 * sends /contact once, as the general form (the page's Suspense fallback). Reading searchParams on the server
 * instead streamed a second copy of the page into the HTML. Those URLs all canonicalise to /contact.
 */
const slugOf = (v: string | null) => (v ? v.replace(/[^a-z0-9-]/g, "").slice(0, 40) : "");

export default function ContactFromUrl({ crumbs }: { crumbs: Crumb[] }) {
  const sp = useSearchParams();
  const channel = slugOf(sp.get("channel"));
  return <ContactView crumbs={crumbs} repSlug={slugOf(sp.get("rep"))} slug={channelBySlug[channel] ? channel : ""} industry={slugOf(sp.get("industry"))} topic={slugOf(sp.get("topic"))} />;
}

export function ContactView({ crumbs, repSlug = "", slug = "", industry = "", topic = "" }: { crumbs: Crumb[]; repSlug?: string; slug?: string; industry?: string; topic?: string }) {
  const rep = repBySlug[repSlug];
  const repMissing = !!repSlug && !rep;
  const channel = slug ? channelBySlug[slug] : undefined;
  const channelQuery = slug ? `?channel=${slug}` : "";
  const support = topic === "support";
  const initials = rep ? rep.name.split(" ").slice(0, 2).map((w) => w[0]).join("") : "";

  return (
    <>
      <section className="u-pt-74d1e an-section">
        <div className="an-wrap an-split an-split--form">
          <div className="an-stack">
            <Breadcrumbs items={crumbs} />
            <span className="an-eyebrow">{support ? "Support" : "Talk to Sales"}</span>
            <h1 className="u-fs-971d9 an-h1">
              {rep ? <>Connect With <span className="an-ai-text">{rep.first}</span></> : support ? <>How Can We <span className="an-ai-text">Help</span>?</> : <>Let’s Plan Your <span className="an-ai-text">Next Campaign</span></>}
            </h1>
            {support ? (
              <p className="an-lede">Tell us what you need help with, whether it’s your account, billing or a campaign, and our team will get back to you.</p>
            ) : (
              <>
                <p className="an-lede">Tell us what you’re looking to achieve. Our team will help you explore the right advertising channels, discuss your budget, and map out the next steps.</p>
                <ul className="u-mt-6px an-list-check">
                  <li>A channel mix tailored to your campaign goals</li>
                  <li>Placement examples relevant to your industry</li>
                  <li>A clear plan for getting your campaign started</li>
                </ul>
              </>
            )}
            <p className="an-muted">Prefer to talk? Call <a href={supportPhoneHref}>{supportPhone}</a>.</p>
            {support ? null : <div className="u-mt-12px an-card an-card--paper">
              <h2 className="u-fs-1-05rem an-h3">Ready to start on your own?</h2>
              <p>A sales inquiry doesn’t create an advertiser account. If you’re ready to get started, sign up to create your account.</p>
              <a className="an-link" href={signupLink(channelQuery)} data-track="signup_click" data-track-location="contact_aside">Sign Up to Advertise <Icon name="arrow" size={16} /></a>
            </div>}
          </div>

          <div className="an-formcard">
            <div data-form-wrap="">
              {rep ? (
                <div className="an-selected" aria-label="Selected team member">
                  <span className="an-initials an-initials--sm" aria-hidden="true">{initials}</span>
                  <div><small>Your inquiry goes to</small><strong>{rep.name}</strong><small>{rep.title}</small></div>
                  <Link className="an-link" href="/team#sales-team">Change</Link>
                </div>
              ) : repMissing ? (
                <div className="an-alert an-alert--info" role="status">
                  <Icon name="people" />
                  <div>The team member you selected isn’t available right now. Your inquiry will go to our sales team, who will connect you with the right person. <Link href="/team">See the team</Link></div>
                </div>
              ) : null}
              {channel ? (
                <div className="an-chips"><span className="an-tag">Interested in: {channel.name}{channel.product ? ` · ${channel.product}` : ""}</span></div>
              ) : null}

              <form className="an-form" id="sales-form" data-form="sales" data-endpoint={formEndpoint.sales} method="post" action={formEndpoint.sales} data-hs-do-not-collect="true" aria-describedby="sales-req">
                <FormAlerts serviceTitle="We couldn’t send your details just now." serviceText="Nothing was lost. Please try again in a moment." />
                <p id="sales-req" className="an-field__hint">All fields are required unless marked optional.</p>
                <div className="an-form__grid">
                  <div className="an-field">
                    <label htmlFor="f-name">Name</label>
                    <input className="an-input" id="f-name" name="name" autoComplete="name" required maxLength={120} data-msg-required="Enter your name." />
                  </div>
                  <div className="an-field">
                    <label htmlFor="f-email">Email</label>
                    {/* Any valid address, personal ones included (QA, 2026-11-12); the design had work email only. */}
                    <input className="an-input" id="f-email" name="email" type="email" autoComplete="email" required maxLength={254} aria-describedby="f-email-hint" data-msg-required="Enter your email." />
                    <p id="f-email-hint" className="an-field__hint">A work email helps us verify your business.</p>
                  </div>
                  <div className="an-field">
                    <label htmlFor="f-company">Company</label>
                    <input className="an-input" id="f-company" name="company" autoComplete="organization" required maxLength={160} data-msg-required="Enter your company name." />
                  </div>
                  <div className="an-field">
                    <label htmlFor="f-site">Company website</label>
                    <input className="an-input" id="f-site" name="website" type="text" inputMode="url" placeholder="company.com" autoComplete="url" required maxLength={200} data-url="" data-msg-required="Enter your company website." />
                  </div>
                  {/* Support asks what's wrong instead of the sales questions (goal, channels, budget). */}
                  {support ? null : <>
                  <div className="an-field is-full">
                    <label htmlFor="f-goal">Campaign goal</label>
                    <select className="an-input" id="f-goal" name="goal" required defaultValue="" data-msg-required="Choose a campaign goal.">
                      <option value="">Select a goal</option>
                      {Object.entries(goals).map(([key, label]) => <option key={key} value={key}>{label}</option>)}
                      <option value="other">Something else</option>
                    </select>
                  </div>
                  <fieldset className="u-b-m-p-cfd26 an-field is-full">
                    <legend>Channels of interest <span className="an-opt">(optional)</span></legend>
                    <div className="u-mt-8px an-checks">
                      {channels.map((c) => (
                        <label className="an-check" key={c.slug}>
                          <input type="checkbox" name="channels[]" value={c.slug} defaultChecked={c.slug === slug} />
                          <span>{c.nav}{c.product ? ` (${c.product})` : ""}</span>
                        </label>
                      ))}
                    </div>
                  </fieldset>
                  <div className="an-field">
                    <label htmlFor="f-budget">Monthly media budget <span className="an-opt">(optional)</span></label>
                    <select className="an-input" id="f-budget" name="budget" defaultValue="">
                      <option value="">Select your monthly spend</option>
                      {budgets.map((b) => <option key={b}>{b}</option>)}
                    </select>
                  </div>
                  </>}
                  <div className="an-field">
                    <label htmlFor="f-phone">Phone <span className="an-opt">(optional)</span></label>
                    <input className="an-input" id="f-phone" name="phone" type="tel" autoComplete="tel" />
                  </div>
                  <div className="an-field is-full">
                    {support ? <>
                    <label htmlFor="f-msg">How can we help?</label>
                    <textarea className="an-input" id="f-msg" name="message" rows={5} maxLength={1000} required data-msg-required="Tell us how we can help." placeholder="Your account, billing or technical question…" />
                    </> : <>
                    <label htmlFor="f-msg">Message <span className="an-opt">(optional)</span></label>
                    <textarea className="an-input" id="f-msg" name="message" rows={3} maxLength={1000} placeholder="Products, audiences, timing…" />
                    </>}
                  </div>
                </div>

                <div className="an-sr" aria-hidden="true">
                  <label htmlFor="f-fax">Leave this empty</label>
                  <input id="f-fax" name={formHoneypot} tabIndex={-1} autoComplete="off" />
                </div>
                <input type="hidden" name="rep" value={rep ? repSlug : ""} />
                <input type="hidden" name="rep_requested" value={repSlug} />
                <input type="hidden" name="channel" value={slug} />
                <input type="hidden" name="product" value={channel?.product ?? ""} />
                <input type="hidden" name="industry" value={industry} />
                <input type="hidden" name="topic" value={topic} />
                <input type="hidden" name="source" value="" />

                <p className="an-consent"><span>By submitting, you agree that Advertising.net, Inc. may contact you about your inquiry. See our <Link href="/privacy">Privacy Policy</Link>.</span></p>
                <div className="an-actions"><button type="submit" className="an-btn an-btn--primary" data-submit="">{rep ? `Send to ${rep.first}` : "Send inquiry"}</button></div>
              </form>
            </div>

            <div className="an-success" data-success="" hidden tabIndex={-1} aria-live="polite">
              <span className="an-success__icon"><Icon name="check" size={28} /></span>
              <h2 className="an-h3">Thanks<span data-success-name="" />. We’ve received your {support ? "request" : "inquiry"}.</h2>
              <p className="an-muted">{rep ? `${rep.first} will` : support ? "Someone from our team will" : "Someone from our sales team will"} email you at <strong data-success-email="" /> {support ? "to help with your request. This doesn’t create an advertiser account." : "to set up a conversation. This is a sales inquiry and doesn’t create an advertiser account."}</p>
              <div className="an-actions">
                <a className="an-btn an-btn--primary" href={signupLink(channelQuery)} data-track="signup_click" data-track-location="sales_success">Sign Up to Advertise</a>
                <Link className="an-btn an-btn--ghost" href="/solutions">Explore channels</Link>
              </div>
            </div>
          </div>
        </div>
      </section>
      <FormRuntimeGate />
      <SiteEffects />
    </>
  );
}
