/* ============================================================
   FlowSpace Finder, funnel screens (window.FinderScreens)
   Hero · Brief-improver · Results (teaser + single gate +
   unlocked shortlist + refine + convert)
   ============================================================ */
(function () {
  "use strict";
  const React = window.React;
  const { useState, useRef, useEffect } = React;
  const DS = window.DesignSystem_019e02;
  const UI = window.FinderUI;
  const FD = window.FinderData;
  const { Button, Input, Badge } = DS;
  const { Icon, Logo, TrustRow, OfficeCard, MiniResult, CompanyBanner, CompanySummary, AreaTile } = UI;
  const { gbp } = FD;

  // ============================================================
  //  HERO
  // ============================================================
  const HEADLINES = {
    a: ["Type your company", "we'll find your London office."],
    b: ["Your London office,", "found by AI in seconds."],
    c: ["Skip the brokers.", "Let AI find your office."],
  };
  function Hero({ onFind, heroBg, heroHeadline }) {
    const [val, setVal] = useState("");
    const dark = (heroBg || "dusk") !== "light";
    const headline = HEADLINES[heroHeadline] || HEADLINES.a;
    const go = () => { if (val.trim()) onFind(val.trim()); };
    const features = [
      { icon: "brain", t: "Reads your team", s: "Size, culture & vibe" },
      { icon: "shield", t: "Whole-of-market", s: "Every London operator" },
      { icon: "zap", t: "A match in seconds", s: "No forms, no brokers" },
    ];
    return React.createElement("div", { className: "f-hero f-hero--" + (heroBg || "dusk") },
      React.createElement("div", { className: "f-hero-noise" }),
      React.createElement("header", { className: "f-hero-nav" },
        React.createElement(Logo, { light: dark }),
        React.createElement("a", { className: "f-hero-nav-link", href: "#" },
          React.createElement(Icon, { name: "message", size: 16 }), "Talk to us")),
      React.createElement("div", { className: "f-hero-inner" },
        React.createElement("div", { className: "f-hero-pill" },
          React.createElement("span", { className: "f-hero-pill-dot" }),
          "AI office finder · London"),
        React.createElement("h1", { className: "f-hero-head" },
          React.createElement("span", { className: "f-hero-head-1" }, headline[0]), " ",
          React.createElement("span", { className: "f-hero-head-2" }, headline[1])),
        React.createElement("p", { className: "f-hero-sub" },
          "Tell us your company and our AI reads who you are, size, culture, the way you work, then matches you to a London office that actually fits."),
        React.createElement("div", { className: "f-hero-form" },
          React.createElement("div", { className: "f-hero-input" },
            React.createElement(Icon, { name: "search", size: 18, style: { color: "var(--color-text-muted)" } }),
            React.createElement("input", {
              value: val, onChange: (e) => setVal(e.target.value), placeholder: "Company name or website…",
              autoFocus: true, autoComplete: "off",
              onKeyDown: (e) => { if (e.key === "Enter") go(); },
            })),
          React.createElement(Button, { variant: "primary", size: "lg", onClick: go, iconRight: React.createElement(Icon, { name: "arrowRight", size: 18 }) }, "Find my office")),
        React.createElement("div", { className: "f-hero-hint" },
          "For teams up to 100 · try ", 
          React.createElement("button", { className: "f-hero-eg", onClick: () => onFind("pleo.io") }, "pleo.io"),
          " or your own."),
        React.createElement("div", { className: "f-hero-features" },
          features.map((f) => React.createElement("div", { key: f.t, className: "f-hero-feature" },
            React.createElement("div", { className: "f-hero-feature-ico" }, React.createElement(Icon, { name: f.icon, size: 18 })),
            React.createElement("div", { className: "f-hero-feature-txt" },
              React.createElement("strong", null, f.t),
              React.createElement("span", null, f.s)))))),
      React.createElement("div", { className: "f-hero-foot" }, React.createElement(TrustRow, { light: dark })));
  }

  // ============================================================
  //  BRIEF IMPROVER (optional, skippable)
  // ============================================================
  const SIZE_OPTS = [{ v: 5, l: "1–5" }, { v: 12, l: "6–15" }, { v: 24, l: "16–30" }, { v: 45, l: "31–60" }, { v: 80, l: "60–100" }];
  const BUDGET_OPTS = [{ v: 480, l: "Value · under £500" }, { v: 650, l: "Mid · £500–700" }, { v: 900, l: "Premium · £700+" }, { v: 0, l: "Flexible" }];
  const AREA_OPTS = ["Shoreditch", "Old Street", "King's Cross", "Soho", "Bank", "London Bridge", "any"];

  // The second screen: lead with the fetched company read, THEN offer
  // optional narrow-down below it. We deliver value before asking anything.
  function CompanyRead({ analysis, onContinue }) {
    const [size, setSize] = useState(null);
    const [budget, setBudget] = useState(null);
    const [area, setArea] = useState(null);
    const [areaOther, setAreaOther] = useState("");
    const isOther = area === "__other__";
    const customArea = areaOther.trim();
    const brief = {};
    if (size != null) brief.size = size;
    if (budget) brief.budget = budget;
    if (isOther) { if (customArea) brief.area = customArea; }
    else if (area && area !== "any") brief.area = area;
    const touched = size != null || budget != null || (area != null && (!isOther || customArea));
    const areaOpts = AREA_OPTS.map((a) => ({ v: a, l: a === "any" ? "No preference" : a })).concat([{ v: "__other__", l: "Other…" }]);
    return React.createElement("div", { className: "f-results" },
      React.createElement(CompanyBanner, { a: analysis }),
      React.createElement("div", { className: "f-narrow" },
        React.createElement("div", { className: "f-narrow-head" },
          React.createElement("div", { className: "f-narrow-eyebrow" },
            React.createElement(Icon, { name: "sparkles", size: 13 }), "Refine your search (optional)"),
          React.createElement("h2", null, "Narrow it down, or let us decide"),
          React.createElement("p", null, "That's what we read about ", React.createElement("em", null, analysis.companyName), " from the web. Tweak anything below to sharpen your matches, or just hit the button and we'll choose for you.")),
        React.createElement(BriefGroup, { icon: "users", label: "Team size", opts: SIZE_OPTS.map((o) => ({ v: o.v, l: o.l })), value: size, onPick: setSize }),
        React.createElement(BriefGroup, { icon: "wallet", label: "Budget per desk", opts: BUDGET_OPTS.map((o) => ({ v: o.v, l: o.l })), value: budget, onPick: setBudget }),
        React.createElement(BriefGroup, {
          icon: "mapPin", label: "Preferred area", opts: areaOpts, value: area,
          onPick: (v) => { setArea(v); if (v !== "__other__") setAreaOther(""); },
        }),
        isOther && React.createElement("div", { className: "f-area-other" },
          React.createElement(Icon, { name: "mapPin", size: 16, style: { color: "var(--color-text-muted)" } }),
          React.createElement("input", {
            type: "text", value: areaOther, autoFocus: true,
            placeholder: "Type a London area or postcode, e.g. Liverpool Street, SE1, near Waterloo…",
            onChange: (e) => setAreaOther(e.target.value),
            onKeyDown: (e) => { if (e.key === "Enter") onContinue(brief); },
          })),
        React.createElement("div", { className: "f-narrow-actions" },
          React.createElement(Button, { variant: "primary", size: "lg", fullWidth: true, onClick: () => onContinue(brief), iconRight: React.createElement(Icon, { name: "arrowRight", size: 18 }) },
            touched ? "Find my matches with this" : "Show me my best matches"),
          React.createElement("div", { className: "f-narrow-hint" },
            React.createElement(Icon, { name: "lock", size: 13 }),
            "No email needed yet, we'll only ask when you want the full shortlist."))));
  }
  function BriefGroup({ icon, label, opts, value, onPick }) {
    return React.createElement("div", { className: "f-brief-group" },
      React.createElement("div", { className: "f-brief-label" }, React.createElement(Icon, { name: icon, size: 15 }), label),
      React.createElement("div", { className: "f-chiprow" },
        opts.map((o) => React.createElement("button", {
          key: String(o.v), className: "f-chip2" + (value === o.v ? " on" : ""),
          onClick: () => onPick(value === o.v ? null : o.v),
        }, o.l))));
  }

  // ============================================================
  //  RESULTS, banner + (locked teaser + gate) OR (unlocked list)
  // ============================================================
  function Results(props) {
    const { analysis, unlocked } = props;
    return React.createElement("div", { className: "f-results" },
      React.createElement(CompanySummary, { a: analysis }),
      unlocked
        ? React.createElement(Unlocked, props)
        : React.createElement(Locked, props));
  }

  // ---- Locked: proof card + in-place reveal (blurred stack + email) ----
  function Locked({ analysis, ranked, teaser, revealStack, onUnlock }) {
    const gateRef = useRef(null);
    const [err, setErr] = useState("");
    const [showSticky, setShowSticky] = useState(false);
    const total = ranked.length;
    const availNow = ranked.filter((s) => s.av === "NOW").length;
    const toGate = () => {
      if (gateRef.current) {
        const y = gateRef.current.getBoundingClientRect().top + window.scrollY - 14;
        window.scrollTo({ top: y, behavior: "smooth" });
        const i = gateRef.current.querySelector("input");
        if (i) setTimeout(() => i.focus(), 420);
      }
    };
    useEffect(() => {
      const onScroll = () => {
        const g = gateRef.current;
        if (!g) return;
        const r = g.getBoundingClientRect();
        const vh = window.innerHeight;
        const gateVisible = r.top < vh - 80 && r.bottom > 80;
        setShowSticky(!gateVisible);
      };
      onScroll();
      const t0 = setTimeout(onScroll, 200);
      window.addEventListener("scroll", onScroll, { passive: true });
      window.addEventListener("resize", onScroll);
      return () => { clearTimeout(t0); window.removeEventListener("scroll", onScroll); window.removeEventListener("resize", onScroll); };
    }, []);
    return React.createElement(React.Fragment, null,
      React.createElement("div", { className: "f-found" },
        React.createElement("h2", { className: "f-found-title" },
          "We found ", React.createElement("strong", null, total, " offices"), " with desks free right now"),
        React.createElement("p", { className: "f-found-sub" },
          "Live, whole-of-market availability for ", analysis.companyName, ", matched and ranked by our AI. Here's your strongest one:")),
      React.createElement(OfficeCard, { space: teaser, analysis, locked: true, rank: 0, teaser: true }),
      React.createElement("div", { ref: gateRef },
        React.createElement(UnlockBlock, { analysis, ranked, total, availNow, revealStack, err, setErr, onUnlock })),
      showSticky && React.createElement("div", { className: "f-sticky" },
        React.createElement("div", { className: "f-sticky-txt" },
          React.createElement("strong", null, "Reveal all ", total, " spaces"),
          React.createElement("span", null, "Names & locations, unlocked on this page")),
        React.createElement(Button, { variant: "primary", onClick: toGate, iconRight: React.createElement(Icon, { name: "arrowRight", size: 17 }) }, "See them")));
  }

  // ---- The reveal-in-place block: blurred stack of real cards + email ----
  function UnlockBlock({ analysis, ranked, total, availNow, revealStack = true, onUnlock, err, setErr }) {
    const [email, setEmail] = useState("");
    const dom = analysis.domain && analysis.domain.includes(".") ? analysis.domain : null;
    const moreCount = Math.max(1, total - 1);
    const stack = ranked.slice(1, 7);
    const submit = () => {
      const e = email.trim().toLowerCase();
      if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)) { setErr("Enter a valid email to reveal the list."); return; }
      const d = e.split("@")[1] || "";
      if (/^(gmail|googlemail|yahoo|hotmail|outlook|live|icloud|aol|proton|gmx|yandex)\./.test(d)) {
        setErr("A work email helps us tailor your matches, try your company address."); return;
      }
      setErr(""); onUnlock(e);
    };
    return React.createElement("div", { className: "f-unlock" + (revealStack ? "" : " f-unlock--flat") },
      React.createElement("div", { className: "f-unlock-panel" },
        React.createElement("div", { className: "f-unlock-count" },
          React.createElement("span", { className: "f-unlock-count-num" }, "+" + moreCount),
          React.createElement("span", { className: "f-unlock-count-lbl" }, "more matches,", React.createElement("br", null), "available now")),
        React.createElement("h3", { className: "f-unlock-title" }, "See all ", total, " spaces, names & locations"),
        React.createElement("p", { className: "f-unlock-lede" },
          "Enter your work email and the full list unlocks ", React.createElement("strong", null, "right here on this page"), ", every building named and placed. We'll email you a copy too."),
        React.createElement("div", { className: "f-unlock-form" },
          React.createElement("div", { className: "f-gate-input" + (err ? " err" : "") },
            React.createElement(Icon, { name: "message", size: 17, style: { color: "var(--color-text-muted)" } }),
            React.createElement("input", {
              type: "email", value: email, placeholder: dom ? "you@" + dom : "you@company.com",
              onChange: (e) => { setEmail(e.target.value); if (err) setErr(""); },
              onKeyDown: (e) => { if (e.key === "Enter") submit(); },
            })),
          React.createElement(Button, { variant: "primary", size: "lg", fullWidth: true, onClick: submit, iconRight: React.createElement(Icon, { name: "eye", size: 18 }) }, "Reveal all " + total + " spaces"),
          err && React.createElement("div", { className: "f-gate-err" }, React.createElement(Icon, { name: "x", size: 13 }), err)),
        React.createElement("div", { className: "f-gate-reassure" },
          React.createElement("span", null, React.createElement(Icon, { name: "eye", size: 14 }), "Unlocks instantly here"),
          React.createElement("span", null, React.createElement(Icon, { name: "shield", size: 14 }), "No spam, ever"),
          React.createElement("span", null, React.createElement(Icon, { name: "check", size: 14 }), "Free, we're paid by the building"))),
      revealStack && React.createElement("div", { className: "f-unlock-peek", "aria-hidden": "true" },
        stack.map((s) => React.createElement(MiniResult, { key: s.id, space: s })),
        React.createElement("div", { className: "f-unlock-peek-more" },
          React.createElement(Icon, { name: "lock", size: 13 }), "+", moreCount, " more spaces, unlock to see them all")));
  }

  // ---- Unlocked: full shortlist + refine + convert ----
  function Unlocked({ analysis, ranked, reactions, onReact, onRefine, refineState, emoji, onBook, booked, likedSpaces }) {
    const [text, setText] = useState("");
    const liked = likedSpaces || [];
    const refineChips = [
      { k: "cheaper", l: "Cheaper", icon: "wallet" },
      { k: "bigger", l: "More room to grow", icon: "users" },
      { k: "creative", l: "More creative", icon: "star", tag: "creative" },
      { k: "premium", l: "More premium", icon: "star", tag: "premium" },
      { k: "value", l: "Best value", icon: "tag", tag: "value" },
    ];
    const visible = ranked.filter((s) => reactions[s.id] !== "no");
    const refinePanel = React.createElement(React.Fragment, null,
      React.createElement("div", { className: "f-refine" },
        React.createElement("div", { className: "f-refine-label" }, React.createElement(Icon, { name: "sparkles", size: 15 }), "Customise my results"),
        React.createElement("div", { className: "f-refine-prompt" },
          React.createElement("input", {
            value: text, placeholder: "Describe what you're after, \"near a tube, warehouse feel, members-club vibe\"…",
            onChange: (e) => setText(e.target.value),
            onKeyDown: (e) => { if (e.key === "Enter" && text.trim()) { onRefine({ text: text.trim() }); setText(""); } },
          }),
          React.createElement(Button, { variant: "primary", onClick: () => { if (text.trim()) { onRefine({ text: text.trim() }); setText(""); } } }, "Ask AI")),
        React.createElement("div", { className: "f-refine-or" }, "or quick refine"),
        React.createElement("div", { className: "f-chiprow" },
          refineChips.map((c) => React.createElement("button", {
            key: c.k, className: "f-chip2 f-chip2--refine" + (refineState && refineState.key === c.k ? " on" : ""),
            onClick: () => onRefine(refineState && refineState.key === c.k ? null : { key: c.k, tag: c.tag }),
          }, React.createElement(Icon, { name: c.icon, size: 14 }), c.l)))),
      refineState && React.createElement("div", { className: "f-refine-note" },
        React.createElement(Icon, { name: "refresh", size: 14 }), "Re-ranked for ", React.createElement("em", null, refineState.label || refineState.text || refineState.key), ".",
        React.createElement("button", { className: "f-refine-clear", onClick: () => onRefine(null) }, "Clear")));
    return React.createElement(React.Fragment, null,
      React.createElement("div", { className: "f-unlocked-banner" },
        React.createElement(Icon, { name: "check", size: 16 }),
        React.createElement("span", null, "Unlocked, all ", ranked.length, " spaces with names and locations. A copy is on its way to your inbox too. ", React.createElement("strong", null, "👍 / 👎 / 💰"), " to teach the AI.")),
      React.createElement("div", { className: "f-list" },
        visible.map((s, i) => React.createElement(OfficeCard, {
          key: s.id, space: s, analysis, rank: i, reaction: reactions[s.id], emoji,
          onReact: (r) => onReact(s.id, r),
        }))),
      React.createElement(Convert, { liked, onBook, booked, analysis }),
      refinePanel);
  }

  // ---- Convert: book a viewing / get curated shortlist ----
  function Convert({ liked, onBook, booked, analysis }) {
    const [date, setDate] = useState("");
    const [done, setDone] = useState(false);
    if (booked || done) {
      return React.createElement("div", { className: "f-convert f-convert--done" },
        React.createElement("div", { className: "f-convert-tick" }, React.createElement(Icon, { name: "check", size: 24 })),
        React.createElement("h3", null, "You're booked in"),
        React.createElement("p", null, "The FlowSpace team will be in touch within the hour to confirm. We'll bring the full set of matched options for ", analysis.companyName, " to your viewing."),
        liked.length > 0 && React.createElement("div", { className: "f-convert-liked" },
          liked.map((s) => React.createElement("div", { key: s.id, className: "f-convert-liked-row" },
            React.createElement(Icon, { name: "check", size: 14 }), s.bld, " · ", s.area))));
    }
    return React.createElement("div", { className: "f-convert" },
      React.createElement("div", { className: "f-convert-head" },
        React.createElement("h3", null, liked.length ? `Ready to see ${liked.length === 1 ? "your shortlisted space" : "your " + liked.length + " shortlisted spaces"}?` : "Want our team to curate the rest?"),
        React.createElement("p", null, "Book an hour and we'll walk you round the ones you like, or have our team send a tailored shortlist. No obligation, no broker fees.")),
      liked.length > 0 && React.createElement("div", { className: "f-convert-liked" },
        liked.map((s) => React.createElement("div", { key: s.id, className: "f-convert-liked-row" },
          React.createElement(Icon, { name: "heart", size: 14 }), s.bld, " · ", s.area, " · ", gbp(s.m), "/mo"))),
      React.createElement("div", { className: "f-convert-actions" },
        React.createElement("div", { className: "f-convert-date" },
          React.createElement(Icon, { name: "calendar", size: 16, style: { color: "var(--color-text-muted)" } }),
          React.createElement("input", { type: "date", value: date, onChange: (e) => setDate(e.target.value) })),
        React.createElement(Button, { variant: "primary", size: "lg", onClick: () => { setDone(true); onBook && onBook(date); }, iconRight: React.createElement(Icon, { name: "arrowRight", size: 18 }) }, "Book a viewing")),
      React.createElement("div", { className: "f-convert-secondary" },
        React.createElement("button", { className: "f-link-btn", onClick: () => { setDone(true); onBook && onBook(null); } }, React.createElement(Icon, { name: "sparkles", size: 15 }), "Just send me the curated shortlist"),
        React.createElement("a", { className: "f-link-btn f-link-btn--wa", href: "#" }, React.createElement(Icon, { name: "message", size: 15 }), "Chat on WhatsApp")));
  }

  window.FinderScreens = { Hero, CompanyRead, Results };
})();
