// wizard.jsx, interactive property-manager discovery flow + confirmation
const STEPS = [
  {
    qic: "home", q: "What's in your portfolio?",
    sub: "So we tailor everything to the kind of sites you manage.",
    opts: [
      { t: "HOAs & residential communities", d: "" },
      { t: "Office & corporate campuses", d: "" },
      { t: "Retail & mixed-use", d: "" },
      { t: "Industrial & warehouse", d: "" },
    ],
  },
  {
    qic: "layers", q: "How many properties do you oversee?",
    sub: "A rough number helps us right-size the crew and routing.",
    opts: [
      { t: "1 to 3 sites", d: "" },
      { t: "4 to 10 sites", d: "" },
      { t: "11 to 25 sites", d: "" },
      { t: "More than 25 sites", d: "" },
    ],
  },
  {
    qic: "text", q: "Where does your current contractor fall short?",
    sub: "Be honest. This is exactly what we want to fix.",
    opts: [
      { t: "Communication", d: "Slow replies, no updates, hard to reach when something comes up." },
      { t: "Consistency", d: "Missed visits or quality that slips once the contract is signed." },
      { t: "Billing surprises", d: "Vague invoices and change orders you never saw coming." },
      { t: "Snow response", d: "Lots and walkways sit too long after a storm." },
      { t: "Honestly, just exploring", d: "Happy enough today, but open to a better option." },
    ],
  },
  {
    qic: "wind", q: "How fast do you need issues handled?",
    sub: "Your expectation when you flag something on a site.",
    opts: [
      { t: "Same day", d: "" },
      { t: "Within 24 to 48 hours", d: "" },
      { t: "Within the week is fine", d: "" },
    ],
  },
  {
    qic: "snow", q: "How critical is snow & ice management?",
    sub: "For many managers this is the make-or-break service.",
    opts: [
      { t: "Top priority", d: "Slips and liability are my biggest winter worry." },
      { t: "Important, not urgent", d: "Needs to be reliable, but it isn't my main concern." },
      { t: "Not needed", d: "Handled separately or doesn't apply to my sites." },
    ],
  },
  {
    qic: "tree", q: "What would make the biggest difference this year?",
    sub: "Pick the one that matters most right now.",
    opts: [
      { t: "Reliable weekly grounds care", d: "" },
      { t: "Enhancements & seasonal color", d: "" },
      { t: "Dialed-in snow & ice management", d: "" },
      { t: "One vendor across every site", d: "" },
    ],
  },
];
const SOURCES = ["Facebook", "Google", "Saw your trucks", "Referral"];
const TOTAL = STEPS.length + 1; // + contact step

function PropertyPlan() {
  const [step, setStep] = React.useState(0);
  const [answers, setAnswers] = React.useState({});
  const [addr, setAddr] = React.useState({ company: "", name: "", email: "", phone: "", src: "" });
  const [done, setDone] = React.useState(false);
  const [sending, setSending] = React.useState(false);
  const [error, setError] = React.useState(null);
  const topRef = React.useRef(null);

  const goTo = (n) => {
    setStep(n);
    if (topRef.current) {
      const y = topRef.current.getBoundingClientRect().top + window.scrollY - 110;
      window.scrollTo({ top: y, behavior: "smooth" });
    }
  };
  const pick = (i, oi) => { setAnswers({ ...answers, [i]: oi }); goTo(step + 1); };

  const finish = async () => {
    setError(null);
    if (!addr.name.trim() || !addr.email.trim() || !addr.phone.trim()) {
      setError("Please add your name, phone, and work email.");
      return;
    }
    const summary = STEPS.map((s, i) => {
      const oi = answers[i];
      return oi != null ? `${s.q}: ${s.opts[oi].t}` : null;
    }).filter(Boolean).join("\n");
    const notes = [
      addr.company ? `Company / group: ${addr.company}` : null,
      addr.src ? `Heard about us: ${addr.src}` : null,
      summary ? `manager intake:\n${summary}` : null,
    ].filter(Boolean).join("\n");
    setSending(true);
    try {
      await window.submitLead({
        name: addr.name.trim(),
        email: addr.email.trim(),
        phone: addr.phone.trim(),
        company: addr.company || null,
        address: addr.company || "",
        propertyType: "Commercial",
        services: ["Full Management"],
        notes,
        leadType: "property-manager",
      });
      setDone(true);
      window.scrollTo({ top: 0, behavior: "auto" });
      setTimeout(() => { const el = document.getElementById("plan"); if (el) window.scrollTo({ top: el.getBoundingClientRect().top + window.scrollY - 90, behavior: "smooth" }); }, 30);
    } catch (err) {
      setError("Something went wrong. Please call us at (630) 296-4277.");
    } finally {
      setSending(false);
    }
  };

  if (done) return <section className="block" id="plan"><div className="wrap"><div className="wizwrap"><ThankYou onReset={() => { setDone(false); setStep(0); }} /></div></div></section>;

  const isAddress = step === STEPS.length;
  const pct = Math.round(((step + 1) / TOTAL) * 100);

  return (
    <section className="block" id="plan" style={{ background: "#e7eae6" }}>
      <div className="wrap">
        <div className="sec-center reveal" style={{ marginBottom: 34 }}>
          <div className="eyebrow">For Property Managers</div>
          <h2 style={{ marginTop: 10 }}>Tell us where your current contractor falls short.</h2>
          <p className="sub">A two-minute walkthrough of your portfolio and the gaps you're living with. We'll come back with exactly how Polaris fixes them across every site you manage.</p>
        </div>

        <div className="wizwrap" ref={topRef}>
          <div className="wizcard">
            <div className="wiz-prog">
              <div className="lbl">Manager Intake · {step + 1} of {TOTAL}</div>
              <div className="track"><div className="fill" style={{ width: pct + "%" }}></div></div>
            </div>

            {!isAddress ? (
              <React.Fragment>
                <div className="wiz-q"><span className="qic"><Icon name={STEPS[step].qic} /></span>{STEPS[step].q}</div>
                <p className="wiz-sub">{STEPS[step].sub}</p>
                <div className="opts">
                  {STEPS[step].opts.map((o, oi) => {
                    const sel = answers[step] === oi;
                    const compact = !o.d;
                    return (
                      <button key={oi} className={"opt" + (o.rec ? " rec" : "") + (sel ? " sel" : "") + (compact ? " compact" : "")} onClick={() => pick(step, oi)}>
                        {o.rec && <span className="badge">Recommended</span>}
                        <div className="ot">{o.t}</div>
                        {o.d && <div className="od">{o.d}</div>}
                      </button>
                    );
                  })}
                </div>
              </React.Fragment>
            ) : (
              <React.Fragment>
                <div className="wiz-eyebrow eyebrow" style={{ textAlign: "center" }}>Almost done</div>
                <h3 className="wiz-card-title">How should we reach you?</h3>
                <div className="field"><label>Company / management group</label><input value={addr.company} onChange={e => setAddr({ ...addr, company: e.target.value })} placeholder="Eastgate Property Group" /></div>
                <div className="grid2" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
                  <div className="field"><label>Your name</label><input value={addr.name} onChange={e => setAddr({ ...addr, name: e.target.value })} placeholder="Jordan Lee" /></div>
                  <div className="field"><label>Phone</label><input value={addr.phone} onChange={e => setAddr({ ...addr, phone: e.target.value })} placeholder="(630) 296-4277" /></div>
                </div>
                <div className="field"><label>Work email</label><input value={addr.email} onChange={e => setAddr({ ...addr, email: e.target.value })} placeholder="you@company.com" /></div>
                <div className="field">
                  <label>Where'd you find us? <span style={{ color: "var(--muted-2)", fontWeight: 600 }}>(optional)</span></label>
                  <div className="chips">
                    {SOURCES.map(s => (
                      <button key={s} className={"chip-pick" + (addr.src === s ? " on" : "")} onClick={() => setAddr({ ...addr, src: addr.src === s ? "" : s })}>{s}</button>
                    ))}
                  </div>
                </div>
                {error && <div className="form-error" style={{ marginTop: 16 }}>{error}</div>}
                <button className="btn btn-amber btn-block btn-lg btn-upper" style={{ marginTop: 24 }} disabled={sending} onClick={finish}>
                  {sending ? "Sending…" : "Continue"} {!sending && <Icon name="arrow" />}</button>
              </React.Fragment>
            )}

            <div className="wiz-nav">
              {step > 0
                ? <button className="wiz-back" onClick={() => goTo(step - 1)}><Icon name="back" />Back</button>
                : <span></span>}
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

function ThankYou({ onReset }) {
  const next = [
    { h: "We review your portfolio", p: "We look at your site types, how often each needs service, and the gaps you flagged with your current contractor." },
    { h: "We walk your priority sites", p: "We'll set up a quick assessment, usually one of these:", ways: [
      { ic: "footprints", b: "On-site walkthrough", d: ": we tour your key properties in person." },
      { ic: "satellite", b: "Remote review", d: ": aerial measurement for routine sites." },
      { ic: "users", b: "Manager meeting", d: ": only if you'd like to align on scope first." },
    ] },
    { h: "We send a transition plan", p: "A clear proposal per property, plus how we take over from your current vendor with no gap in service." },
    { h: "You decide", p: "Give us the go-ahead and we'll onboard your sites on your timeline." },
  ];
  return (
    <div className="wizcard thanks">
      <div className="check"><Icon name="checkc" /></div>
      <h2>Thanks. We've got the full picture.</h2>
      <p className="lede">Here's what we'll do with what you shared, and what happens next.</p>

      <div className="optional">
        <div className="tag">Optional · Scope faster</div>
        <div className="row1">
          <div className="badge-ic"><Icon name="layers" /></div>
          <h3>Share your site list</h3>
        </div>
        <p>Send a quick list or spreadsheet of the properties you manage and we'll scope every one before we even get on a call.</p>
        <button className="btn btn-green btn-block btn-lg btn-upper"><Icon name="layers" /> Add property list</button>
      </div>

      <div className="next">
        <div className="hd">What happens next</div>
        {next.map((s, i) => (
          <div className="nstep" key={i}>
            <div className="n">{i + 1}</div>
            <div>
              <h4>{s.h}</h4>
              <p>{s.p}</p>
              {s.ways && (
                <div className="ways">
                  {s.ways.map((w, j) => (
                    <div className="way" key={j}><Icon name={w.ic} /><span><b>{w.b}</b>{w.d}</span></div>
                  ))}
                </div>
              )}
            </div>
          </div>
        ))}
      </div>

      <button className="btn btn-ghost btn-lg" style={{ marginTop: 28 }} onClick={onReset}><Icon name="back" /> Start over</button>
    </div>
  );
}

Object.assign(window, { PropertyPlan });
