"use client";

import Link from "@/components/Link";
import { useSearchParams } from "next/navigation";
import FormAlerts from "@/components/FormAlerts";
import FormRuntimeGate from "@/components/FormRuntimeGate";
import Icon from "@/components/Icon";
import SiteEffects from "@/components/SiteEffects";
import { channelBySlug, channels } from "@/lib/channels";
import { forgotPasswordHref, formEndpoint, loginHref, supportEmail } from "@/lib/site";

/**
 * Sign up, preset from ?channel=. It reads the URL in the browser, so the server sends /signup once, as the plain
 * form (the page's Suspense fallback). Reading searchParams on the server instead streamed a second copy of the
 * page into the HTML.
 */
export default function SignupFromUrl() {
  const channel = useSearchParams().get("channel") ?? "";
  return <SignupView slug={channelBySlug[channel] ? channel : ""} />;
}

export function SignupView({ slug = "" }: { slug?: string }) {
  const channel = slug ? channelBySlug[slug] : undefined;
  const salesLink = slug ? `/contact?channel=${slug}` : "/contact";

  return (
    <>
      <section className="u-pt-74d1e an-section">
        <div className="an-wrap an-split an-split--form">
          <div className="an-stack">
            <span className="an-eyebrow">Start advertising</span>
            <h1 className="u-fs-971d9 an-h1">Create your <span className="an-ai-text">advertiser account</span></h1>
            <p className="an-lede">Two short steps. Then our onboarding team reviews your request and emails you an invitation to set up your login.</p>
            <ol className="u-mt-8px an-path an-path--v">
              <li><strong>Tell us who you are</strong><span className="u-fs-14-5px an-muted">Work email and name</span></li>
              <li><strong>Tell us about your business</strong><span className="u-fs-14-5px an-muted">Company, website and goals</span></li>
              <li><strong>Account review</strong><span className="u-fs-14-5px an-muted">We confirm your details and eligibility, then email you an invitation</span></li>
              <li><strong>Launch</strong><span className="u-fs-14-5px an-muted">Set your password, then add billing, tracking and creative, with our help</span></li>
            </ol>
            <p className="u-fs-14-5px an-muted">Prefer to talk first? <Link href={salesLink} data-track="sales_click" data-track-location="signup_aside">Talk to Sales</Link></p>
          </div>

          <div className="an-formcard">
            <div data-form-wrap="">
              <div className="an-alert an-alert--info" role="status" data-duplicate="" hidden tabIndex={-1}>
                <Icon name="people" />
                <div>
                  <strong>We already have a request or account for this email.</strong> There’s no need to submit again. If your request was approved, use the link in your invitation email to set up access. Already set up your account? <a href={loginHref}>Log in</a> or <a href={forgotPasswordHref}>reset your password</a>. Questions? <a href={`mailto:${supportEmail}`}>{supportEmail}</a>
                </div>
              </div>
              <FormAlerts serviceTitle="We couldn’t submit your request." serviceText="Everything you entered has been kept. Please try again in a moment." />

              <form className="an-form" id="signup-form" data-form="signup" data-endpoint={formEndpoint.signup} method="post" action={formEndpoint.signup} data-hs-do-not-collect="true" noValidate>
                <div className="an-steps-mini" aria-hidden="true"><i className="is-on" data-step-dot="1" /><i data-step-dot="2" /></div>
                {channel ? (
                  <div className="an-chips"><span className="an-tag">Selected channel: {channel.name}{channel.product ? ` · ${channel.product}` : ""}</span></div>
                ) : null}
                <input type="hidden" name="access_mode" value="request" />
                <input type="hidden" name="product" value={channel?.product ?? ""} />

                <fieldset data-step="1" className="u-b-m-p-d-gap-f8a1d">
                  <legend className="u-mb-6px an-h3">Step 1 of 2 · Your details</legend>
                  <div className="an-field">
                    <label htmlFor="s-email">Work email</label>
                    <input className="an-input" id="s-email" name="email" type="email" autoComplete="email" inputMode="email" required maxLength={254} data-work-email="" data-msg-required="Enter your work email." />
                    <p className="an-field__hint">We’ll use this to send your approval decision and your invitation.</p>
                  </div>
                  <div className="an-form__grid">
                    <div className="an-field">
                      <label htmlFor="s-first">First name</label>
                      <input className="an-input" id="s-first" name="first_name" autoComplete="given-name" required maxLength={80} data-msg-required="Enter your first name." />
                    </div>
                    <div className="an-field">
                      <label htmlFor="s-last">Last name</label>
                      <input className="an-input" id="s-last" name="last_name" autoComplete="family-name" required maxLength={80} data-msg-required="Enter your last name." />
                    </div>
                  </div>
                  <div className="an-actions"><button type="button" className="an-btn an-btn--primary" data-step-next="2">Continue</button></div>
                </fieldset>

                <fieldset data-step="2" hidden className="u-b-m-p-d-gap-f8a1d">
                  <legend className="u-mb-6px an-h3">Step 2 of 2 · Your business</legend>
                  <div className="an-form__grid">
                    <div className="an-field">
                      <label htmlFor="s-co">Company</label>
                      <input className="an-input" id="s-co" name="company" autoComplete="organization" required maxLength={160} data-msg-required="Enter your company name." />
                    </div>
                    <div className="an-field">
                      <label htmlFor="s-site">Company website</label>
                      <input className="an-input" id="s-site" name="website" type="text" inputMode="url" autoComplete="url" placeholder="company.com" required maxLength={200} data-url="" data-msg-required="Enter your company website." />
                    </div>
                    <div className="an-field">
                      <label htmlFor="s-phone">Phone</label>
                      <input className="an-input" id="s-phone" name="phone" type="tel" autoComplete="tel" required data-msg-required="Enter a phone number." />
                    </div>
                    <div className="an-field">
                      <label htmlFor="s-country">Country</label>
                      <select className="an-input" id="s-country" name="country" autoComplete="country" required defaultValue="" data-msg-required="Choose your country.">
                        <option value="">Select a country</option>
                        <option value="US">United States</option>
                        <option value="CA">Canada</option>
                        <option value="GB">United Kingdom</option>
                        <option value="other">Other</option>
                      </select>
                    </div>
                    <div className="an-field">
                      <label htmlFor="s-type">I am a…</label>
                      <select className="an-input" id="s-type" name="account_type" required defaultValue="" data-msg-required="Choose one.">
                        <option value="">Select</option>
                        <option value="brand">Brand / business</option>
                        <option value="agency">Agency</option>
                        <option value="ecommerce">Ecommerce / retailer</option>
                        <option value="other">Other</option>
                      </select>
                    </div>
                    <div className="an-field">
                      <label htmlFor="s-ch">Primary channel interest <span className="an-opt">(optional)</span></label>
                      <select className="an-input" id="s-ch" name="channel_interest" defaultValue={slug}>
                        <option value="">Not sure yet</option>
                        {channels.map((c) => (
                          <option key={c.slug} value={c.slug}>{c.name}{c.product ? ` (${c.product})` : ""}</option>
                        ))}
                      </select>
                    </div>
                    <div className="an-field">
                      <label htmlFor="s-budget">Monthly media budget <span className="an-opt">(optional)</span></label>
                      <select className="an-input" id="s-budget" name="budget" defaultValue="">
                        <option value="">Select a range</option>
                        <option>Under $5,000</option>
                        <option>$5,000 – $25,000</option>
                        <option>$25,000 – $100,000</option>
                        <option>$100,000+</option>
                        <option>Not sure</option>
                      </select>
                    </div>
                  </div>
                  <div className="an-field">
                    <label className="an-consent">
                      <input type="checkbox" name="terms" value="1" required data-msg-required="Please accept the terms to continue." />
                      <span>I agree to the Advertising.net <Link href="/ad-policies" target="_blank">Ad Policies</Link> and <Link href="/privacy" target="_blank">Privacy Policy</Link>.</span>
                    </label>
                  </div>
                  <div className="an-actions">
                    <button type="button" className="an-btn an-btn--ghost" data-step-back="1">Back</button>
                    <button type="submit" className="an-btn an-btn--primary" data-submit="">Create account</button>
                  </div>
                </fieldset>
              </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 application.</h2>
              <p className="an-muted">We’ve sent a confirmation to <strong data-success-email="" />. Our onboarding team reviews new advertiser accounts, typically within 1–2 business days. If your request is approved, we’ll email you an invitation to set your password and get started.</p>
              <p className="an-muted">Your request is not an approval, and no account or campaign is active yet.</p>
              <div className="an-actions">
                <Link className="an-btn an-btn--primary" href="/solutions">Explore channels</Link>
                <Link className="an-btn an-btn--ghost" href="/team">Meet the team</Link>
              </div>
            </div>
          </div>
        </div>
      </section>

      <section className="u-smt-90px an-section an-section--paper an-section--tight" id="login">
        <div className="an-wrap">
          <div className="u-gtc-ai-cg-8a87c an-card">
            <span className="an-icon-tile"><Icon name="people" size={22} /></span>
            <div>
              <h2 className="u-fs-1-1rem an-h3">Already an advertiser?</h2>
              <p>Log in to manage campaigns and reporting.</p>
            </div>
            <a className="an-btn an-btn--ghost" href={loginHref}>Log in</a>
          </div>
        </div>
      </section>
      <FormRuntimeGate />
      <SiteEffects />
    </>
  );
}
