// PERSONALIZED DISCOVERY — 3-step wizard (industry → size → pain)
// → uses window.claude.complete to generate a custom agent roadmap on demand.
// Replaces the static team-based Discovery.

const INDUSTRIES = [
  { id: "saas", label: "B2B SaaS" },
  { id: "fintech", label: "Fintech / Financial" },
  { id: "ecom", label: "E-commerce / Retail" },
  { id: "services", label: "Professional services" },
  { id: "manufact", label: "Manufacturing / Industrial" },
  { id: "healthcare", label: "Healthcare / Life-sci" },
  { id: "media", label: "Media / Marketplaces" },
  { id: "other", label: "Other" },
];

const SIZES = [
  { id: "1-50", label: "1–50", detail: "scrappy team" },
  { id: "51-200", label: "51–200", detail: "growth stage" },
  { id: "201-1000", label: "201–1,000", detail: "scale-up" },
  { id: "1000+", label: "1,000+", detail: "enterprise" },
];

const PAINS = [
  { id: "outbound", label: "Not enough outbound capacity", icon: "→" },
  { id: "inbound", label: "Inbound tickets overwhelming the team", icon: "↘" },
  { id: "renewals", label: "Renewals slipping or running late", icon: "↻" },
  { id: "ops", label: "Manual back-office grind", icon: "≡" },
  { id: "data", label: "Data scattered across systems", icon: "◇" },
  { id: "csat", label: "Customer experience inconsistent", icon: "★" },
];

function Discovery() {
  // Restore from URL hash if present (?map=industry|size|pain)
  const initial = (() => {
    try {
      const h = new URLSearchParams(window.location.hash.replace(/^#/, ''));
      const m = h.get('map');
      if (!m) return null;
      const [i, s, p] = m.split('|');
      return { i, s, p };
    } catch (_) { return null; }
  })();

  const [step, setStep] = useState(initial ? 2 : 0);
  const [industry, setIndustry] = useState(initial ? initial.i : null);
  const [size, setSize] = useState(initial ? initial.s : null);
  const [pain, setPain] = useState(initial ? initial.p : null);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState(null);
  const [result, setResult] = useState(null);
  const [copied, setCopied] = useState(false);

  const reset = () => {
    setStep(0); setIndustry(null); setSize(null); setPain(null); setResult(null); setError(null);
    if (window.history && window.history.replaceState) {
      window.history.replaceState({}, '', window.location.pathname + window.location.search);
    }
  };

  function persistToUrl() {
    if (!industry || !size || !pain) return;
    const v = `${industry}|${size}|${pain}`;
    const newHash = `#map=${encodeURIComponent(v)}`;
    if (window.history && window.history.replaceState) {
      window.history.replaceState({}, '', window.location.pathname + window.location.search + newHash);
    }
  }

  function copyShareLink() {
    persistToUrl();
    const url = window.location.href.split('#')[0] + `#map=${encodeURIComponent(`${industry}|${size}|${pain}`)}`;
    navigator.clipboard?.writeText(url).then(() => {
      setCopied(true);
      setTimeout(() => setCopied(false), 2400);
    });
  }

  function openInIris() {
    const indLabel = INDUSTRIES.find(x => x.id === industry)?.label || industry;
    const sizeLabel = SIZES.find(x => x.id === size)?.label || size;
    const painLabel = PAINS.find(x => x.id === pain)?.label || pain;
    window.__sgvIrisContext = {
      preface: `The visitor just ran a Discovery: industry=${indLabel}, team size=${sizeLabel}, primary pain=${painLabel}. They have a generated agent map on screen. Ask them which agent they want to talk through first.`,
    };
    if (window.openIris) window.openIris();
  }

  async function generate() {
    setBusy(true);
    setError(null);
    setResult(null);
    try {
      const indLabel = INDUSTRIES.find(x => x.id === industry)?.label || industry;
      const sizeLabel = SIZES.find(x => x.id === size)?.label || size;
      const painLabel = PAINS.find(x => x.id === pain)?.label || pain;

      const prompt = `You are Iris, the discovery agent for SupportGenie (a Salesforce + AI agent studio).

A visitor just told you:
- Industry: ${indLabel}
- Team size: ${sizeLabel} people
- Primary pain: ${painLabel}

Generate a custom Salesforce AI agent roadmap. Return ONLY valid JSON with this exact shape (no markdown, no preamble, no trailing commas):

{
  "summary": "One sentence — what we'd build for them.",
  "agents": [
    {
      "name": "Short product-style name (3–4 words)",
      "kind": "Voice agent | Agentforce topic | Internal copilot | Scheduled agent",
      "what": "1-2 sentence description of what it does",
      "value": "Quantified impact like '↑ 23% renewal close' or '↓ 4 hrs / CSM / week'",
      "weeks_to_ship": 2 or 3
    }
  ],
  "estimate": {
    "build_low": 42000,
    "build_high": 95000,
    "care_per_month": 9500,
    "rationale": "1 sentence on why this range"
  },
  "first_step": "1 sentence — what they should do this week to unblock"
}

Make exactly 3 agents. Be specific to the industry and pain. Use realistic Salesforce terminology (opportunities, cases, accounts, contacts). Quantified value must be plausible — no 10x claims. Pricing tiers: Build = $42K/agent flat, Care = $9.5K/mo for up to 4 agents. Multi-agent builds: $42K + $35K per additional agent. Just return the JSON.`;

      const out = await window.claude.complete(prompt);
      const text = (out || "").trim();
      // Try strict parse; fall back to extracting the first { ... } block.
      let parsed;
      try {
        parsed = JSON.parse(text);
      } catch (_) {
        const m = text.match(/\{[\s\S]*\}/);
        if (m) parsed = JSON.parse(m[0]);
        else throw new Error("Could not parse the response.");
      }
      setResult(parsed);
      setStep(3);
      persistToUrl();
    } catch (e) {
      console.error(e);
      setError("Something went sideways generating your map. Try again — or just book a 20-minute call and we'll do it live.");
    } finally {
      setBusy(false);
    }
  }

  return (
    <section className="section section--teal" id="discovery">
      <div className="shell">
        <div className="section-head">
          <div className="num">§ 03</div>
          <div>
            <div className="label" style={{ marginBottom: 24 }}>AGENT DISCOVERY · LIVE</div>
            <h2 className="display-l serif" style={{ margin: 0, maxWidth: "20ch", textWrap: "pretty", color: "var(--bone)" }}>
              Three questions. <span style={{ color: "var(--yellow)" }}>Your custom agent map.</span>
            </h2>
            <p className="lead" style={{ marginTop: 20, color: "color-mix(in oklab, var(--bone) 70%, transparent)", maxWidth: "55ch" }}>
              Iris generates the roadmap on the spot — agents we'd actually build, ranked by impact,
              with a real cost range. Powered by the same brain that runs our front desk.
            </p>
          </div>
        </div>

        {/* Stepper */}
        {step < 3 && (
          <div style={{ display: "flex", gap: 0, marginBottom: 32, border: "1px solid color-mix(in oklab, var(--bone) 24%, transparent)", maxWidth: "fit-content" }}>
            {["Industry", "Team size", "Pain"].map((label, i) => {
              const done = (i === 0 && industry) || (i === 1 && size) || (i === 2 && pain);
              const current = i === step;
              return (
                <button
                  key={label}
                  type="button"
                  onClick={() => setStep(i)}
                  disabled={i > step && !done}
                  style={{
                    padding: "10px 18px",
                    background: current ? "var(--persimmon)" : (done ? "color-mix(in oklab, var(--bone) 10%, transparent)" : "transparent"),
                    color: current ? "var(--ink)" : (done ? "var(--bone)" : "color-mix(in oklab, var(--bone) 55%, transparent)"),
                    border: "none",
                    borderRight: i < 2 ? "1px solid color-mix(in oklab, var(--bone) 18%, transparent)" : "none",
                    fontFamily: "var(--font-mono)",
                    fontSize: 12,
                    letterSpacing: "0.1em",
                    textTransform: "uppercase",
                    cursor: i > step && !done ? "not-allowed" : "pointer",
                    transition: "all 0.18s",
                  }}
                >
                  0{i + 1} · {label}
                  {done && <span style={{ marginLeft: 8, opacity: 0.7 }}>✓</span>}
                </button>
              );
            })}
          </div>
        )}

        {/* Step content */}
        {step === 0 && (
          <WizardStep title="Pick your industry" hint="We tune the agent map to the patterns we see most in your space.">
            <ChipGrid options={INDUSTRIES} value={industry} onChange={(v) => { setIndustry(v); setStep(1); }} />
          </WizardStep>
        )}
        {step === 1 && (
          <WizardStep title="Team size" hint="So we right-size the build — fewer, deeper agents for small teams; orchestration for big ones.">
            <ChipGrid options={SIZES.map(s => ({ id: s.id, label: s.label, sub: s.detail }))} value={size} onChange={(v) => { setSize(v); setStep(2); }} big />
          </WizardStep>
        )}
        {step === 2 && (
          <WizardStep title="What hurts most right now?" hint="Be honest — the worst pain is where the first agent earns its keep.">
            <ChipGrid options={PAINS} value={pain} onChange={(v) => setPain(v)} />
            <div style={{ marginTop: 32, display: "flex", gap: 12, alignItems: "center", flexWrap: "wrap" }}>
              <button
                type="button"
                onClick={generate}
                disabled={!industry || !size || !pain || busy}
                className="btn"
                style={{
                  background: "var(--persimmon)",
                  color: "var(--ink)",
                  borderColor: "var(--persimmon)",
                  opacity: (!industry || !size || !pain || busy) ? 0.5 : 1,
                  cursor: (!industry || !size || !pain || busy) ? "not-allowed" : "pointer",
                  fontSize: 15,
                  padding: "16px 26px",
                }}
              >
                {busy ? <><GenSpinner /> Generating your map…</> : <>Generate my agent map <span className="arr">→</span></>}
              </button>
              <button type="button" onClick={reset} style={{ background: "transparent", border: "none", color: "color-mix(in oklab, var(--bone) 70%, transparent)", fontFamily: "var(--font-mono)", fontSize: 12, letterSpacing: "0.08em", cursor: "pointer", textTransform: "uppercase" }}>Start over</button>
            </div>
            {error && <div style={{ marginTop: 16, padding: 12, background: "color-mix(in oklab, var(--persimmon) 20%, transparent)", color: "var(--bone)", fontSize: 13 }}>{error}</div>}
          </WizardStep>
        )}

        {/* Result */}
        {step === 3 && result && (
          <ResultPanel result={result} onReset={reset} onCopyLink={copyShareLink} onAskIris={openInIris} copied={copied} />
        )}
      </div>
    </section>
  );
}

function WizardStep({ title, hint, children }) {
  return (
    <div style={{ minHeight: 320 }}>
      <h3 className="serif" style={{ margin: 0, fontSize: "clamp(28px, 3vw, 42px)", lineHeight: 1.05, letterSpacing: "-0.025em", color: "var(--bone)" }}>
        {title}
      </h3>
      <p style={{ margin: "12px 0 32px 0", color: "color-mix(in oklab, var(--bone) 65%, transparent)", maxWidth: "55ch", fontSize: 15 }}>
        {hint}
      </p>
      {children}
    </div>
  );
}

function ChipGrid({ options, value, onChange, big }) {
  return (
    <div style={{
      display: "grid",
      gridTemplateColumns: big ? "repeat(auto-fit, minmax(200px, 1fr))" : "repeat(auto-fit, minmax(220px, 1fr))",
      gap: 8,
    }}>
      {options.map(opt => {
        const active = value === opt.id;
        return (
          <button
            key={opt.id}
            type="button"
            onClick={() => onChange(opt.id)}
            style={{
              padding: big ? "20px 22px" : "16px 18px",
              background: active ? "var(--persimmon)" : "color-mix(in oklab, var(--bone) 8%, transparent)",
              border: `1px solid ${active ? "var(--persimmon)" : "color-mix(in oklab, var(--bone) 22%, transparent)"}`,
              color: active ? "var(--ink)" : "var(--bone)",
              cursor: "pointer",
              textAlign: "left",
              transition: "all 0.18s",
              display: "flex",
              flexDirection: "column",
              gap: 4,
              fontFamily: "var(--font-ui)",
            }}
            onMouseEnter={e => { if (!active) { e.currentTarget.style.background = "color-mix(in oklab, var(--bone) 14%, transparent)"; e.currentTarget.style.borderColor = "color-mix(in oklab, var(--bone) 40%, transparent)"; }}}
            onMouseLeave={e => { if (!active) { e.currentTarget.style.background = "color-mix(in oklab, var(--bone) 8%, transparent)"; e.currentTarget.style.borderColor = "color-mix(in oklab, var(--bone) 22%, transparent)"; }}}
          >
            <span style={{ fontSize: big ? 24 : 15, fontWeight: big ? 700 : 500, fontFamily: big ? "var(--font-display)" : "var(--font-ui)", letterSpacing: big ? "-0.02em" : "0" }}>
              {opt.icon && <span style={{ marginRight: 8, color: active ? "var(--ink)" : "var(--yellow)" }}>{opt.icon}</span>}
              {opt.label}
            </span>
            {opt.sub && <span style={{ fontSize: 11, fontFamily: "var(--font-mono)", letterSpacing: "0.08em", textTransform: "uppercase", color: active ? "var(--ink)" : "color-mix(in oklab, var(--bone) 60%, transparent)" }}>{opt.sub}</span>}
          </button>
        );
      })}
    </div>
  );
}

function GenSpinner() {
  return (
    <span style={{
      display: "inline-block",
      width: 14,
      height: 14,
      border: "2px solid currentColor",
      borderTopColor: "transparent",
      borderRadius: "50%",
      animation: "spin 0.8s linear infinite",
      marginRight: 8,
      verticalAlign: "middle",
    }}>
      <style>{`@keyframes spin { to { transform: rotate(360deg); } }`}</style>
    </span>
  );
}

function ResultPanel({ result, onReset, onCopyLink, onAskIris, copied }) {
  const fmtMoney = (n) => "$" + Math.round(n).toLocaleString();
  return (
    <div style={{ animation: "fadeUp 0.5s ease-out" }}>
      <style>{`@keyframes fadeUp { from { opacity:0; transform: translateY(12px); } to { opacity:1; transform: translateY(0); } }`}</style>

      <p className="mono" style={{ fontSize: 11, letterSpacing: "0.16em", textTransform: "uppercase", color: "var(--yellow)", margin: 0 }}>
        ↳ YOUR AGENT MAP
      </p>
      <h3 className="serif" style={{ margin: "12px 0 0 0", fontSize: "clamp(26px, 3vw, 40px)", lineHeight: 1.1, letterSpacing: "-0.02em", color: "var(--bone)", textWrap: "balance", maxWidth: "32ch" }}>
        {result.summary}
      </h3>

      {/* Agent cards */}
      <div style={{
        marginTop: 36,
        display: "grid",
        gridTemplateColumns: "repeat(auto-fit, minmax(280px, 1fr))",
        gap: 1,
        background: "color-mix(in oklab, var(--bone) 18%, transparent)",
        border: "1px solid color-mix(in oklab, var(--bone) 24%, transparent)",
      }}>
        {(result.agents || []).map((a, i) => (
          <article key={i} style={{ background: "var(--paper)", padding: 28, display: "flex", flexDirection: "column", gap: 14, minHeight: 260, color: "var(--ink)" }}>
            <header style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
              <span className="mono" style={{ fontSize: 11, color: "var(--ink-mute)", letterSpacing: "0.1em" }}>
                AGT · {String(i + 1).padStart(2, "0")} / {result.agents.length}
              </span>
              <span className="mono" style={{ fontSize: 10, padding: "3px 8px", background: "var(--cobalt)", color: "var(--bone)", letterSpacing: "0.1em", textTransform: "uppercase" }}>
                {a.kind}
              </span>
            </header>
            <h4 className="serif" style={{ margin: 0, fontSize: 24, lineHeight: 1.08, letterSpacing: "-0.02em", color: "var(--ink)" }}>{a.name}</h4>
            <p style={{ margin: 0, fontSize: 14, lineHeight: 1.4, color: "var(--ink-soft)" }}>{a.what}</p>
            <div style={{ marginTop: "auto", paddingTop: 12, borderTop: "1px solid var(--rule)", display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
              <div>
                <div className="mono" style={{ fontSize: 9, color: "var(--ink-mute)", letterSpacing: "0.1em", textTransform: "uppercase" }}>Expected impact</div>
                <div className="serif" style={{ fontSize: 22, lineHeight: 1, letterSpacing: "-0.025em", color: "var(--persimmon)", marginTop: 4 }}>{a.value}</div>
              </div>
              <div className="mono" style={{ fontSize: 11, color: "var(--ink-soft)" }}>{a.weeks_to_ship}w</div>
            </div>
          </article>
        ))}
      </div>

      {/* Estimate row */}
      {result.estimate && (
        <div style={{
          marginTop: 24,
          padding: "24px 28px",
          background: "var(--ink)",
          color: "var(--bone)",
          display: "grid",
          gridTemplateColumns: "1.5fr 1fr 1fr auto",
          gap: 24,
          alignItems: "center",
        }} className="estimate-row">
          <div>
            <div className="mono" style={{ fontSize: 10, letterSpacing: "0.14em", textTransform: "uppercase", color: "color-mix(in oklab, var(--bone) 55%, transparent)", marginBottom: 6 }}>
              Build range · fixed fee
            </div>
            <div className="serif" style={{ fontSize: "clamp(28px, 3.4vw, 44px)", lineHeight: 1, letterSpacing: "-0.025em" }}>
              {fmtMoney(result.estimate.build_low)} – {fmtMoney(result.estimate.build_high)}
            </div>
          </div>
          <div>
            <div className="mono" style={{ fontSize: 10, letterSpacing: "0.14em", textTransform: "uppercase", color: "color-mix(in oklab, var(--bone) 55%, transparent)", marginBottom: 6 }}>
              Care · monthly
            </div>
            <div className="serif" style={{ fontSize: 28, lineHeight: 1, letterSpacing: "-0.025em" }}>{fmtMoney(result.estimate.care_per_month)}</div>
          </div>
          <div style={{ fontSize: 12, color: "color-mix(in oklab, var(--bone) 70%, transparent)", lineHeight: 1.4, maxWidth: "30ch" }}>
            {result.estimate.rationale}
          </div>
          <a href="contact.html#book" className="btn btn-accent" style={{ whiteSpace: "nowrap" }}>
            Scope this with us <span className="arr">→</span>
          </a>
        </div>
      )}

      {/* First step + CTAs */}
      {result.first_step && (
        <div style={{
          marginTop: 24,
          padding: 24,
          border: "1px solid color-mix(in oklab, var(--bone) 24%, transparent)",
          color: "var(--bone)",
          display: "flex",
          justifyContent: "space-between",
          alignItems: "center",
          gap: 24,
          flexWrap: "wrap",
        }}>
          <div>
            <div className="mono" style={{ fontSize: 10, letterSpacing: "0.16em", textTransform: "uppercase", color: "var(--yellow)", marginBottom: 8 }}>
              ↳ DO THIS WEEK
            </div>
            <p style={{ margin: 0, fontFamily: "var(--font-display)", fontSize: "clamp(16px, 1.6vw, 22px)", lineHeight: 1.3, letterSpacing: "-0.015em", maxWidth: "60ch", fontWeight: 600 }}>
              {result.first_step}
            </p>
          </div>
          <div style={{ display: "flex", gap: 10 }}>
            <button type="button" onClick={onAskIris} className="btn btn-ghost" style={{ borderColor: "color-mix(in oklab, var(--bone) 40%, transparent)", color: "var(--bone)" }}>
              Talk to Iris about this
            </button>
            <button type="button" onClick={onReset} style={{ background: "transparent", border: "none", color: "color-mix(in oklab, var(--bone) 65%, transparent)", fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.08em", cursor: "pointer", textTransform: "uppercase" }}>
              Try again
            </button>
          </div>
        </div>
      )}

      {/* Share row */}
      <div style={{
        marginTop: 16,
        padding: "14px 20px",
        background: "color-mix(in oklab, var(--bone) 6%, transparent)",
        border: "1px dashed color-mix(in oklab, var(--bone) 22%, transparent)",
        display: "flex",
        justifyContent: "space-between",
        alignItems: "center",
        gap: 16,
        flexWrap: "wrap",
      }}>
        <div style={{ display: "flex", alignItems: "center", gap: 12, color: "color-mix(in oklab, var(--bone) 75%, transparent)", fontSize: 13 }}>
          <span className="mono" style={{ fontSize: 10, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--yellow)" }}>↳ SHARE</span>
          <span>Send this map to a teammate — they'll land right where you are.</span>
        </div>
        <div style={{ display: "flex", gap: 8 }}>
          <button type="button" onClick={onCopyLink} className="btn" style={{ background: "var(--bone)", color: "var(--teal)", borderColor: "var(--bone)", padding: "10px 16px", fontSize: 12 }}>
            {copied ? "✓ Copied" : "Copy share link"} <span className="arr" style={{ display: copied ? "none" : "inline" }}>→</span>
          </button>
          <a
            href={`mailto:?subject=${encodeURIComponent('Agent map from SupportGenie')}&body=${encodeURIComponent('I generated this on supportgenie.us — take a look:\n\n' + window.location.href)}`}
            className="btn btn-ghost"
            style={{ borderColor: "color-mix(in oklab, var(--bone) 35%, transparent)", color: "var(--bone)", padding: "10px 16px", fontSize: 12 }}
          >
            Email it to me
          </a>
        </div>
      </div>

      <style>{`
        @media (max-width: 980px) {
          .estimate-row { grid-template-columns: 1fr !important; gap: 16px !important; }
        }
      `}</style>
    </div>
  );
}

Object.assign(window, { Discovery });
