// Hero: left = headline + CTAs + stat row; right = multi-step "Start your project" lead form.
// On tablet/mobile the form stacks first (top) via .hero-form order in index.html CSS.
const NS_HERO = window.AnsysDigitalDesignSystem_4543d7;

function HeroForm() {
  const { Input, Select, Textarea, Button } = NS_HERO;
  const REG = window.ANSYS_REGION || {};
  const steps = ["Contact", "Project", "Timeline"];
  const [step, setStep] = React.useState(0);
  const [sent, setSent] = React.useState(false);
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState({});
  const [f, setF] = React.useState({
    fullName: "", email: "", phone: "", company: "",
    service: "", platform: "", revenue: "", products: "",
    timeline: "", message: "", source: "", website: "", besttime: "",
  });
  const set = (k) => (e) => { const v = e.target.value; setF((p) => ({ ...p, [k]: v })); if (err[k]) setErr((p) => ({ ...p, [k]: undefined })); };
  const go = (n) => setStep(Math.max(0, Math.min(2, n)));

  const validateStep = (s) => {
    const e = {};
    if (s === 0) {
      if (!f.fullName.trim()) e.fullName = "Please enter your name.";
      if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(f.email.trim())) e.email = "Enter a valid email address.";
      if (f.phone.trim() && f.phone.replace(/[^\d]/g, "").length < 7) e.phone = "Enter a valid phone number.";
      if (!f.company.trim()) e.company = "Please enter your company or brand.";
    }
    setErr(e);
    return Object.keys(e).length === 0;
  };

  const next = () => { if (validateStep(step)) go(step + 1); };

  const submit = (ev) => {
    ev.preventDefault();
    if (step < 2) { next(); return; }
    if (!validateStep(0)) { go(0); return; }
    if (f.website) { setSent(true); return; } // honeypot: silently drop bots
    setBusy(true);
    const dial = REG.dial ? REG.dial + " " : "";
    const payload = new URLSearchParams({
      name: f.fullName, email: f.email, phone: dial + f.phone,
      company: f.company, service: f.service, platform: f.platform, revenue: f.revenue,
      products: f.products, timeline: f.timeline, message: f.message, source: f.source,
      besttime: f.besttime,
      region: REG.name || "",
    });
    // Premium enquiry brief — reads like a proposal request, not a raw form dump.
    const has = (v) => v && !/^select|^when do you want/i.test(v);
    const row = (label, v) => (has(v) ? "• " + label + ": " + v : null);
    const first = (f.fullName.trim().split(/\s+/)[0] || "there");
    const lines = [
      "*ANSYS DIGITAL* — Premium Shopify Growth Partner",
      "──────────────────────",
      "Hello Ansys Digital team,",
      "",
      "I'd like to discuss a Shopify project with you. Here are my details:",
      "",
      "*━ ABOUT ME ━*",
      row("Name", f.fullName.trim()),
      row("Brand", f.company.trim()),
      row("Email", f.email.trim()),
      f.phone.trim() ? "• Phone: " + dial + f.phone.trim() : null,
      "",
      "*━ THE PROJECT ━*",
      row("What I need", f.service),
      row("Current platform", f.platform),
      row("Monthly revenue", f.revenue),
      row("Catalogue size", f.products),
      "",
      "*━ TIMING ━*",
      row("Start timeline", f.timeline),
      row("Best time to reach me", f.besttime),
      "",
      f.message.trim() ? "*━ GOALS & CONTEXT ━*" : null,
      f.message.trim() || null,
      f.message.trim() ? "" : null,
      "──────────────────────",
      row("Enquiry from", REG.name),
      row("Heard about you via", f.source),
      "",
      "Looking forward to your reply. Thank you!",
      "— " + first,
    ].filter((l) => l !== null && l !== undefined);
    const wa = "https://wa.me/919278024499?text=" + encodeURIComponent(lines.join("\n"));

    // International route: a properly formatted business email brief.
    const mrow = (label, v) => (has(v) ? "  " + label.padEnd(24, ".") + " " + v : null);
    const mailLines = [
      "Hello Ansys Digital team,",
      "",
      "I'm exploring a Shopify project and would like to discuss it with you.",
      "Below is a summary of my requirements.",
      "",
      "ABOUT THE BUSINESS",
      "------------------",
      mrow("Contact name", f.fullName.trim()),
      mrow("Brand / company", f.company.trim()),
      mrow("Email", f.email.trim()),
      f.phone.trim() ? "  " + "Phone".padEnd(24, ".") + " " + dial + f.phone.trim() : null,
      mrow("Location", REG.name),
      "",
      "PROJECT REQUIREMENTS",
      "--------------------",
      mrow("Scope", f.service),
      mrow("Current platform", f.platform),
      mrow("Monthly revenue", f.revenue),
      mrow("Catalogue size", f.products),
      "",
      "TIMING & AVAILABILITY",
      "---------------------",
      mrow("Preferred start", f.timeline),
      mrow("Best time to reach me", f.besttime),
      "",
      f.message.trim() ? "GOALS & CONTEXT" : null,
      f.message.trim() ? "---------------" : null,
      f.message.trim() || null,
      f.message.trim() ? "" : null,
      has(f.source) ? "Found you via: " + f.source : null,
      "",
      "Please let me know your availability for an introductory call, along with",
      "an indicative scope and timeline.",
      "",
      "Kind regards,",
      f.fullName.trim() || first,
      f.company.trim(),
    ].filter((l) => l !== null && l !== undefined && l !== "");
    const subject = "Shopify project enquiry — " + (f.company.trim() || f.fullName.trim() || "New enquiry")
      + (has(f.service) ? " (" + f.service + ")" : "");
    const mail = "mailto:support@ansysdigital.com?subject=" + encodeURIComponent(subject)
      + "&body=" + encodeURIComponent(mailLines.join("\n"));
    const isIndia = (REG.code || "in") === "in";
    const done = () => { setBusy(false); setSent(true); window.open(isIndia ? wa : mail, isIndia ? "_blank" : "_self", "noopener"); };
    fetch("send.php", { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: payload })
      .then(done).catch(done); // preview has no PHP — still confirm + open WhatsApp
  };

  return (
    <div style={{ background: "var(--surface-card)", borderRadius: "var(--radius-xl)", boxShadow: "var(--shadow-xl)", border: "1px solid var(--border-subtle)", padding: "clamp(1.4rem,2.4vw,2rem)", width: "100%", maxWidth: "100%", minWidth: 0, overflow: "hidden" }}>
      {sent ? (
        <div style={{ textAlign: "center", padding: "36px 8px" }}>
          <span style={{ width: 58, height: 58, borderRadius: 99, background: "var(--success-50)", color: "var(--success-500)", display: "grid", placeItems: "center", margin: "0 auto 18px" }}><Ic name="check" size={28} stroke={2.4} /></span>
          <h3 style={{ margin: "0 0 8px", fontFamily: "var(--font-display)", fontSize: 21, fontWeight: 700 }}>Request received</h3>
          <p style={{ margin: 0, color: "var(--text-secondary)", fontSize: 14.5 }}>Thank you{f.fullName ? ", " + f.fullName.split(" ")[0] : ""} — your details are on their way to us. We'll be in touch within one business day.</p>
        </div>
      ) : (
        <React.Fragment>
          <div style={{ marginBottom: 18 }}>
            <h3 style={{ margin: 0, fontFamily: "var(--font-display)", fontSize: 22, fontWeight: 700, letterSpacing: "var(--tracking-tight)" }}>Start your project</h3>
            <p style={{ margin: "5px 0 0", fontSize: 13.5, color: "var(--text-muted)" }}>Free consultation — no commitment required</p>
          </div>
          <div style={{ display: "flex", gap: 8, marginBottom: 20 }}>
            {steps.map((s, i) => (
              <button key={s} type="button" onClick={() => { if (i <= step || validateStep(step)) go(i); }} style={{
                flex: 1, display: "flex", alignItems: "center", justifyContent: "center", gap: 7, cursor: "pointer",
                padding: "8px 6px", borderRadius: "var(--radius-md)", fontFamily: "var(--font-body)", fontSize: 12.5, fontWeight: 600,
                border: "1px solid " + (i === step ? "var(--brand)" : "var(--border-default)"),
                background: i === step ? "var(--blue-50)" : "var(--surface-card)",
                color: i === step ? "var(--brand)" : "var(--text-muted)",
              }}>
                <span style={{ width: 18, height: 18, borderRadius: 99, display: "grid", placeItems: "center", fontSize: 11, fontWeight: 700, background: i < step ? "var(--brand)" : i === step ? "var(--brand)" : "var(--neutral-200)", color: i <= step ? "#fff" : "var(--text-muted)" }}>{i < step ? "✓" : i + 1}</span>
                <span className="step-label">{s}</span>
              </button>
            ))}
          </div>
          <form onSubmit={submit} noValidate style={{ display: "flex", flexDirection: "column", gap: 15 }}>
            {/* honeypot: hidden from humans, catches bots */}
            <input type="text" tabIndex={-1} autoComplete="off" value={f.website} onChange={set("website")} aria-hidden="true" style={{ position: "absolute", left: "-9999px", width: 1, height: 1, opacity: 0 }} />
            {step === 0 ? (
              <React.Fragment>
                <Input label="Full name" name="name" placeholder={REG.code === "in" ? "Your full name" : "John Doe"} value={f.fullName} onChange={set("fullName")} error={err.fullName} required />
                <Input label="Business email" name="email" type="email" placeholder="you@company.com" value={f.email} onChange={set("email")} error={err.email} required />
                {REG.code !== "in" ? <Input label={"Phone (" + (REG.dialLabel || "") + ")"} name="phone" type="tel" placeholder={REG.phonePlaceholder || "Your phone number"} value={f.phone} onChange={set("phone")} error={err.phone} /> : null}
                <Input label="Company / brand name" name="company" placeholder="Your brand" value={f.company} onChange={set("company")} error={err.company} required />
              </React.Fragment>
            ) : step === 1 ? (
              <React.Fragment>
                <Select label="What do you need?" value={f.service} onChange={set("service")} options={["Select a service…", "New Shopify store", "Redesign / rebuild", "Migration to Shopify", "Shopify Plus", "CRO / optimization", "Performance"]} />
                <Select label="Current platform" value={f.platform} onChange={set("platform")} options={["Select your platform…", "Already on Shopify", "Not on Shopify yet"]} />
                <Select label="Monthly revenue" value={f.revenue} onChange={set("revenue")} options={["Select range…"].concat(REG.revenue || [])} />
                <Select label="Number of products" value={f.products} onChange={set("products")} options={["Select range…", "1–50", "50–500", "500–5,000", "5,000+"]} />
              </React.Fragment>
            ) : (
              <React.Fragment>
                <Select label="Timeline" value={f.timeline} onChange={set("timeline")} options={["When do you want to start?", "ASAP", "1–3 months", "3–6 months", "Just exploring"]} />
                {REG.code !== "in" ? <Select label={"Best time to reach you (" + (REG.tzLabel || "your local time") + ")"} value={f.besttime} onChange={set("besttime")} options={["Select a window…", "Morning (9am–12pm)", "Afternoon (12–4pm)", "Evening (4–7pm)", "Email only — no calls"]} /> : null}
                <Textarea label="Tell us more about your project" rows={3} value={f.message} onChange={set("message")} placeholder="Current challenges, goals, specific requirements…" />
                <Select label="How did you hear about us?" value={f.source} onChange={set("source")} options={["Select…", "Google", "Referral", "Social", "Shopify partners", "Other"]} />
              </React.Fragment>
            )}
            <div style={{ display: "flex", gap: 10, marginTop: 4 }}>
              {step > 0 ? <Button variant="secondary" type="button" onClick={() => go(step - 1)} iconLeft={<Ic name="arrow-left" size={16} />}>Back</Button> : null}
              <Button variant="primary" type="submit" fullWidth disabled={busy} iconRight={step < 2 ? <Ic name={busy ? "loader" : "arrow-right"} size={17} /> : null}>{busy ? "Sending…" : step < 2 ? "Next step" : "Get free consultation"}</Button>
            </div>
            <p style={{ margin: 0, fontSize: 12, color: "var(--text-muted)", textAlign: "center" }}>We reply within one business day. No spam, ever.</p>
          </form>
        </React.Fragment>
      )}
    </div>
  );
}

function Hero({ onCta }) {
  const { Button, Avatar } = NS_HERO;
  const REG = window.ANSYS_REGION || {};
  const stats = [
    { v: "250+", l: "Projects delivered" },
    { v: "98%", l: "Client satisfaction" },
    { v: "6+", l: "Countries served" },
    { v: "Fast", l: "Delivery & support" },
  ];
  return (
    <section id="top" style={{ position: "relative", overflow: "hidden" }}>
      <div style={{ position: "absolute", inset: 0, backgroundImage: "var(--grad-halo)", pointerEvents: "none" }} />
      <div style={{ position: "relative", maxWidth: "var(--container-wide)", margin: "0 auto", padding: "clamp(2.5rem,6vw,5rem) var(--gutter) var(--section-y)", display: "grid", gridTemplateColumns: "minmax(0,1.05fr) minmax(0,0.95fr)", gap: "clamp(2rem,4vw,4.5rem)", alignItems: "center" }} className="hero-grid">
        <div className="reveal hero-copy">
          <span style={{ display: "inline-flex", alignItems: "center", gap: 8, padding: "6px", borderRadius: "var(--radius-pill)", background: "var(--surface-card)", border: "1px solid var(--border-default)", boxShadow: "var(--shadow-xs)", marginBottom: 24 }}>
            <span style={{ background: "var(--blue-50)", color: "var(--brand)", fontFamily: "var(--font-mono)", fontSize: 11, fontWeight: 600, letterSpacing: ".04em", textTransform: "uppercase", padding: "4px 9px", borderRadius: "var(--radius-pill)" }}>{REG.eyebrow || "Shopify Plus Partner"}</span>
            <span style={{ fontSize: 13, color: "var(--text-secondary)", paddingRight: 10 }}>Premium Shopify Growth Agency</span>
          </span>
          <h1 style={{ margin: 0, fontFamily: "var(--font-display)", fontWeight: 800, fontSize: "var(--display-md)", lineHeight: "var(--leading-tight)", letterSpacing: "var(--tracking-tighter)", textWrap: "balance" }}>
            Build Shopify stores that <span style={{ position: "relative", color: "var(--brand)" }}>sell, scale &amp; grow<span style={{ position: "absolute", left: 0, right: 0, bottom: 2, height: 6, background: "var(--accent)", borderRadius: 4, opacity: .9, zIndex: -1 }} /></span>.
          </h1>
          <p style={{ margin: "20px 0 0", fontSize: 18, lineHeight: "var(--leading-snug)", color: "var(--text-secondary)", maxWidth: 500, textWrap: "pretty" }}>
            {REG.audience || "We design, develop and optimize premium Shopify stores that help businesses launch faster, convert more customers, and grow confidently."}
          </p>
          <div className="hero-cta-row" style={{ display: "flex", gap: 14, marginTop: 28, flexWrap: "wrap" }}>
            <Button variant="primary" size="lg" onClick={onCta} iconRight={<Ic name="arrow-right" size={18} />}>Book discovery call</Button>
            <Button variant="secondary" size="lg" onClick={() => { const el = document.getElementById("work"); if (el) window.scrollTo({ top: el.offsetTop - 20, behavior: "smooth" }); }} iconLeft={<Ic name="layout-grid" size={16} />}>View portfolio</Button>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 0, marginTop: 36, border: "1px solid var(--border-subtle)", borderRadius: "var(--radius-lg)", overflow: "hidden", background: "var(--surface-subtle)" }} className="hero-stats">
            {stats.map((s, i) => (
              <div key={s.l} style={{ padding: "16px 14px", borderLeft: i ? "1px solid var(--border-subtle)" : "none", textAlign: "center" }}>
                <div style={{ fontFamily: "var(--font-display)", fontWeight: 800, fontSize: 24, letterSpacing: "var(--tracking-tight)", color: "var(--text-primary)" }}>{s.v}</div>
                <div style={{ fontSize: 12, color: "var(--text-muted)", marginTop: 3 }}>{s.l}</div>
              </div>
            ))}
          </div>
        </div>
        <div className="reveal hero-form" style={{ transitionDelay: ".08s", minWidth: 0 }}>
          <HeroForm />
        </div>
      </div>
    </section>
  );
}
Object.assign(window, { Hero });