/* Contact page */

/* ---- Replace this with your actual web3forms access key ---- */
const WEB3FORMS_KEY = "f5e0597a-f4b2-4bf3-bd31-8838a14de4b8";

/* Read quiz result from localStorage (expires after 7 days) */
function getQuizResult() {
  try {
    const raw = localStorage.getItem("smbe_quiz");
    if (!raw) return null;
    const v = JSON.parse(raw);
    if (Date.now() - v.ts > 7 * 24 * 60 * 60 * 1000) return null;
    return v; // { id, label, ts }
  } catch(e) { return null; }
}

function ContactPage({ basePath }) {
  const [submitted, setSubmitted] = React.useState(false);
  const [sending, setSending] = React.useState(false);
  const [step, setStep] = React.useState(1);
  const [quizResult] = React.useState(() => getQuizResult());
  const [form, setForm] = React.useState({
    name: "",
    business: "",
    email: "",
    phone: "",
    tier: quizResult ? quizResult.id : "",
    budget: "",
    timeline: "",
    help: "",
  });
  const update = (k, v) => setForm({ ...form, [k]: v });

  const onSubmit = async (e) => {
    e.preventDefault();
    setSending(true);
    const tierLabel = TIERS.find((t) => t.id === form.tier)?.label || form.tier;
    const payload = {
      access_key: WEB3FORMS_KEY,
      subject: `New enquiry from ${form.business}`,
      name: form.name,
      email: form.email,
      phone: form.phone || "Not provided",
      business: form.business,
      tier: tierLabel,
      budget: form.budget || "Not specified",
      timeline: form.timeline || "Not specified",
      message: form.help,
      ...(quizResult ? { quiz_recommendation: quizResult.label } : {}),
    };
    try {
      const res = await fetch("https://api.web3forms.com/submit", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      });
      const data = await res.json();
      if (data.success) {
        setSubmitted(true);
      } else {
        alert("Something went wrong sending your message. Please WhatsApp or email us directly.");
      }
    } catch(err) {
      alert("Something went wrong sending your message. Please WhatsApp or email us directly.");
    } finally {
      setSending(false);
    }
  };

  return (
    <>
      <SiteNav current="contact" basePath={basePath} />
      <main>
        <section className="contact-hero" data-screen-label="01 Contact Hero">
          <div className="contact-hero-bg">
            <div className="ch-blob ch-blob-g" />
            <div className="ch-blob ch-blob-o" />
          </div>
          <div className="container contact-hero-inner">
            <div className="contact-hero-left">
              <span className="eyebrow">Let's chat</span>
              <h1 className="h-display contact-h1">
                Tell us what<br />
                <span className="accent-green">you need</span>.
              </h1>
              <p className="lede contact-lede">
                A 20-minute call, free. We'll listen, ask good questions, and tell you honestly whether we're the right fit. If we're not, we'll point you somewhere better.
              </p>

              <div className="contact-channels">
                <a className="contact-channel" href="https://wa.me/447939188385?text=Hi%20-%20I%27d%20like%20to%20chat%20about%20my%20business" target="_blank" rel="noreferrer">
                  <div className="cc-icon" style={{ background: "#25d366" }}><Icon.whatsapp /></div>
                  <div>
                    <div className="cc-label">WhatsApp</div>
                    <div className="cc-v">+44 7939 188385</div>
                    <div className="cc-sub">Fastest. Reply within hours.</div>
                  </div>
                </a>
                <a className="contact-channel" href="mailto:hello@smbemore.com">
                  <div className="cc-icon" style={{ background: "var(--green-deep)" }}>@</div>
                  <div>
                    <div className="cc-label">Email</div>
                    <div className="cc-v">hello@smbemore.com</div>
                    <div className="cc-sub">If you'd rather write it all out.</div>
                  </div>
                </a>
                <a className="contact-channel" href="#form">
                  <div className="cc-icon" style={{ background: "var(--orange-warm)" }}>✎</div>
                  <div>
                    <div className="cc-label">Project form</div>
                    <div className="cc-v">Contact Us →</div>
                    <div className="cc-sub">Tell us more, we'll come back with a plan.</div>
                  </div>
                </a>
              </div>

              <div className="contact-meta">
                <div><strong>Hours</strong><span>Mon–Fri · 9am–6pm BST</span></div>
                <div><strong>Reply within</strong><span>A few hours, usually faster</span></div>
                <div><strong>Based in</strong><span>Kent · working everywhere</span></div>
              </div>
            </div>

            <div className="contact-hero-right" id="form">
              {!submitted ? (
                <form className="contact-form" onSubmit={onSubmit}>
                  <div className="cf-progress">
                    {[1, 2, 3].map((n) => (
                      <div key={n} className={"cf-p-step" + (step >= n ? " on" : "") + (step === n ? " current" : "")}>
                        <div className="cf-p-num">{step > n ? "✓" : n}</div>
                        <div className="cf-p-l">{["About you", "Your project", "Budget & timing"][n - 1]}</div>
                      </div>
                    ))}
                  </div>

                  {step === 1 && (
                    <div className="cf-step">
                      <h2 className="h-2">Hi, who are we talking to?</h2>
                      <p className="cf-step-lede">Just the basics — we'll dig deeper on the call.</p>
                      <label>
                        <span>Your name *</span>
                        <input value={form.name} onChange={(e) => update("name", e.target.value)} required placeholder="e.g. Sarah Beckett" />
                      </label>
                      <label>
                        <span>Business name *</span>
                        <input value={form.business} onChange={(e) => update("business", e.target.value)} required placeholder="e.g. Beckett &amp; Sons Plumbing" />
                      </label>
                      <div className="cf-row">
                        <label>
                          <span>Email *</span>
                          <input type="email" value={form.email} onChange={(e) => update("email", e.target.value)} required placeholder="you@business.co.uk" />
                        </label>
                        <label>
                          <span>Phone (optional)</span>
                          <input type="tel" value={form.phone} onChange={(e) => update("phone", e.target.value)} placeholder="07..." />
                        </label>
                      </div>
                      <div className="cf-actions">
                        <button type="button" className="btn btn-accent btn-lg" onClick={() => setStep(2)} disabled={!form.name || !form.business || !form.email}>
                          Next: your project <Icon.arrow />
                        </button>
                      </div>
                    </div>
                  )}

                  {step === 2 && (
                    <div className="cf-step">
                      <h2 className="h-2">What's the project about?</h2>
                      <p className="cf-step-lede">Pick a tier and tell us a bit. Don't worry about getting it perfect.</p>
                      {quizResult && (
                        <div className="cf-quiz-banner">
                          <span className="cfqb-icon"><Icon.sparkle /></span>
                          Based on your quiz, we've pre-selected <strong>{quizResult.label}</strong> for you — feel free to change it.
                        </div>
                      )}
                      <div className="cf-tier-grid">
                        {TIERS.map((t) => (
                          <button
                            type="button"
                            key={t.id}
                            className={"cf-tier" + (form.tier === t.id ? " on" : "")}
                            onClick={() => update("tier", t.id)}
                            style={{"--c": t.color, "--bg": t.bg}}
                          >
                            <div className="cf-tier-icon">{React.createElement(Icon[t.icon])}</div>
                            <div className="cf-tier-label">{t.label}</div>
                            <div className="cf-tier-price">{t.price}</div>
                          </button>
                        ))}
                      </div>
                      <label>
                        <span>What do you need help with? *</span>
                        <textarea
                          value={form.help}
                          onChange={(e) => update("help", e.target.value)}
                          required
                          rows="5"
                          placeholder="A new website, more leads, an admin system, an AI assistant... A sentence or two is plenty."
                        />
                      </label>
                      <div className="cf-actions">
                        <button type="button" className="btn btn-ghost btn-lg" onClick={() => setStep(1)}>
                          Back
                        </button>
                        <button type="button" className="btn btn-accent btn-lg" onClick={() => setStep(3)} disabled={!form.tier || !form.help}>
                          Next: budget & timing <Icon.arrow />
                        </button>
                      </div>
                    </div>
                  )}

                  {step === 3 && (
                    <div className="cf-step">
                      <h2 className="h-2">Budget and timing</h2>
                      <p className="cf-step-lede">Rough is fine. We'll confirm everything on the call.</p>
                      <div className="cf-pick">
                        <span className="cf-pick-l">Budget</span>
                        <div className="cf-pick-chips">
                          {["Under £2.5k", "£2.5k–£5k", "£5k–£10k", "£10k+", "Not sure yet"].map((b) => (
                            <button type="button" key={b} className={"cf-chip" + (form.budget === b ? " on" : "")} onClick={() => update("budget", b)}>{b}</button>
                          ))}
                        </div>
                      </div>
                      <div className="cf-pick">
                        <span className="cf-pick-l">When would you like this live?</span>
                        <div className="cf-pick-chips">
                          {["ASAP", "1–2 months", "3–6 months", "Just exploring"].map((b) => (
                            <button type="button" key={b} className={"cf-chip" + (form.timeline === b ? " on" : "")} onClick={() => update("timeline", b)}>{b}</button>
                          ))}
                        </div>
                      </div>
                      <div className="cf-actions">
                        <button type="button" className="btn btn-ghost btn-lg" onClick={() => setStep(2)}>
                          Back
                        </button>
                        <button type="submit" className="btn btn-accent btn-lg" disabled={sending}>
                          {sending ? "Sending…" : <><span>Send enquiry</span> <Icon.arrow /></>}
                        </button>
                      </div>
                    </div>
                  )}

                  <div className="cf-foot">
                    Or just <a href="https://wa.me/447939188385?text=Hi%20SMBeMore%2C%20I%27d%20like%20to%20chat%20about%20my%20business" target="_blank" rel="noreferrer">message us on WhatsApp</a> — it's faster.
                  </div>
                </form>
              ) : (
                <div className="contact-success">
                  <div className="cs-icon"><Icon.check /></div>
                  <h2 className="h-1">Got it — thanks {form.name.split(" ")[0]}.</h2>
                  <p className="lede">We'll be in touch within a few hours, usually faster. In the meantime, here's our WhatsApp if you'd rather chat now.</p>
                  <div className="cs-summary">
                    <div className="cs-row"><span>Business</span><strong>{form.business}</strong></div>
                    <div className="cs-row"><span>Looking at</span><strong>{TIERS.find(t => t.id === form.tier)?.label || "—"}</strong></div>
                    <div className="cs-row"><span>Budget</span><strong>{form.budget || "—"}</strong></div>
                    <div className="cs-row"><span>Timeline</span><strong>{form.timeline || "—"}</strong></div>
                  </div>
                  <div className="cs-actions">
                    <a className="btn btn-whatsapp btn-lg" href="https://wa.me/447939188385?text=Hi%20SMBeMore%2C%20I%27d%20like%20to%20chat%20about%20my%20business" target="_blank" rel="noreferrer">
                      <Icon.whatsapp /> Open WhatsApp
                    </a>
                    <a className="btn btn-ghost btn-lg" href={basePath + "index.html"}>
                      Back to home <Icon.arrow />
                    </a>
                  </div>
                </div>
              )}
            </div>
          </div>
        </section>

        <section className="contact-trust" data-screen-label="02 Trust">
          <div className="container">
            <div className="ct-trust-grid">
              <div className="ct-trust-item">
                <div className="ct-trust-v"><Counter to={6} /></div>
                <div className="ct-trust-l">years building for small businesses</div>
              </div>
              <div className="ct-trust-item">
                <div className="ct-trust-v"><Counter to={84} prefix="+" /></div>
                <div className="ct-trust-l">projects shipped &amp; counting</div>
              </div>
              <div className="ct-trust-item">
                <div className="ct-trust-v"><Counter to={2} suffix="h" /></div>
                <div className="ct-trust-l">average response time</div>
              </div>
              <div className="ct-trust-item">
                <div className="ct-trust-v">★ <Counter to={4.9} decimals={1} /></div>
                <div className="ct-trust-l">average client rating</div>
              </div>
            </div>
          </div>
        </section>
      </main>
      <SiteFooter basePath={basePath} />
    </>
  );
}

window.ContactPage = ContactPage;
