/* global React, ReactDOM, Faq, Footer, Lenis */const { useEffect, useState } = React;

/* Smooth scroll (shared behavior with the homepage) */
function useLenis() {
  useEffect(() => {
    if (typeof Lenis === "undefined") return;
    const lenis = new Lenis({
      lerp: 0.115,
      duration: 0.9,
      easing: (t) => 1 - Math.pow(1 - t, 4),
      smoothWheel: true,
      smoothTouch: false,
      wheelMultiplier: 0.95,
    });
    window.__lenis = lenis;
    let rafId;
    const raf = (time) => { lenis.raf(time); rafId = requestAnimationFrame(raf); };
    rafId = requestAnimationFrame(raf);
    const anchorHandler = (e) => {
      const a = e.target.closest('a[href^="#"]');
      if (!a) return;
      const href = a.getAttribute("href");
      if (href.length < 2) return;
      const el = document.querySelector(href);
      if (!el) return;
      e.preventDefault();
      const easeInOutCubic = (t) => (t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2);
      lenis.scrollTo(el, { offset: -40, duration: 1.5, easing: easeInOutCubic });
    };
    document.addEventListener("click", anchorHandler);
    return () => {
      cancelAnimationFrame(rafId);
      document.removeEventListener("click", anchorHandler);
      lenis.destroy();
      delete window.__lenis;
    };
  }, []);
}

/* Reveal on scroll (matches homepage timing) */
function useReveal() {
  useEffect(() => {
    const els = [...document.querySelectorAll(".reveal")];
    const reveal = () => {
      const trigger = window.innerHeight * 0.82;
      els.forEach((el) => {
        if (el.getAttribute("data-visible") === "true") return;
        if (el.getBoundingClientRect().top < trigger) {
          el.setAttribute("data-visible", "true");
        }
      });
    };
    reveal();
    window.addEventListener("scroll", reveal, { passive: true });
    window.addEventListener("resize", reveal);
    let lenis = null;
    const attach = () => {
      if (!lenis && window.__lenis) { lenis = window.__lenis; lenis.on("scroll", reveal); }
    };
    attach();
    const poll = setInterval(attach, 120);
    setTimeout(() => clearInterval(poll), 2000);
    return () => {
      window.removeEventListener("scroll", reveal);
      window.removeEventListener("resize", reveal);
      if (lenis) lenis.off("scroll", reveal);
      clearInterval(poll);
    };
  }, []);
}

/* Cal.com inline embed */
function CalEmbed() {
  useEffect(() => {
    (function (C, A, L) {
      let p = function (a, ar) { a.q.push(ar); };
      let d = C.document;
      C.Cal = C.Cal || function () {
        let cal = C.Cal; let ar = arguments;
        if (!cal.loaded) {
          cal.ns = {}; cal.q = cal.q || [];
          d.head.appendChild(d.createElement("script")).src = A;
          cal.loaded = true;
        }
        if (ar[0] === L) {
          const api = function () { p(api, arguments); };
          const namespace = ar[1];
          api.q = api.q || [];
          if (typeof namespace === "string") {
            cal.ns[namespace] = cal.ns[namespace] || api;
            p(cal.ns[namespace], ar);
            p(cal, ["initNamespace", namespace]);
          } else p(cal, ar);
          return;
        }
        p(cal, ar);
      };
    })(window, "https://app.cal.com/embed/embed.js", "init");

    window.Cal("init", "scalenic-call", { origin: "https://cal.com" });
    window.Cal.ns["scalenic-call"]("inline", {
      elementOrSelector: "#cal-embed-call",
      config: { layout: "month_view", theme: "light" },
      calLink: "igorsalagin/15min",
    });
    window.Cal.ns["scalenic-call"]("ui", {
      theme: "light",
      cssVarsPerTheme: {
        light: { "cal-brand": "#0F0F0F" },
        dark:  { "cal-brand": "#F6F4EF" },
      },
      hideEventTypeDetails: false,
      layout: "month_view",
    });
  }, []);

  return (
    <div className="booking-card">
      <div id="cal-embed-call" className="cal-embed" />
    </div>
  );
}

function CallHero() {
  return (
    <section className="call-hero" id="top">
      <div className="narrow call-hero-inner">
        <a className="call-brand reveal" data-visible="true" href="index.html" aria-label="Scalenic - home">
          <span className="call-dia" />
          <span>Scalenic</span>
        </a>
        <h1 className="h-display call-headline reveal" data-visible="true">
          Let&rsquo;s talk.
        </h1>
        <p className="lead call-sub reveal" data-visible="true">
          A 15-minute call on your business, your site, your goals, and whether we&rsquo;re a fit.
        </p>
      </div>
    </section>
  );
}

function ScheduleAgainCta() {
  const [isMobile, setIsMobile] = useState(false);
  useEffect(() => {
    const mq = window.matchMedia("(max-width: 700px)");
    const update = () => setIsMobile(mq.matches);
    update();
    mq.addEventListener("change", update);
    return () => mq.removeEventListener("change", update);
  }, []);

  const scrollUp = (e) => {
    e.preventDefault();
    const el = document.getElementById("book");
    if (!el) return;
    if (window.__lenis) {
      const easeInOutCubic = (t) => (t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2);
      window.__lenis.scrollTo(el, { offset: -40, duration: 1.5, easing: easeInOutCubic });
    } else {
      const top = el.getBoundingClientRect().top + window.scrollY - 40;
      window.scrollTo({ top, behavior: "smooth" });
    }
  };

  const innerStyle = isMobile
    ? { display: "block", width: "100%" }
    : {
        display: "flex",
        justifyContent: "center",
        alignItems: "center",
        width: "100%",
        textAlign: "center",
      };

  const btnStyle = isMobile
    ? {
        display: "flex",
        width: "100%",
        minWidth: 0,
        margin: 0,
        justifyContent: "center",
      }
    : {
        display: "inline-flex",
        margin: "0 auto",
        minWidth: 280,
        justifyContent: "center",
      };

  return (
    <section className="section call-again">
      <div className="narrow call-again-inner" style={innerStyle}>
        <button className="btn" onClick={scrollUp} style={btnStyle}>
          Schedule a call
        </button>
      </div>
    </section>
  );
}

function CallCred() {
  return (
    <div
      className="call-cred reveal"
      data-visible="true"
      style={{
        display: "flex",
        justifyContent: "center",
        alignItems: "center",
        width: "100%",
        margin: "0 0 32px",
        padding: 0,
        textAlign: "center",
      }}
    >
      <div
        className="cta-final-cred"
        style={{
          display: "inline-flex",
          flexDirection: "row",
          alignItems: "center",
          gap: 12,
          margin: 0,
        }}
      >
        <img className="cta-final-avatar" src="assets/igor-avatar.png" alt="Igor Šalagin" width="56" height="56" />
        <span className="cta-final-cred-text">
          <strong>Igor Šalagin</strong>
          <span className="cta-final-cred-sub">Shipped 65 websites</span>
        </span>
      </div>
    </div>
  );
}

function CopyEmail() {
  const [copied, setCopied] = useState(false);
  const copy = () => {
    const email = "igor@scalenic.com";
    const fallback = () => {
      try {
        const ta = document.createElement("textarea");
        ta.value = email;
        ta.setAttribute("readonly", "");
        ta.style.position = "fixed";
        ta.style.top = "-9999px";
        document.body.appendChild(ta);
        ta.select();
        document.execCommand("copy");
        document.body.removeChild(ta);
      } catch (e) { /* no-op */ }
    };
    if (navigator.clipboard && navigator.clipboard.writeText) {
      navigator.clipboard.writeText(email).catch(fallback);
    } else {
      fallback();
    }
    setCopied(true);
    setTimeout(() => setCopied(false), 1800);
  };
  return (
    <div
      className="email-row"
      style={{
        marginTop: 28,
        display: "flex",
        flexDirection: "column",
        alignItems: "center",
        textAlign: "center",
        gap: 14,
        width: "100%",
      }}
    >
      <span className="email-row-label" style={{ textAlign: "center" }}>Or just email:</span>
      <div
        className="email-row-actions"
        style={{
          display: "flex",
          flexDirection: "column",
          alignItems: "center",
          textAlign: "center",
          gap: 12,
          width: "100%",
        }}
      >
        <a
          href="mailto:igor@scalenic.com"
          className="email-val"
          style={{ textAlign: "center" }}
        >
          igor@scalenic.com
        </a>
        <button
          className="copy-btn"
          data-copied={copied}
          onClick={copy}
          type="button"
          style={{ justifyContent: "center" }}
        >
          {copied ? "Copied" : "Copy email"}
        </button>
      </div>
    </div>
  );
}

function CallApp() {
  useLenis();
  useReveal();
  return (
    <React.Fragment>
      <CallHero />
      <section className="section call-embed-section" id="book" aria-label="Booking calendar">
        <div className="narrow reveal" data-visible="true">
          <CallCred />
          <CalEmbed />
          <CopyEmail />
        </div>
      </section>
      <div className="reveal"><Faq /></div>
      <div className="reveal"><ScheduleAgainCta /></div>
    </React.Fragment>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<CallApp />);
