/* global React */
const { useState: useStateW, useMemo: useMemoW, useEffect: useEffectW } = React;

const WEBHOOK = "https://n8n.226.wtf/webhook/whycanti-lead";

function submitLead(payload) {
  return fetch(WEBHOOK, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(payload),
  }).catch(() => {});
}

// ============ QUICK WIZARD — 3 steps ============
function WizardQuick({ setPage }) {
  const [step, setStep] = useStateW(0);
  const [data, setData] = useStateW({ need:"", timeline:"", contact:"" });
  const [submitting, setSubmitting] = useStateW(false);

  const steps = [
    { k:"need", q:"What do you need most?", opts:[
      ["website","Stronger website / brand"],
      ["content","Consistent content"],
      ["systems","Cleaner systems & ops"],
      ["strategy","Senior strategic direction"],
    ]},
    { k:"timeline", q:"When are you starting?", opts:[
      ["now","Immediately"],
      ["30d","Within 30 days"],
      ["60d","Within 60 days"],
      ["explore","Just exploring"],
    ]},
  ];

  if (step >= steps.length) {
    return (
      <main className="page-enter" style={{ minHeight:"80vh", display:"grid", placeItems:"center", padding:"80px 24px" }}>
        <div style={{ maxWidth: 640, textAlign:"center" }}>
          <div className="eyebrow" style={{ marginBottom: 24, justifyContent:"center" }}><Dot/>Quick fit — complete</div>
          <div className="display" style={{ marginBottom: 32 }}>
            Looks like a fit.<br/><span className="it">Let's talk.</span>
          </div>
          <p className="lead" style={{ margin:"0 auto 40px" }}>
            Based on what you told us, you'd most likely benefit from <strong style={{ color:"var(--accent-ink)", fontStyle:"italic" }}>{labelFor(data.need)}</strong>. Drop your email and we'll send a 20-minute call slot.
          </p>
          <input className="input" placeholder="you@company.com" value={data.contact} onChange={e => setData({...data, contact: e.target.value})} style={{ marginBottom: 16, textAlign:"center" }}/>
          <div style={{ display:"flex", gap: 12, justifyContent:"center", flexWrap:"wrap" }}>
            <button className="btn btn-primary" disabled={submitting || !data.contact} style={{ opacity: (!data.contact||submitting) ? 0.5 : 1 }}
              onClick={() => {
                if (!data.contact) return;
                setSubmitting(true);
                submitLead({ source:"wizard-quick", need:data.need, timeline:data.timeline, contact:data.contact, email:data.contact })
                  .finally(() => { setSubmitting(false); setPage("home"); });
              }}>
              {submitting ? "Sending…" : "Send & continue"} <Arr/>
            </button>
            <button className="btn btn-ghost" onClick={() => setPage("wizard-full")}>Want the deep version? <Arr/></button>
          </div>
        </div>
      </main>
    );
  }

  const s = steps[step];
  return (
    <main className="page-enter" style={{ minHeight:"86vh", display:"flex", flexDirection:"column", padding:"64px 0" }}>
      <div className="wrap" style={{ flex: 1, display:"flex", flexDirection:"column", maxWidth: 880 }}>
        <div style={{ display:"flex", justifyContent:"space-between", alignItems:"center", marginBottom: 64 }}>
          <div className="eyebrow"><Dot/>Quick fit — 2 questions</div>
          <div className="mono small" style={{ color:"var(--ink-3)" }}>{step + 1} / {steps.length}</div>
        </div>

        <div style={{ height: 2, background:"var(--line)", marginBottom: 64, overflow:"hidden", borderRadius: 1 }}>
          <div style={{ width: `${((step+1) / (steps.length+1)) * 100}%`, height:"100%", background:"var(--accent)", transition:"width .5s cubic-bezier(.2,.7,.2,1)" }}/>
        </div>

        <div key={step} className="rise" style={{ flex: 1 }}>
          <h2 className="display" style={{ marginTop: 0, marginBottom: 56, fontSize:"clamp(40px, 6vw, 80px)" }}>{s.q}</h2>
          <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap: 14 }} className="qopt-grid">
            {s.opts.map(([v, l]) => (
              <button key={v} onClick={() => { setData({...data, [s.k]: v}); setStep(step + 1); }} style={{
                textAlign:"left", padding:"24px 28px",
                border:"1px solid var(--line)", borderRadius:"var(--radius)",
                background: data[s.k] === v ? "var(--ink)" : "var(--bg-elev)",
                color: data[s.k] === v ? "var(--bg)" : "var(--ink)",
                fontFamily:"var(--serif)", fontSize:"clamp(20px, 2vw, 26px)", letterSpacing:"-0.01em",
                transition:"all .25s",
              }}
                onMouseEnter={e => { if (data[s.k] !== v) { e.currentTarget.style.borderColor = "var(--ink)"; }}}
                onMouseLeave={e => { if (data[s.k] !== v) { e.currentTarget.style.borderColor = "var(--line)"; }}}
              >
                {l}
              </button>
            ))}
          </div>
        </div>

        <div style={{ marginTop: 40, display:"flex", justifyContent:"space-between", alignItems:"center" }}>
          <button className="btn-link" onClick={() => step > 0 ? setStep(step - 1) : setPage("home")}>← Back</button>
          <button className="btn-link" onClick={() => setPage("wizard-full")}>Need the deep wizard? <Arr size={11}/></button>
        </div>

        <style>{`@media (max-width: 700px) { .qopt-grid { grid-template-columns: 1fr !important; } }`}</style>
      </div>
    </main>
  );
}

function labelFor(k) {
  return {
    website:"Brand Launch",
    content:"a Content Engine",
    systems:"Growth Infrastructure",
    strategy:"Strategic Support",
  }[k] || "a tailored engagement";
}

// ============ FULL WIZARD — 8 steps with branching + live summary ============
function WizardFull({ setPage }) {
  const [step, setStep] = useStateW(0);
  const [data, setData] = useStateW({
    business:"", stage:"", challenges:[], services:[], outcomes:[], timeline:"", budget:"",
    name:"", email:"", company:"", website:"", phone:"", notes:"",
  });

  const steps = [
    { k:"business", kind:"single", q:"What kind of business do you run?",
      opts:[["service","Service business"],["local","Local business"],["personal","Personal brand"],["ecom","Ecommerce"],["startup","Startup"],["creative","Creative business"],["other","Other"]] },
    { k:"stage", kind:"single", q:"Where are you in the arc?",
      opts:[["fresh","Starting fresh"],["outdated","Existing but outdated"],["growing","Growing & inconsistent"],["established","Established but inefficient"],["scale","Ready to scale"]] },
    { k:"challenges", kind:"multi", q:"What's slowing you down? Pick all that apply.",
      opts:[["site","Weak website"],["content","Inconsistent content"],["systems","Messy backend systems"],["positioning","Unclear positioning"],["execution","Not enough execution support"],["manual","Too many manual processes"]] },
    { k:"services", kind:"multi", q:"Which areas do you think you need?",
      opts:[["brand","Website / brand launch"],["content","Content engine"],["growth","Growth infrastructure"],["strat","Strategic support"],["unsure","Not sure yet"]] },
    { k:"outcomes", kind:"multi", q:"What would you like to improve in 90 days?",
      opts:[["credible","Look more credible"],["leads","Generate more leads"],["consistency","Publish consistently"],["time","Save time"],["workflows","Improve workflows"],["offer","Clarify the offer"],["scale","Scale efficiently"]] },
    { k:"timeline", kind:"single", q:"When do you want to begin?",
      opts:[["now","Immediately"],["30","Within 30 days"],["60","Within 60 days"],["q","This quarter"],["explore","Exploring"]] },
    { k:"budget", kind:"single", q:"What's your investment range?",
      opts:[["u2","Under $2k"],["2-5","$2k–$5k"],["5-10","$5k–$10k"],["10p","$10k+"],["guide","Need guidance"]] },
    { k:"contact", kind:"contact", q:"Where should we send the brief?" },
  ];

  const total = steps.length;
  const recommendation = useMemoW(() => recommendFor(data), [data]);

  if (step >= total) {
    return <WizardSummary data={data} recommendation={recommendation} setPage={setPage}/>;
  }

  const s = steps[step];

  const set = (val) => {
    if (s.kind === "multi") {
      const cur = data[s.k] || [];
      const next = cur.includes(val) ? cur.filter(x => x !== val) : [...cur, val];
      setData({...data, [s.k]: next});
    } else {
      setData({...data, [s.k]: val});
    }
  };

  const canAdvance = s.kind === "contact"
    ? data.name && data.email
    : s.kind === "multi"
      ? (data[s.k] || []).length > 0
      : !!data[s.k];

  return (
    <main className="page-enter wiz-layout" style={{ background:"var(--bg)" }}>
      <style>{`
        .wiz-layout { display: grid; grid-template-columns: 1fr 380px; min-height: 100vh; }
        @media (max-width: 980px) { .wiz-layout { grid-template-columns: 1fr !important; } .wiz-summary { display: none !important; } }
      `}</style>
      <div style={{ display:"contents" }}>
        {/* Main */}
        <section style={{ padding:"clamp(32px, 5vw, 80px) clamp(24px, 5vw, 80px)", display:"flex", flexDirection:"column", borderRight:"1px solid var(--line)" }}>
          <header style={{ display:"flex", justifyContent:"space-between", alignItems:"center", marginBottom: 56 }}>
            <button onClick={() => setPage("home")} style={{ display:"flex", alignItems:"center", gap: 14 }}>
              <Logo/>
            </button>
            <button className="btn-link" onClick={() => setPage("home")}>Save & exit</button>
          </header>

          <div style={{ marginBottom: 56 }}>
            <div style={{ display:"flex", justifyContent:"space-between", alignItems:"center", marginBottom: 14 }}>
              <div className="eyebrow"><Dot/>Onboarding wizard</div>
              <div className="mono small" style={{ color:"var(--ink-3)" }}>STEP {String(step+1).padStart(2,"0")} / {String(total).padStart(2,"0")}</div>
            </div>
            <div style={{ display:"grid", gridTemplateColumns: `repeat(${total}, 1fr)`, gap: 4 }}>
              {Array.from({ length: total }).map((_, i) => (
                <div key={i} style={{ height: 3, borderRadius: 2, background: i <= step ? (i === step ? "var(--accent)" : "var(--ink)") : "var(--line)", transition:"background .4s" }}/>
              ))}
            </div>
          </div>

          <div key={step} className="rise" style={{ flex: 1, maxWidth: 720 }}>
            <h2 className="display" style={{ fontSize:"clamp(36px, 5vw, 64px)", marginTop: 0, marginBottom: 44, lineHeight: 1 }}>{s.q}</h2>

            {s.kind === "contact" ? (
              <div style={{ display:"flex", flexDirection:"column", gap: 14 }}>
                <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap: 14 }}>
                  <input className="input" placeholder="Full name *" value={data.name} onChange={e => setData({...data, name: e.target.value})}/>
                  <input className="input" type="email" placeholder="Email *" value={data.email} onChange={e => setData({...data, email: e.target.value})}/>
                </div>
                <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap: 14 }}>
                  <input className="input" placeholder="Company" value={data.company} onChange={e => setData({...data, company: e.target.value})}/>
                  <input className="input" placeholder="Website (optional)" value={data.website} onChange={e => setData({...data, website: e.target.value})}/>
                </div>
                <input className="input" placeholder="Phone (optional)" value={data.phone} onChange={e => setData({...data, phone: e.target.value})}/>
                <textarea className="input" rows="4" placeholder="Anything else? (optional)" value={data.notes} onChange={e => setData({...data, notes: e.target.value})}/>
              </div>
            ) : (
              <div style={{ display:"grid", gridTemplateColumns: s.opts.length > 5 ? "1fr 1fr 1fr" : "1fr 1fr", gap: 12 }} className="opt-grid">
                {s.opts.map(([v, l]) => {
                  const selected = s.kind === "multi" ? (data[s.k] || []).includes(v) : data[s.k] === v;
                  return (
                    <button key={v} onClick={() => set(v)} style={{
                      textAlign:"left", padding:"22px 24px",
                      border: "1px solid " + (selected ? "var(--ink)" : "var(--line)"),
                      borderRadius:"var(--radius)",
                      background: selected ? "var(--ink)" : "var(--bg-elev)",
                      color: selected ? "var(--bg)" : "var(--ink)",
                      transition:"all .2s",
                      position:"relative",
                    }}>
                      <div style={{ fontFamily:"var(--serif)", fontSize: 20, letterSpacing:"-0.01em", lineHeight: 1.15 }}>{l}</div>
                      {selected && (
                        <div style={{ position:"absolute", top: 10, right: 10, color:"var(--accent)" }}><Tick size={12}/></div>
                      )}
                    </button>
                  );
                })}
              </div>
            )}

            {s.kind === "multi" && <p className="small" style={{ marginTop: 16 }}>Pick as many as apply.</p>}
          </div>

          <footer style={{ marginTop: 56, display:"flex", justifyContent:"space-between", alignItems:"center", paddingTop: 28, borderTop:"1px solid var(--line)" }}>
            <button className="btn btn-ghost" onClick={() => step === 0 ? setPage("home") : setStep(step - 1)}>← Back</button>
            <div style={{ display:"flex", gap: 12, alignItems:"center" }}>
              {s.kind !== "contact" && <button className="btn-link" onClick={() => setStep(step + 1)}>Skip</button>}
              <button className="btn btn-primary" onClick={() => setStep(step + 1)} disabled={!canAdvance} style={{ opacity: canAdvance ? 1 : 0.4, cursor: canAdvance ? "pointer" : "not-allowed" }}>
                {step === total - 1 ? "See recommendation" : "Continue"} <Arr/>
              </button>
            </div>
          </footer>
        </section>

        {/* Live summary */}
        <aside className="wiz-summary" style={{ padding:"clamp(32px, 4vw, 56px)", background:"var(--bg-deep)", position:"sticky", top: 0, height:"100vh", overflowY:"auto" }}>
          <div className="eyebrow" style={{ marginBottom: 24 }}><Dot/>Live brief</div>
          <div style={{ fontFamily:"var(--serif)", fontSize: 28, letterSpacing:"-0.015em", lineHeight: 1.1, marginBottom: 32 }}>
            Building a picture<br/>of your engagement.
          </div>

          <div style={{ display:"flex", flexDirection:"column", gap: 0, borderTop:"1px solid var(--line)" }}>
            <SumRow label="Business" v={lookup("business", data.business)}/>
            <SumRow label="Stage" v={lookup("stage", data.stage)}/>
            <SumRow label="Challenges" v={(data.challenges || []).map(c => lookup("challenges", c)).join(", ")}/>
            <SumRow label="Services" v={(data.services || []).map(c => lookup("services", c)).join(", ")}/>
            <SumRow label="Outcomes" v={(data.outcomes || []).map(c => lookup("outcomes", c)).join(", ")}/>
            <SumRow label="Timeline" v={lookup("timeline", data.timeline)}/>
            <SumRow label="Budget" v={lookup("budget", data.budget)}/>
          </div>

          {recommendation.primary && (
            <div style={{ marginTop: 32, padding: 20, background:"var(--ink)", color:"var(--bg)", borderRadius:"var(--radius)" }}>
              <div className="mono small" style={{ color:"oklch(from var(--accent) calc(l + 0.05) c h)", letterSpacing:".1em", marginBottom: 8 }}>RECOMMENDED PATH</div>
              <div style={{ fontFamily:"var(--serif)", fontSize: 22, letterSpacing:"-0.01em", lineHeight: 1.1 }}>{recommendation.primary}</div>
              <div className="small" style={{ color:"oklch(from var(--bg) l c h / 0.7)", marginTop: 10 }}>{recommendation.reason}</div>
            </div>
          )}
        </aside>
      </div>
    </main>
  );
}

function SumRow({ label, v }) {
  return (
    <div style={{ display:"grid", gridTemplateColumns:"1fr 1.4fr", gap: 12, padding:"14px 0", borderBottom:"1px solid var(--line)", alignItems:"start" }}>
      <div className="mono small" style={{ color:"var(--ink-4)", letterSpacing:".06em", textTransform:"uppercase", fontSize: 10 }}>{label}</div>
      <div style={{ fontSize: 13, color: v ? "var(--ink)" : "var(--ink-4)", lineHeight: 1.4 }}>{v || "—"}</div>
    </div>
  );
}

const LOOKUPS = {
  business: { service:"Service business", local:"Local business", personal:"Personal brand", ecom:"Ecommerce", startup:"Startup", creative:"Creative business", other:"Other" },
  stage: { fresh:"Starting fresh", outdated:"Existing but outdated", growing:"Growing & inconsistent", established:"Established but inefficient", scale:"Ready to scale" },
  challenges: { site:"Weak website", content:"Inconsistent content", systems:"Messy systems", positioning:"Unclear positioning", execution:"Execution support", manual:"Manual processes" },
  services: { brand:"Brand launch", content:"Content engine", growth:"Growth infrastructure", strat:"Strategic support", unsure:"Not sure" },
  outcomes: { credible:"Credibility", leads:"Leads", consistency:"Consistency", time:"Save time", workflows:"Workflows", offer:"Offer clarity", scale:"Scale" },
  timeline: { now:"Immediately", "30":"Within 30 days", "60":"Within 60 days", q:"This quarter", explore:"Exploring" },
  budget: { u2:"Under $2k", "2-5":"$2k–$5k", "5-10":"$5k–$10k", "10p":"$10k+", guide:"Need guidance" },
};
function lookup(group, val) {
  if (!val) return "";
  return LOOKUPS[group]?.[val] || val;
}

function recommendFor(data) {
  const ch = data.challenges || [];
  const sv = data.services || [];
  if (ch.includes("site") && data.stage === "fresh") {
    return { primary:"Brand Launch", reason:"You're starting fresh and the site is the gap. Lead with the foundation, then layer content & systems." };
  }
  if (ch.includes("content") || sv.includes("content")) {
    return { primary:"Content Engine", reason:"Inconsistent publishing is the named bottleneck. The engine fixes the cadence first." };
  }
  if (ch.includes("manual") || ch.includes("systems") || sv.includes("growth")) {
    return { primary:"Growth Infrastructure", reason:"The drag is operational. Cleaning the workflows compounds across every other layer." };
  }
  if (ch.includes("positioning") || sv.includes("strat")) {
    return { primary:"Strategic Support", reason:"Direction comes before delivery. Quarterly advisory will sharpen the next decisions." };
  }
  if (sv.length >= 2) {
    return { primary:"Phased combined engagement", reason:"You've named multiple needs — a phased rollout (foundation → engine → ops) keeps the cadence calm." };
  }
  return { primary:"", reason:"" };
}

function WizardSummary({ data, recommendation, setPage }) {
  useEffectW(() => {
    submitLead({ source:"wizard-full", ...data });
  }, []);
  return (
    <main className="page-enter" style={{ minHeight:"86vh", padding:"80px 0" }}>
      <div className="wrap" style={{ maxWidth: 980 }}>
        <div className="eyebrow rise" style={{ marginBottom: 24 }}><Dot/>Brief complete</div>
        <h1 className="display rise rise-1" style={{ marginTop: 0, marginBottom: 32 }}>
          Got it, {data.name.split(" ")[0] || "operator"}.<br/>
          <span className="it">Here's the read.</span>
        </h1>
        <p className="lead rise rise-2" style={{ marginBottom: 56, maxWidth: "60ch" }}>
          Below is the brief we'll bring to the call — and our preliminary read on the engagement that fits.
        </p>

        <div className="rise rise-3" style={{ display:"grid", gridTemplateColumns:"1.2fr 1fr", gap: 24 }} className="sumf-grid">
          <div style={{ padding:"clamp(28px, 3vw, 40px)", background:"var(--bg-elev)", border:"1px solid var(--line)", borderRadius:"var(--radius-lg)" }}>
            <div className="eyebrow" style={{ marginBottom: 24 }}>The brief</div>
            <div style={{ display:"flex", flexDirection:"column", gap: 0, borderTop:"1px solid var(--line)" }}>
              <SumRow label="Business" v={lookup("business", data.business)}/>
              <SumRow label="Stage" v={lookup("stage", data.stage)}/>
              <SumRow label="Challenges" v={(data.challenges || []).map(c => lookup("challenges", c)).join(", ")}/>
              <SumRow label="Service interest" v={(data.services || []).map(c => lookup("services", c)).join(", ")}/>
              <SumRow label="Outcomes" v={(data.outcomes || []).map(c => lookup("outcomes", c)).join(", ")}/>
              <SumRow label="Timeline" v={lookup("timeline", data.timeline)}/>
              <SumRow label="Budget" v={lookup("budget", data.budget)}/>
              <SumRow label="Contact" v={data.email}/>
            </div>
          </div>

          <div style={{ padding:"clamp(28px, 3vw, 40px)", background:"var(--ink)", color:"var(--bg)", borderRadius:"var(--radius-lg)", display:"flex", flexDirection:"column", justifyContent:"space-between", gap: 32 }}>
            <div>
              <div className="mono small" style={{ color:"oklch(from var(--accent) calc(l + 0.05) c h)", letterSpacing:".1em", marginBottom: 12 }}>RECOMMENDED PATH</div>
              <div style={{ fontFamily:"var(--serif)", fontSize:"clamp(28px, 3vw, 40px)", letterSpacing:"-0.015em", lineHeight: 1.05, marginBottom: 18 }}>{recommendation.primary || "Tailored engagement"}</div>
              <p style={{ color:"oklch(from var(--bg) l c h / 0.75)", margin: 0, fontSize: 15 }}>{recommendation.reason || "We'll bring a tailored read on the call."}</p>
            </div>
            <div style={{ display:"flex", flexDirection:"column", gap: 10 }}>
              <button className="btn btn-accent" onClick={() => setPage("home")}>Book the call <Arr/></button>
              <button className="btn-link" style={{ color:"oklch(from var(--bg) l c h / 0.7)", borderColor:"oklch(from var(--bg) l c h / 0.2)" }} onClick={() => setPage("home")}>Or send a proposal request <Arr size={11}/></button>
            </div>
          </div>
        </div>

        <p className="small rise rise-4" style={{ marginTop: 40 }}>
          We'll be in your inbox under 12 hours with a confirmed slot and a working agenda.
        </p>
      </div>
      <style>{`@media (max-width: 880px) { .sumf-grid { grid-template-columns: 1fr !important; } }`}</style>
    </main>
  );
}

Object.assign(window, { WizardQuick, WizardFull });
