const CFG = window.NORIX_FUNNEL;

function NorixMark({ size = 28, light = false }) {
  return (
    <svg viewBox="0 0 64 64" width={size} height={size} aria-hidden="true">
      <rect width="64" height="64" rx="14" fill={light ? "#FBFAF7" : "#161C2E"} />
      <path d="M 17 16 L 25 16 L 25 36 L 39 16 L 47 16 L 47 48 L 39 48 L 39 28 L 25 48 L 17 48 Z" fill={light ? "#0A0E1A" : "#FBFAF7"} />
      <circle cx="50" cy="48" r="2.4" fill="#1FA9BB" />
    </svg>
  );
}

function Wordmark() {
  return <span className="fx-nav__word">Norix<span className="fx-nav__dot">.</span></span>;
}

function BookButton({ children = "Book My Free Call", size = "lg", className = "" }) {
  return (
    <button type="button" data-book className={`fx-btn fx-btn--${size} ${className}`}>
      {children}
    </button>
  );
}

function FunnelNav() {
  const [scrolled, setScrolled] = React.useState(false);
  React.useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 8);
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  return (
    <header className={`fx-nav${scrolled ? " is-scrolled" : ""}`}>
      <div className="fx-nav__inner">
        <a href="/" className="fx-nav__brand" aria-label="Norix home">
          <NorixMark />
          <Wordmark />
        </a>
        <nav className="fx-nav__links">
          <a href="#how">How it works</a>
          <a href="#why">Why Norix</a>
          <a href="#faq">FAQ</a>
        </nav>
        <BookButton size="sm">Book a Free Call</BookButton>
      </div>
    </header>
  );
}

function FunnelHero() {
  return (
    <section className="fx-hero">
      <div className="fx-hero__glow" aria-hidden="true"></div>
      <div className="fx-wrap fx-hero__inner">
        <div className="fx-pill">For UK builders &amp; construction firms</div>
        <h1 className="fx-hero__title">
          Serious homeowners, booked into your diary.{" "}
          <span className="fx-accent">You just turn up and quote.</span>
        </h1>
        <p className="fx-hero__sub">
          We find homeowners in your area who have the budget and want the work done, check them
          properly, and book them in for you. You stay on the tools.
        </p>
        <BookButton className="fx-btn--hero" />
        <p className="fx-micro">30 minutes &middot; No hard sell &middot; You leave with a plan either way</p>
        <Vsl />
      </div>
    </section>
  );
}

function toEmbedUrl(url) {
  if (!url) return "";
  const yt = url.match(/(?:youtu\.be\/|youtube\.com\/(?:watch\?v=|embed\/|shorts\/))([\w-]{6,})/);
  if (yt) return `https://www.youtube-nocookie.com/embed/${yt[1]}?rel=0&modestbranding=1&playsinline=1`;
  const vm = url.match(/vimeo\.com\/(?:video\/)?(\d+)/);
  if (vm) return `https://player.vimeo.com/video/${vm[1]}?title=0&byline=0&portrait=0`;
  return url;
}

function Vsl() {
  const src = toEmbedUrl(CFG.VSL_URL);
  const isFile = /\.(mp4|webm|mov)(\?|#|$)/i.test(src);
  return (
    <div className="fx-vsl">
      <div className="fx-vsl__frame">
        {src && isFile ? (
          <video
            src={src}
            poster={CFG.VSL_POSTER || undefined}
            controls
            playsInline
            preload="metadata"
            aria-label="Norix: Turn Up & Quote"
          ></video>
        ) : src ? (
          <iframe
            src={src}
            title="How Norix fills construction diaries with booked quotes"
            allow="autoplay; fullscreen; picture-in-picture; encrypted-media"
            allowFullScreen
          ></iframe>
        ) : (
          <div className="fx-vsl__placeholder">
            <div className="fx-vsl__play" aria-hidden="true">
              <svg viewBox="0 0 24 24" width="30" height="30"><path d="M8 5v14l11-7z" fill="currentColor" /></svg>
            </div>
            <div className="fx-vsl__label">Watch this before you book</div>
            <div className="fx-vsl__soon">Video coming soon</div>
          </div>
        )}
      </div>
      <BookButton>I've Seen Enough &ndash; Book My Call</BookButton>
    </div>
  );
}

const PAINS = [
  { t: "Quiet weeks you didn't plan for", b: "Flat out one month, scratching around the next. Hard to hire or plan when you can't see past Friday." },
  { t: "Money burned on leads", b: "Lead sites and ads that sent you price-checkers, time-wasters and numbers that never pick up." },
  { t: "Waiting for the phone to ring", b: "Referrals are the best work going, but they come when they come. You can't build a business on them." },
  { t: "Missed calls, missed jobs", b: "You're up a ladder, they ring someone else. By the time you call back, the job's gone." },
  { t: "Losing out to worse builders", b: "Firms you'd outwork any day are landing the big jobs, just because they're easier to find." },
];

function Pain() {
  return (
    <section className="fx-section">
      <div className="fx-wrap">
        <div className="fx-eyebrow">Be honest</div>
        <h2 className="fx-h2">Great at the job. Sick of the feast and famine.</h2>
        <div className="fx-pain">
          {PAINS.map((p) => (
            <div key={p.t} className="fx-card">
              <div className="fx-card__x" aria-hidden="true">&times;</div>
              <h3 className="fx-card__t">{p.t}</h3>
              <p className="fx-card__b">{p.b}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

const FILTER = [
  { t: "Budget", b: "Can actually afford the job." },
  { t: "Postcode", b: "Inside the patch you cover." },
  { t: "Job type", b: "Work you want, not work you'd turn down." },
  { t: "Start date", b: "Ready to go, not ‘maybe next year’." },
  { t: "Reachable", b: "A real person who answers the phone." },
];

function Filter() {
  return (
    <section className="fx-section fx-section--alt">
      <div className="fx-wrap">
        <div className="fx-eyebrow">Only the good ones get through</div>
        <h2 className="fx-h2">We do the vetting. You do the quoting.</h2>
        <p className="fx-lead">
          Every enquiry gets a reply within minutes, evenings and weekends included, plus a few quick
          questions on WhatsApp before it ever reaches you. If they don't tick all five boxes, you never hear about them.
        </p>
        <div className="fx-filter">
          {FILTER.map((f, i) => (
            <div key={f.t} className="fx-filter__item">
              <span className="fx-filter__n">
                <span className="fx-filter__num">{i + 1}</span>
                <svg className="fx-filter__tick" viewBox="0 0 24 24" aria-hidden="true">
                  <path pathLength="1" d="M5 12.5l4.5 4.5L19 7.5" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round" />
                </svg>
              </span>
              <div>
                <div className="fx-filter__t">{f.t}</div>
                <div className="fx-filter__b">{f.b}</div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

const STEPS = [
  { t: "A straight-talking call", b: "30 minutes on your trade, your area and the jobs you want more of. If we can't help, we'll tell you." },
  { t: "We set it all up", b: "Adverts, wording, targeting, the follow-up and the booking. You don't lift a finger." },
  { t: "Homeowners start enquiring", b: "Your adverts go in front of local homeowners who are looking for your kind of work right now." },
  { t: "We vet every one", b: "Each enquiry is answered fast and checked against the five boxes. The rest are filtered out." },
  { t: "You turn up and quote", b: "The ones who pass are booked straight into your diary, with their details ready for you." },
  { t: "We keep sharpening it", b: "Every week we look at what's bringing in the best jobs and put more behind it." },
];

function Process() {
  return (
    <section className="fx-section" id="how">
      <div className="fx-wrap">
        <div className="fx-eyebrow">From first call to booked quotes</div>
        <h2 className="fx-h2">What happens after you book</h2>
        <p className="fx-lead">No jargon, no long contracts. This is the whole thing.</p>
        <ol className="fx-steps">
          {STEPS.map((s, i) => (
            <li key={s.t} className="fx-step">
              <span className="fx-step__n">{String(i + 1).padStart(2, "0")}</span>
              <h3 className="fx-step__t">{s.t}</h3>
              <p className="fx-step__b">{s.b}</p>
            </li>
          ))}
        </ol>
        <div className="fx-center"><BookButton>Start With a Free Call</BookButton></div>
      </div>
    </section>
  );
}

function WhyNorix() {
  return (
    <section className="fx-section" id="why">
      <div className="fx-wrap">
        <div className="fx-guarantee">
          <div className="fx-eyebrow fx-eyebrow--center">Why builders work with us</div>
          <h2 className="fx-h2 fx-h2--center">
            Less chasing. <span className="fx-accent">More quoting.</span>
          </h2>
          <p className="fx-lead fx-lead--center">You're paying for jobs in the diary, not clicks, likes or a fancy report.</p>
          <ul className="fx-checks">
            <li>Only vetted homeowners make it into your diary</li>
            <li>Every enquiry answered within minutes, even when you're on site</li>
            <li>Clear weekly numbers, so you always know what you're getting</li>
          </ul>
          <BookButton>Let's Talk About Your Area</BookButton>
        </div>
      </div>
    </section>
  );
}

const FAQS = [
  { q: "How quickly will I see jobs come in?", a: "Setup takes about a week. Once your adverts are live, the first booked quotes usually land within the first couple of weeks." },
  { q: "How much does it cost?", a: "It depends on your area, your trade and how many jobs you're after, so we work it out on the call. You'll get one clear price with no hidden extras before you agree to anything." },
  { q: "What do I actually have to do?", a: "Turn up and quote. We run the adverts, the follow-up and the booking. We'll need about an hour of your time at the start so we understand the work you do." },
  { q: "What counts as a booked quote?", a: "A homeowner in your area, with the budget and timing for work you do, who has agreed a time for you to come out and price the job." },
  { q: "Will you send the same homeowners to my competitors?", a: "No. We keep the number of firms we work with in each area small, so you're not fighting another builder for the same lead." },
];

function FunnelFAQ() {
  const [open, setOpen] = React.useState(0);
  return (
    <section className="fx-section fx-section--alt" id="faq">
      <div className="fx-wrap fx-wrap--narrow">
        <div className="fx-eyebrow fx-eyebrow--center">Before you book</div>
        <h2 className="fx-h2 fx-h2--center">The questions builders ask us</h2>
        <div className="fx-faq">
          {FAQS.map((f, i) => (
            <div key={f.q} className={`fx-faq__item${open === i ? " is-open" : ""}`}>
              <button type="button" className="fx-faq__q" aria-expanded={open === i} onClick={() => setOpen(open === i ? -1 : i)}>
                <span>{f.q}</span>
                <span className="fx-faq__icon" aria-hidden="true">+</span>
              </button>
              <div className="fx-faq__a"><div><p>{f.a}</p></div></div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function FinalCta() {
  return (
    <section className="fx-section fx-final">
      <div className="fx-hero__glow fx-hero__glow--low" aria-hidden="true"></div>
      <div className="fx-wrap fx-center">
        <h2 className="fx-h2 fx-h2--center">Your next good job is already looking for a builder.</h2>
        <p className="fx-lead fx-lead--center">
          Make sure it finds you. On a free 30-minute call we'll show you how many homeowners are looking
          in your area, what it costs to reach them, and whether we're the right fit.
        </p>
        <BookButton />
        <p className="fx-micro">Takes under a minute &middot; Pick a time that suits you</p>
      </div>
    </section>
  );
}

function FunnelFooter() {
  return (
    <footer className="fx-footer">
      <div className="fx-wrap fx-footer__inner">
        <div className="fx-footer__brand">
          <NorixMark size={26} />
          <Wordmark />
        </div>
        <nav className="fx-footer__links">
          <a href="#how">How it works</a>
          <a href="#why">Why Norix</a>
          <a href="#faq">FAQ</a>
          <a href="mailto:ahmet@norixai.co.uk">ahmet@norixai.co.uk</a>
        </nav>
        <div className="fx-footer__legal">&copy; 2026 Norix &middot; UK-based &middot; GDPR compliant</div>
      </div>
    </footer>
  );
}

// Shows once the hero (and both its Book buttons) has scrolled off the top, and steps aside while the
// closing section's Book button is on screen, so there are never two identical buttons stacked.
// Watches the hero section, not its last button: the hero is always on screen at load, so a fling or
// anchor jump that skips straight past the button still registers as leaving it.
function StickyBar() {
  const [show, setShow] = React.useState(false);
  React.useEffect(() => {
    const hero = document.querySelector(".fx-hero");
    const finalBtn = document.querySelector(".fx-final [data-book]");
    if (!hero || !finalBtn) return;
    let pastHero = false;
    let finalInView = false;
    // Bottom margin = the bar's own height, so "in view" means visible above where the bar sits
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.target === hero) pastHero = !e.isIntersecting && e.boundingClientRect.top < 0;
        else finalInView = e.isIntersecting;
      });
      setShow(pastHero && !finalInView);
    }, { rootMargin: "0px 0px -88px 0px" });
    io.observe(hero);
    io.observe(finalBtn);
    return () => io.disconnect();
  }, []);
  return (
    <div className={`fx-sticky${show ? " is-shown" : ""}`} aria-hidden={!show}>
      <div className="fx-sticky__inner">
        <span className="fx-sticky__text">Serious homeowners, booked into your diary</span>
        <BookButton size="md" />
      </div>
    </div>
  );
}

Object.assign(window, { FunnelNav, FunnelHero, Pain, Filter, Process, WhyNorix, FunnelFAQ, FinalCta, FunnelFooter, StickyBar });
