"use client";
import { FormEvent, useMemo, useState } from "react";
import { CANADIAN_VEHICLE_CATALOG, displayVehicleName } from "../lib/canadian-vehicle-catalog";
type FormData = {
    condition: string;
    year: string;
    yearMin: string;
    yearMax: string;
    make: string;
    model: string;
    trim: string;
    exteriorColor: string;
    exteriorColorFlexible: boolean;
    interiorColor: string;
    mustHaveOptions: string;
    maxMileage: string;
    mileageMin: string;
    mileageMax: string;
    targetBudget: string;
    budgetMin: string;
    budgetMax: string;
    flexibility: string;
    location: string;
    postalCode: string;
    notes: string;
    name: string;
    email: string;
    phone: string;
    website: string;
    consent: boolean;
};
const initialForm: FormData = {
    condition: "New",
    year: "",
    yearMin: "",
    yearMax: "",
    make: "",
    model: "",
    trim: "",
    exteriorColor: "",
    exteriorColorFlexible: true,
    interiorColor: "",
    mustHaveOptions: "",
    maxMileage: "",
    mileageMin: "",
    mileageMax: "",
    targetBudget: "",
    budgetMin: "",
    budgetMax: "",
    flexibility: "Exact match only",
    location: "",
    postalCode: "",
    notes: "",
    name: "",
    email: "",
    phone: "",
    website: "",
    consent: false,
};
const faqs = [
    {
        question: "What exactly do I receive?",
        answer: "A concise research summary with the best available price we found, the dealer and location, the matching vehicle specifications, and relevant pricing notes available at the time of research.",
    },
    {
        question: "Do dealerships pay to be recommended?",
        answer: "No. Beat My Car Quote currently receives no commissions or referral fees from dealerships. Your CAD $50 research fee is how we are paid.",
    },
    {
        question: "Do you sell or finance the vehicle?",
        answer: "No. We are an independent vehicle-pricing research service, not a dealership. You decide whether to contact and purchase directly from the dealer we identify.",
    },
    {
        question: "Is the dealer price guaranteed?",
        answer: "Dealer prices and inventory can change. We date every recommendation and explain any known conditions, but the dealer must confirm final pricing and availability before purchase.",
    },
    {
        question: "What if my exact specification is unavailable?",
        answer: "Tell us how flexible you are. When an exact match cannot be found, we can identify the closest useful alternative and clearly explain the differences.",
    },
];
function scrollToRequest() {
    document.getElementById("request")?.scrollIntoView({ behavior: "smooth" });
}
export default function HomePage() {
    const [step, setStep] = useState(1);
    const [form, setForm] = useState<FormData>(initialForm);
    const [error, setError] = useState("");
    const [loading, setLoading] = useState(false);
    const rangeSearch = form.condition !== "New";
    const makes = useMemo(() => Object.keys(CANADIAN_VEHICLE_CATALOG).sort(), []);
    const modelEntries = useMemo(() => Object.entries(CANADIAN_VEHICLE_CATALOG[form.make] || {}), [form.make]);
    const selectedModel = modelEntries.find(([key]) => displayVehicleName(key) === form.model);
    const trims = selectedModel?.[1] || [];
    const currentYear = new Date().getFullYear();
    const newYears = [currentYear + 1, currentYear, currentYear - 1].map(String);
    const usedYears = Array.from({ length: currentYear - 1989 }, (_, index) => String(currentYear - index));
    const vehicleSummary = useMemo(() => {
        const years = rangeSearch ? [form.yearMin, form.yearMax].filter(Boolean).join("–") : form.year;
        return [years, form.make, form.model, form.trim].filter(Boolean).join(" ") || "Your vehicle";
    }, [form.year, form.yearMin, form.yearMax, form.make, form.model, form.trim, rangeSearch]);
    function update<K extends keyof FormData>(key: K, value: FormData[K]) {
        setForm((current) => ({ ...current, [key]: value }));
        if (error)
            setError("");
    }
    function changeMake(make: string) { setForm((current) => ({ ...current, make, model: "", trim: "" })); setError(""); }
    function changeModel(model: string) { setForm((current) => ({ ...current, model, trim: "" })); setError(""); }
    function formatCurrency(key: "budgetMin" | "budgetMax") { const raw = form[key].replace(/[$,\sA-Z]/gi, ""); const amount = Number(raw); if (Number.isFinite(amount) && raw) update(key, new Intl.NumberFormat("en-CA", { style: "currency", currency: "CAD" }).format(amount)); }
    function validateStep(currentStep: number) {
        if (currentStep === 1 && ((!rangeSearch && !form.year) || (rangeSearch && (!form.yearMin || !form.yearMax)) || !form.make || !form.model)) {
            return rangeSearch ? "Select the year range, make, and model to continue." : "Select the model year, make, and model to continue.";
        }
        if (currentStep === 1 && rangeSearch && Number(form.yearMin) > Number(form.yearMax)) return "The starting model year cannot be later than the ending model year.";
        if (currentStep === 1 && !form.exteriorColorFlexible && !form.exteriorColor.trim()) return "Enter your preferred exterior colour, or select that you are flexible on colour.";
        if (currentStep === 2 && rangeSearch && form.mileageMin && form.mileageMax && Number(form.mileageMin.replace(/[,\s]/g, "")) > Number(form.mileageMax.replace(/[,\s]/g, ""))) return "The minimum mileage cannot exceed the maximum mileage.";
        if (currentStep === 2 && rangeSearch && form.budgetMin && form.budgetMax && Number(form.budgetMin.replace(/[$,\sA-Z]/gi, "")) > Number(form.budgetMax.replace(/[$,\sA-Z]/gi, ""))) return "The minimum budget cannot exceed the maximum budget.";
        if (currentStep === 2 && (!form.location.trim() || !form.postalCode.trim())) {
            return "Add your city or region and postal code so we can evaluate the right market.";
        }
        if (currentStep === 3 &&
            (!form.name.trim() || !/^\S+@\S+\.\S+$/.test(form.email) || !form.consent)) {
            return "Add your name and a valid email, then accept the service terms.";
        }
        return "";
    }
    function nextStep() {
        const message = validateStep(step);
        if (message) {
            setError(message);
            return;
        }
        setError("");
        setStep((current) => Math.min(3, current + 1));
        document.getElementById("request")?.scrollIntoView({ behavior: "smooth", block: "start" });
    }
    async function submitRequest(event: FormEvent<HTMLFormElement>) {
        event.preventDefault();
        const message = validateStep(3);
        if (message) {
            setError(message);
            return;
        }
        setLoading(true);
        setError("");
        try {
            const response = await fetch("/api/create-checkout", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify(form),
            });
            const result = (await response.json()) as {
                url?: string;
                error?: string;
            };
            if (!response.ok || !result.url) {
                throw new Error(result.error || "Checkout could not be started. Please try again.");
            }
            window.location.assign(result.url);
        }
        catch (requestError) {
            setError(requestError instanceof Error ? requestError.message : "Checkout could not be started.");
            setLoading(false);
        }
    }
    return (<main>
      <header className="site-header">
        <a className="brand" href="#top" aria-label="Beat My Car Quote home">
          <img src="/logo.svg" alt="Beat My Car Quote"/>
        </a>
        <nav aria-label="Primary navigation">
          <a href="#how-it-works">How it works</a>
          <a href="#what-you-get">What you get</a>
          <a href="#faq">FAQ</a>
        </nav>
        <button className="button button-small" onClick={scrollToRequest}>Start my search</button>
      </header>

      <section className="hero" id="top">
        <div className="hero-copy">
          <div className="eyebrow"><span /> Independent vehicle price research</div>
          <h1>The car you want.<br /><em>A price you’ll like.</em></h1>
          <p className="hero-lede">
            Tell us exactly what you want. We research dealer pricing across the market and return the best available offers—clearly compared and ready for you to act on.
          </p>
          <div className="hero-actions">
            <button className="button" onClick={scrollToRequest}>Find my best price <span aria-hidden="true">→</span></button>
            <a className="button-secondary hero-secondary-action" href="#how-it-works">See how it works</a>
          </div>
          <p className="modern-price-note"><strong>CAD $50</strong><span aria-hidden="true" /> Results within 2 business days</p>
        </div>

        <div className="modern-hero-demo" aria-label="Example customer request progress">
          <div className="modern-demo-top"><span>Your request</span><strong><i /> Research underway</strong></div>
          <div className="modern-quote-card">
            <span className="card-kicker">Vehicle brief</span>
            <h3>2026 BMW X3 xDrive30</h3>
            <p>Alpine White · Premium package · Ontario</p>
            <div className="modern-progress" aria-label="Two of three research stages complete"><span /><span /><span /></div>
            <div className="modern-demo-details">
              <div><span>Dealers contacted</span><strong>Multiple locations</strong></div>
              <div><span>Quote review</span><strong>All-in pricing</strong></div>
            </div>
            <div className="modern-demo-result">
              <div><span>What you receive</span><strong>Lowest offers + dealer contacts</strong></div>
              <b aria-hidden="true">✓</b>
            </div>
          </div>
        </div>
      </section>

      <section className="trust-band">
        <p className="buyer-first-message">We work for the buyer.</p>
        <strong><span>✓</span> No referral fees</strong><i />
        <strong><span>✓</span> No paid placements</strong><i />
        <strong><span>✓</span> You buy directly</strong>
      </section>

      <section className="section how" id="how-it-works">
        <div className="section-heading">
          <span className="section-number">01</span>
          <div><p className="eyebrow-text">Simple by design</p><h2>A better way to find the right deal.</h2></div>
        </div>
        <div className="steps-grid">
          <article><span>1</span><h3>Build your exact brief</h3><p>Choose the year, make, model, trim, colour, options, location and acceptable alternatives.</p></article>
          <article><span>2</span><h3>We compare the market</h3><p>Relevant dealers provide pricing while we review availability, fees and conditions.</p></article>
          <article><span>3</span><h3>Receive the best options</h3><p>Get the lowest available offers, dealer details and practical guidance within two business days.</p></article>
        </div>
      </section>

      <section className="section report-section" id="what-you-get">
        <div className="report-copy">
          <span className="section-number">02</span>
          <p className="eyebrow-text">Clarity, not clutter</p>
          <h2>A decision-ready answer.</h2>
          <p>We turn your request into a concise, useful recommendation—so you know what we found, where we found it, and what to confirm before you buy.</p>
          <ul className="included-list">
            <li><span>01</span> Best available price found</li>
            <li><span>02</span> Dealer name and location</li>
            <li><span>03</span> Matching specification details</li>
            <li><span>04</span> Known fees and pricing conditions</li>
            <li><span>05</span> Closest alternative when useful</li>
          </ul>
        </div>
        <div className="report-preview">
          <div className="paper-edge"/>
          <div className="report-title"><img src="/brand-icon.svg" alt=""/><div><small>PRIVATE RESEARCH BRIEF</small><strong>Best-price recommendation</strong></div></div>
          <div className="report-vehicle"><span>Requested vehicle</span><strong>Your exact specification</strong><p>Trim · Options · Colour · Purchase location</p></div>
          <div className="report-row"><span>Best available offer</span><b>Price disclosed in report</b></div>
          <div className="report-row"><span>Dealer &amp; location</span><b>Direct purchasing details</b></div>
          <div className="report-note"><span>Independent note</span><p>Dealer pricing and inventory remain subject to confirmation at the time of purchase.</p></div>
        </div>
      </section>

      <section className="section request-section" id="request">
        <div className="request-intro">
          <span className="section-number light">03</span>
          <p className="eyebrow-text coral">Start your search</p>
          <h2>Tell us what’s in your driveway next.</h2>
          <p>Complete your vehicle brief and pay the fixed CAD $50 research fee securely through Stripe.</p>
          <div className="promise-card">
            <span>What happens next</span>
            <strong>Your recommendation arrives within two business days.</strong>
            <p>We’ll use the email you provide for delivery and any essential clarification.</p>
          </div>
        </div>

        <div className="form-shell">
          <div className="form-progress" aria-label={`Step ${step} of 3`}>
            {[1, 2, 3].map((item) => <span key={item} className={item <= step ? "active" : ""}/>)}
          </div>
          <div className="form-meta"><span>STEP {step} OF 3</span><strong>{step === 1 ? "The vehicle" : step === 2 ? "Your preferences" : "Review & payment"}</strong></div>

          <form onSubmit={submitRequest} noValidate>
            {step === 1 && (<fieldset>
                <legend>Let’s start with the exact car.</legend>
                <p className="field-help">Required fields are marked with an asterisk.</p>
                <div className="field-grid three">
                  <label><span>Condition *</span><select value={form.condition} onChange={(e) => setForm((current) => ({ ...current, condition: e.target.value, year: "", yearMin: "", yearMax: "" }))}><option>New</option><option>Used</option><option>Either</option></select></label>
                  {!rangeSearch ? <label><span>Model year *</span><select value={form.year} onChange={(e) => update("year", e.target.value)}><option value="">Select year</option>{newYears.map((year) => <option key={year}>{year}</option>)}</select></label> : <><label><span>Oldest model year *</span><select value={form.yearMin} onChange={(e) => update("yearMin", e.target.value)}><option value="">Select year</option>{usedYears.map((year) => <option key={year}>{year}</option>)}</select></label><label><span>Newest model year *</span><select value={form.yearMax} onChange={(e) => update("yearMax", e.target.value)}><option value="">Select year</option>{usedYears.map((year) => <option key={year}>{year}</option>)}</select></label></>}
                  <label><span>Make *</span><select value={form.make} onChange={(e) => changeMake(e.target.value)}><option value="">Select Canadian-market make</option>{makes.map((make) => <option key={make}>{make}</option>)}</select></label>
                </div>
                <div className="field-grid two">
                  <label><span>Model *</span><select value={form.model} disabled={!form.make} onChange={(e) => changeModel(e.target.value)}><option value="">{form.make ? "Select model" : "Select a make first"}</option>{modelEntries.map(([key]) => <option key={key} value={displayVehicleName(key)}>{displayVehicleName(key)}</option>)}</select></label>
                  <label><span>Trim</span><select value={form.trim} disabled={!form.model} onChange={(e) => update("trim", e.target.value)}><option value="">{form.model ? "Any trim / select trim" : "Select a model first"}</option>{trims.map((trim) => <option key={trim}>{trim}</option>)}</select></label>
                </div>
                <p className="field-help">Make, model and trim choices are limited to the maintained Canadian-market catalog. Exact model-year availability is confirmed during research.</p>
                <div className="field-grid two">
                  <label><span>Preferred exterior colour</span><input placeholder="e.g. Black, blue, or white" value={form.exteriorColor} onChange={(e) => update("exteriorColor", e.target.value)}/></label>
                  <label><span>Interior colour</span><input placeholder="First choice or acceptable colours" value={form.interiorColor} onChange={(e) => update("interiorColor", e.target.value)}/></label>
                </div>
                <fieldset className="colour-flexibility-field">
                  <legend>Are you flexible on exterior colour?</legend>
                  <label><input type="radio" name="exteriorColorFlexible" checked={form.exteriorColorFlexible} onChange={() => update("exteriorColorFlexible", true)}/><span>Yes — match all available colours</span></label>
                  <label><input type="radio" name="exteriorColorFlexible" checked={!form.exteriorColorFlexible} onChange={() => update("exteriorColorFlexible", false)}/><span>No — match only my preferred colour</span></label>
                  <p>Leaving the preferred colour blank automatically means that any exterior colour is acceptable.</p>
                </fieldset>
              </fieldset>)}

            {step === 2 && (<fieldset>
                <legend>Set the boundaries for the search.</legend>
                <div className="field-grid two">
                  <label><span>Must-have options</span><textarea rows={3} placeholder="Packages, drivetrain, engine, technology…" value={form.mustHaveOptions} onChange={(e) => update("mustHaveOptions", e.target.value)}/></label>
                  <label><span>Additional notes</span><textarea rows={3} placeholder="Anything else that would affect your decision" value={form.notes} onChange={(e) => update("notes", e.target.value)}/></label>
                </div>
                {rangeSearch ? <><div className="field-grid two"><label><span>Minimum mileage</span><input inputMode="numeric" placeholder="0" value={form.mileageMin} onChange={(e) => update("mileageMin", e.target.value.replace(/\D/g, ""))}/></label><label><span>Maximum mileage</span><input inputMode="numeric" placeholder="80,000" value={form.mileageMax} onChange={(e) => update("mileageMax", e.target.value.replace(/\D/g, ""))}/></label></div><div className="field-grid two"><label><span>Minimum budget</span><input inputMode="decimal" placeholder="$20,000.00" value={form.budgetMin} onFocus={() => update("budgetMin", form.budgetMin.replace(/[$,\sA-Z]/gi, ""))} onChange={(e) => update("budgetMin", e.target.value)} onBlur={() => formatCurrency("budgetMin")}/></label><label><span>Maximum budget</span><input inputMode="decimal" placeholder="$45,000.00" value={form.budgetMax} onFocus={() => update("budgetMax", form.budgetMax.replace(/[$,\sA-Z]/gi, ""))} onChange={(e) => update("budgetMax", e.target.value)} onBlur={() => formatCurrency("budgetMax")}/></label></div></> : <div className="field-grid two"><label><span>Maximum mileage</span><input disabled value="New vehicle" /></label><label><span>Target budget</span><input inputMode="decimal" placeholder="$50,000.00" value={form.targetBudget} onFocus={() => update("targetBudget", form.targetBudget.replace(/[$,\sA-Z]/gi, ""))} onChange={(e) => update("targetBudget", e.target.value)} onBlur={() => { const amount = Number(form.targetBudget.replace(/[$,\sA-Z]/gi, "")); if (Number.isFinite(amount) && form.targetBudget) update("targetBudget", new Intl.NumberFormat("en-CA", { style: "currency", currency: "CAD" }).format(amount)); }}/></label></div>}
                <label className="full-field"><span>How flexible is the specification?</span><select value={form.flexibility} onChange={(e) => update("flexibility", e.target.value)}><option>Exact match only</option><option>Show close alternatives</option><option>Price matters more than exact specification</option></select></label>
                <div className="field-grid two">
                  <label><span>Your city / region *</span><input placeholder="e.g. Toronto, Ontario" value={form.location} onChange={(e) => update("location", e.target.value)}/></label>
                  <label><span>Postal code *</span><input autoComplete="postal-code" placeholder="e.g. M5V 2T6" value={form.postalCode} onChange={(e) => update("postalCode", e.target.value)}/></label>
                </div>
              </fieldset>)}

            {step === 3 && (<fieldset>
                <legend>Review your brief and continue to payment.</legend>
                <div className="review-card"><span>VEHICLE REQUEST</span><strong>{vehicleSummary}</strong><p>{form.exteriorColorFlexible ? `${form.exteriorColor ? `${form.exteriorColor} preferred · ` : ""}Any exterior colour accepted` : form.exteriorColor} · {form.location}</p><button type="button" onClick={() => setStep(1)}>Edit vehicle</button></div>
                <div className="field-grid two">
                  <label><span>Your name *</span><input autoComplete="name" value={form.name} onChange={(e) => update("name", e.target.value)}/></label>
                  <label><span>Email for your report *</span><input type="email" autoComplete="email" placeholder="you@example.com" value={form.email} onChange={(e) => update("email", e.target.value)}/></label>
                </div>
                <label className="full-field"><span>Phone number</span><input type="tel" autoComplete="tel" placeholder="Optional" value={form.phone} onChange={(e) => update("phone", e.target.value)}/></label>
                <label className="honeypot" aria-hidden="true">Website<input tabIndex={-1} autoComplete="off" value={form.website} onChange={(e) => update("website", e.target.value)}/></label>
                <div className="payment-summary"><div><span>Independent vehicle price research</span><small>Delivered within two business days</small></div><strong>CAD $50</strong></div>
                <label className="check-field"><input type="checkbox" checked={form.consent} onChange={(e) => update("consent", e.target.checked)}/><span>I agree to the <a href="/terms" target="_blank">service terms</a> and <a href="/privacy" target="_blank">privacy policy</a>, and understand that dealer pricing and availability require dealer confirmation.</span></label>
              </fieldset>)}

            {error && <div className="form-error" role="alert">{error}</div>}

            <div className="form-actions">
              {step > 1 && <button type="button" className="button-secondary" onClick={() => { setError(""); setStep((current) => current - 1); }}>Back</button>}
              {step < 3 ? <button type="button" className="button form-next" onClick={nextStep}>Continue <span aria-hidden="true">→</span></button> : <button type="submit" className="button form-next" disabled={loading}>{loading ? "Opening secure checkout…" : "Continue to secure payment →"}</button>}
            </div>
            {step === 3 && <p className="secure-note"><span>●</span> Payment is processed securely by Stripe. We never receive your card details.</p>}
          </form>
        </div>
      </section>

      <section className="section faq-section" id="faq">
        <div className="section-heading"><span className="section-number">04</span><div><p className="eyebrow-text">Good questions</p><h2>Know before you search.</h2></div></div>
        <div className="faq-list">{faqs.map((faq) => <details key={faq.question}><summary>{faq.question}<span>+</span></summary><p>{faq.answer}</p></details>)}</div>
      </section>

      <section className="final-cta">
        <img src="/brand-icon.svg" alt=""/>
        <h2>One request. One clear recommendation.</h2>
        <p>Stop wondering whether there’s a better deal somewhere else.</p>
        <button className="button" onClick={scrollToRequest}>Start my CAD $50 search →</button>
      </section>

      <footer>
        <div className="footer-brand"><img src="/logo-reversed.svg" alt="Beat My Car Quote"/><p>Independent vehicle price research for buyers who would rather know.</p></div>
        <div><strong>Explore</strong><a href="#how-it-works">How it works</a><a href="#what-you-get">What you get</a><a href="#faq">FAQ</a></div>
        <div><strong>Legal</strong><a href="/terms">Terms</a><a href="/privacy">Privacy</a><a href="mailto:hello@beatmycarquote.com">Contact</a></div>
        <div className="footer-disclosure"><strong>Independent by design</strong><p>We are not a dealership and currently receive no dealer commissions or referral fees.</p></div>
        <small>© {new Date().getFullYear()} Beat My Car Quote. All rights reserved.</small>
      </footer>
    </main>);
}
