// Public case studies: production case-study structure with route-scoped evidence.
const LANDING = "/conversion";
const STUDY = JSON.parse(document.getElementById("public-study-data").textContent);
const SECTIONS = [
  {id:"client",n:"Client & Context",num:"01"},
  {id:"challenge",n:"Challenge & Goals",num:"02"},
  {id:"discovery",n:"Discovery",num:"03"},
  {id:"solution",n:"Solutions",num:"04"},
  {id:"implementation",n:"Implementation & Development",num:"05"},
  {id:"results",n:"Results & Impact",num:"06"}
];
const OTHER = cwRelatedCases(STUDY.slug, STUDY.category);
function useScrollSpy(ids, offset = 130) {
  const [active, setActive] = useState(null);
  useEffect(() => {
    const onScroll = () => {
      let cur = null;
      for (const id of ids) {
        const el = document.getElementById(id);
        if (el) {
          const anchorOffset = parseFloat(getComputedStyle(el).scrollMarginTop) || 0;
          if (el.getBoundingClientRect().top <= Math.max(offset, anchorOffset) + 2) cur = id;
        }
      }
      setActive(cur);
    };
    window.addEventListener("scroll", onScroll, { passive: true });
    window.addEventListener("resize", onScroll);
    const observer = new ResizeObserver(onScroll);
    const article = document.querySelector('.csx-article');
    if (article) observer.observe(article);
    onScroll();
    return () => { window.removeEventListener("scroll", onScroll); window.removeEventListener("resize", onScroll); observer.disconnect(); };
  }, []);
  return active;
}

function Media({src,alt,caption,eager=false}) {
  return <figure className="sw-figure">
    <a href={src} target="_blank" rel="noopener noreferrer" aria-label={"Open full-size image: "+alt}>
      <img src={src} alt={alt} width={STUDY.imageSizes?.[src]?.[0]} height={STUDY.imageSizes?.[src]?.[1]} loading={eager?"eager":"lazy"} decoding="async" />
    </a>
    {caption && <figcaption className="csx-figcap">{caption}</figcaption>}
  </figure>;
}
function Hero() {
  const [tab,setTab]=useState(Object.keys(STUDY.tabs)[0]);
  const keys=Object.keys(STUDY.tabs);
  function moveTab(e,index) {
    let next=index;
    if(e.key==="ArrowRight") next=(index+1)%keys.length;
    else if(e.key==="ArrowLeft") next=(index-1+keys.length)%keys.length;
    else if(e.key==="Home") next=0;
    else if(e.key==="End") next=keys.length-1;
    else return;
    e.preventDefault();setTab(keys[next]);document.getElementById("public-study-tab-"+next).focus();
  }
  return <header className="csx-hero" id="top">
    <div className="haze-bloom" aria-hidden="true" />
    <div className="csx-wrap">
      <div className="csx-crumb"><a href={LANDING+"#showcase"}>Case Studies</a><i className="ri-arrow-right-s-line"/><span className="csx-crumb-cur">{STUDY.name}</span></div>
      <div className="csx-hero-grid">
        <div className="csx-hero-text">
          <span className="csx-hero-ghost" aria-hidden="true">{STUDY.name}</span>
          <div className="eyebrow csx-hero-eyebrow"><span className="dot"/>{STUDY.name} · {STUDY.engagement}</div>
          <h1 className="csx-hero-title">{STUDY.headline[0]} <span className="gradient-text">{STUDY.headline[1]}</span></h1>
        </div>
        <div className="csx-hero-media sw-hero-media"><img src={STUDY.hero} alt={STUDY.heroAlt} fetchpriority="high" /></div>
        <div className="csx-hero-metrics">
          <div className="csx-tabs" role="tablist" aria-label="Case study metrics">{keys.map((key,i)=><button key={key} id={"public-study-tab-"+i} role="tab" aria-controls="public-study-stats" aria-selected={tab===key} tabIndex={tab===key?0:-1} className={"csx-tab"+(tab===key?" is-active":"")} onClick={()=>setTab(key)} onKeyDown={e=>moveTab(e,i)}>{key}</button>)}</div>
          <div className="csx-stats" id="public-study-stats" role="tabpanel" aria-labelledby={"public-study-tab-"+keys.indexOf(tab)}>{STUDY.tabs[tab].map((s,i)=><div className="csx-stat" key={tab+i}><div className="csx-stat-num">{s.v}{s.up&&<i className="ri-arrow-up-line csx-up"/>}</div><div className="csx-stat-label">{s.l}</div></div>)}</div>
        </div>
      </div>
    </div>
  </header>;
}
function MetaBand() {
  return <section className="csx-meta"><div className="csx-wrap"><div className="glass csx-meta-card"><div className="csx-meta-grid">
    <div><div className="csx-label">Summary</div><p className="csx-summary-text">{STUDY.summary}</p><div className="csx-label">Services</div><div className="csx-chips">{STUDY.services.map((s,i)=><span className="csx-chip" key={s}><i className={["ri-focus-3-line","ri-flask-line","ri-pen-nib-line","ri-code-s-slash-line"][i]}/>{s}</span>)}</div></div>
    <div className="csx-meta-sub"><div className="csx-facts">{STUDY.facts.map(([label,value],i)=><div className="csx-fact" key={label}><span className="csx-fact-ic"><i className={["ri-store-2-line","ri-focus-3-line","ri-stack-line"][i]}/></span><div><p className="csx-fact-t">{label}</p><p className="csx-fact-v">{value}</p></div></div>)}</div></div>
  </div></div></div></section>;
}
function Bullets({items}) { return <ul className="csx-list">{items.map((s,i)=><li key={i}>{s}</li>)}</ul>; }
function Spec({rows}) {return <dl className="csx-spec">{rows.map(([k,v])=><React.Fragment key={k}><dt className="csx-spec-k">{k}</dt><dd className="csx-spec-v">{v}</dd></React.Fragment>)}</dl>;}
function Section({id,children}) {const s=SECTIONS.find(s=>s.id===id);return <section id={id} className="csx-sec" data-screen-label={s.n}><h2 className="csx-h2"><span className="csx-h2-num">{s.num}</span>{s.n}</h2>{children}</section>;}
function EvidenceCard({item,index}) {
  return <div className="csx-test">
    <div className="csx-test-head"><span className="csx-test-badge">{STUDY.engagement === "CRO Audit" ? "Audit" : "Tracking"} {String(index+1).padStart(2,"0")}</span><h3 className="csx-test-title">{item.title}</h3></div>
    <p className="public-evidence-context">{item.label}</p>
    <Spec rows={item.rows}/>
    <div className="csx-result sw-result-neutral"><span className="csx-result-ic"><i className="ri-checkbox-circle-line"/></span><div className="csx-result-txt">{item.outcome}</div></div>
    <div className="public-evidence-single">
      {item.media.map(media=><div key={media.src}>{media.label&&<p className="csx-ba-tag public-evidence-label">{media.label}</p>}<Media {...media}/></div>)}
    </div>
    {item.note&&<p className="csx-note">{item.note}</p>}
  </div>;
}
function ClientTestimonial() {
  const t=STUDY.testimonial;
  if(!t) return null;
  return <div className="glass csx-quote public-study-quote">
    {t.image&&<div className="csx-quote-photo"><img src={t.image} alt={t.name} loading="lazy"/></div>}
    <div><blockquote className="csx-quote-txt">“{t.text}”</blockquote><div className="csx-quote-by"><p className="csx-quote-name">{t.name}</p>{t.role&&<p className="csx-quote-role">{t.role}</p>}</div></div>
    {t.logo&&<img className="csx-quote-logo" src={t.logo} alt="" loading="lazy"/>}
  </div>;
}
function Article() {
  return <article className="csx-article">
    <Section id="client">{STUDY.context.map((p,i)=><p className="csx-p" key={i}>{p}</p>)}</Section>
    <Section id="challenge"><div className="csx-cols2"><div className="csx-subcard csx-subcard--neg"><p className="csx-subcard-h"><i className="ri-error-warning-line"/>Challenges</p><Bullets items={STUDY.challenges}/></div><div className="csx-subcard csx-subcard--pos"><p className="csx-subcard-h"><i className="ri-focus-3-line"/>Goals</p><Bullets items={STUDY.goals}/></div></div></Section>
    <Section id="discovery"><Bullets items={STUDY.discovery}/>{STUDY.discoveryMedia&&<Media {...STUDY.discoveryMedia}/>}</Section>
    <Section id="solution">{STUDY.highlights.map((item,i)=><EvidenceCard item={item} index={i} key={item.title}/>)}</Section>
    <Section id="implementation"><Spec rows={STUDY.implementation}/></Section>
    <Section id="results"><div className="glass csx-winbox"><p className="csx-winbox-h">Highlighted outcomes</p>{STUDY.results.items.map(([label,value])=><div className="csx-winrow" key={label}><span className="csx-winrow-l">{label}</span><span className="csx-winrow-v">{value}</span></div>)}</div>{STUDY.results.narrative.map((p,i)=><p className="csx-p" key={i}>{p}</p>)}<p className="csx-note">{STUDY.results.note}</p></Section>
    <ClientTestimonial/>
    <ClosingCTA/>
  </article>;
}
function Rail({ active }) {
  return (
    <aside className="csx-rail">
      <div>
        <div className="csx-toc-title"><i className="ri-list-unordered" />Table of Contents</div>
        <nav className="csx-toc">
          {SECTIONS.map((s) => (
            <a key={s.id} href={"#" + s.id} className={"csx-toc-link" + (active === s.id ? " is-active" : "")}>{s.n}</a>
          ))}
        </nav>
      </div>
      <div className="glass glass--featured csx-wins">
        <div className="csx-wins-h">Find your next conversion priorities.</div>
        <p className="csx-wins-p">Review your website with Edu in a free 30-minute session. Identify 2–3 conversion priorities and leave knowing what to tackle next.</p>
        <a href={CW_BOOKING.url} data-cw-booking="" className="btn btn-primary btn-sm">Book a free walkthrough <i className="ri-arrow-right-line" /></a>
        <div className="csx-wins-proof">
          <div className="csx-wins-badge">
            <span className="csx-wins-stars csx-wins-stars--tp"><i className="ri-star-fill" /><i className="ri-star-fill" /><i className="ri-star-fill" /><i className="ri-star-fill" /><i className="ri-star-fill" /></span>
            <img src={assetUrl("assets/trustpilot-wordmark.png")} alt="Trustpilot" />
          </div>
          <div className="csx-wins-badge">
            <span className="csx-wins-stars"><i className="ri-star-fill" /><i className="ri-star-fill" /><i className="ri-star-fill" /><i className="ri-star-fill" /><i className="ri-star-fill" /></span>
            <img src={assetUrl("assets/clutch-wordmark.png")} alt="Clutch" />
          </div>
        </div>
      </div>
    </aside>
  );
}

// ---- mobile TOC dropdown ------------------------------------------------
function MobileTOC({ active }) {
  const [open, setOpen] = useState(false);
  const cur = SECTIONS.find((s) => s.id === active);
  const label = cur ? cur.n : "Table of Contents";
  return (
    <div className={"csx-toc-mob" + (open ? " is-open" : "")}>
      <button className="csx-toc-mob-btn" onClick={() => setOpen(!open)} aria-expanded={open}>
        <span className="csx-toc-mob-cur"><i className="ri-list-unordered" />{label}</span>
        <i className="ri-arrow-down-s-line csx-toc-mob-chev" />
      </button>
      <div className="csx-toc-mob-panel">
        <div className="csx-toc-mob-list">
          <div className="csx-toc-mob-list-inner">
            {SECTIONS.map((s) => (
              <a key={s.id} href={"#" + s.id} className={active === s.id ? "is-active" : ""} onClick={() => setOpen(false)}>{s.n}</a>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

// ---- mobile sticky CTA dropdown -----------------------------------------
function MobileCTA() {
  const [open, setOpen] = useState(false);
  const [show, setShow] = useState(false);
  useEffect(() => {
    const onScroll = () => {
      const a = document.getElementById("client");
      const past = a ? a.getBoundingClientRect().top < window.innerHeight * 0.85 : false;
      setShow(past);
    };
    window.addEventListener("scroll", onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  useEffect(() => {
    document.body.classList.toggle("csx-cta-on", show);
    return () => document.body.classList.remove("csx-cta-on");
  }, [show]);
  return (
    <div className={"csx-mobcta" + (open ? " is-open" : "") + (show ? " is-visible" : "")}>
      <button className="csx-mobcta-bar" onClick={() => setOpen(!open)} aria-expanded={open}>
        <span className="csx-mobcta-lead"><span className="csx-mobcta-dot" />Book a free walkthrough</span>
        <i className="ri-arrow-up-s-line csx-mobcta-chev" />
      </button>
      <div className="csx-mobcta-panel">
        <div className="csx-mobcta-inner">
          <div className="csx-mobcta-content">
            <div className="csx-mobcta-h">Know what to tackle next.</div>
            <p className="csx-mobcta-p">Review your website with Edu in a free 30-minute session. Identify 2–3 conversion priorities and leave knowing what to tackle next.</p>
            <a href={CW_BOOKING.url} data-cw-booking="" className="btn btn-primary" onClick={() => setOpen(false)}>Book a free walkthrough <i className="ri-arrow-right-line" /></a>
            <div className="csx-wins-proof csx-mobcta-proof">
              <div className="csx-wins-badge">
                <span className="csx-wins-stars csx-wins-stars--tp"><i className="ri-star-fill" /><i className="ri-star-fill" /><i className="ri-star-fill" /><i className="ri-star-fill" /><i className="ri-star-fill" /></span>
                <img src={assetUrl("assets/trustpilot-wordmark.png")} alt="Trustpilot" />
              </div>
              <div className="csx-wins-badge">
                <span className="csx-wins-stars"><i className="ri-star-fill" /><i className="ri-star-fill" /><i className="ri-star-fill" /><i className="ri-star-fill" /><i className="ri-star-fill" /></span>
                <img src={assetUrl("assets/clutch-wordmark.png")} alt="Clutch" />
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}


function ClosingCTA() { return (<div className="glass glass--featured csx-cta">
          <div className="haze-bloom" aria-hidden="true" />
          <div className="csx-cta-inner">
            <h3 className="csx-cta-h">Find the next priorities for your website.</h3>
            <div className="csx-cta-checks">
              <div className="csx-cta-check"><i className="ri-check-line" />Review your website with Edu in a free 30-minute session.</div>
              <div className="csx-cta-check"><i className="ri-check-line" />Identify 2–3 conversion priorities and what to tackle next.</div>
              <div className="csx-cta-check"><i className="ri-check-line" />Discuss the right next step. Full Shopify audits start at $1,000.</div>
            </div>
            <div className="csx-cta-actions">
              <a href={CW_BOOKING.url} data-cw-booking="" className="btn btn-primary">Book a free walkthrough <i className="ri-arrow-right-line" /></a>
            </div>
          </div>
        </div>); }
function OtherCases() {
  const trackRef = useRef(null);
  const [idx, setIdx] = useState(0);
  const scrollTo = (i) => {
    const track = trackRef.current; if (!track) return;
    const card = track.children[i];
    if (card) track.scrollTo({ left: card.offsetLeft - track.offsetLeft, behavior: "smooth" });
  };
  const onScroll = () => {
    const track = trackRef.current; if (!track) return;
    let nearest = 0, best = Infinity;
    [...track.children].forEach((c, i) => {
      const d = Math.abs(c.offsetLeft - track.offsetLeft - track.scrollLeft);
      if (d < best) { best = d; nearest = i; }
    });
    setIdx(nearest);
  };
  const step = (dir) => scrollTo(Math.max(0, Math.min(OTHER.length - 1, idx + dir)));
  return (
    <section className="csx-other">
      <div className="csx-wrap">
        <div className="csx-other-head">
          <h2 className="csx-other-title">Other case studies</h2>
          <div className="csx-other-nav">
            <button className="csx-arrow" onClick={() => step(-1)} aria-label="Previous"><i className="ri-arrow-left-line" /></button>
            <button className="csx-arrow" onClick={() => step(1)} aria-label="Next"><i className="ri-arrow-right-line" /></button>
          </div>
        </div>
        <div className="csx-other-track" ref={trackRef} onScroll={onScroll}>
          {OTHER.map((c) => (
            <article className="csx-other-card" key={c.id}>
              <div className="csx-other-media"><img src={assetUrl(c.img)} alt={c.name} loading="lazy" /></div>
              <div className="csx-other-body">
                <p className="csx-other-desc">{c.desc}</p>
                <div className="csx-other-metrics">
                  {c.m.map(([txt, up], i) => (
                    <div className="csx-other-metric" key={i}>
                      <i className={up ? "ri-arrow-up-line" : "ri-timer-flash-line"} style={{ color: up ? "var(--success)" : "var(--violet-400)" }} />
                      <span>{txt}</span>
                    </div>
                  ))}
                </div>
                {c.href && <a href={c.href} className="csx-other-link">View case study <i className="ri-arrow-right-line" /></a>}
              </div>
            </article>
          ))}
        </div>
        <div className="csx-dots">
          {OTHER.map((c, i) => <button key={i} className={"csx-dot" + (idx === i ? " is-active" : "")} onClick={() => scrollTo(i)} aria-label={"Go to " + c.name} />)}
        </div>
      </div>
    </section>
  );
}

// ---- footer -------------------------------------------------------------
function CaseFooter() {
  const cols = [
    { head: "Conversion Works", links: [["The problem", LANDING + "#work"], ["What we build", LANDING + "#workers"], ["Process", LANDING + "#how"], ["Case studies", LANDING + "#showcase"], ["Pricing", LANDING + "#pricing"]] },
    { head: "Taurist", links: [["Taurist Technologies", "https://taurist.com"], ["Siteworks", "/siteworks"], ["Workers", "/workers"], ["About", "/about"], ["Notes", "/notes"], ["Email Us", "mailto:hello@taurist.com"]] },
  ];
  const link = { fontFamily: "var(--font-body)", fontWeight: 300, fontSize: 14, color: "var(--fg3)", textDecoration: "none", transition: "color .15s", width: "fit-content" };
  const colHead = { fontFamily: "var(--font-ui)", fontSize: 12, fontWeight: 600, letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--fg2)", marginBottom: 16 };
  return (
    <footer style={{ borderTop: "1px solid var(--border-subtle)", background: "var(--neutral-900)", paddingTop: 64, position: "relative" }}>
      <div className="streak" style={{ position: "absolute", top: 0, left: 0, right: 0, opacity: 0.4 }} />
      <div className="wrap">
        <div style={{ display: "grid", gap: 40, paddingBottom: 52, gridTemplateColumns: "1.6fr 1fr 1fr" }} className="footer-grid">
          <div>
            <div style={{ display: "flex", alignItems: "center", gap: 14, flexWrap: "wrap", rowGap: 8 }}>
              <Logo height={40} />
              <span style={{ width: 1, height: 20, background: "var(--border-default)" }} />
              <span style={{ fontFamily: "var(--font-ui)", fontSize: 12, fontWeight: 600, letterSpacing: "0.06em", textTransform: "uppercase", color: "var(--fg3)" }}>by Taurist Technologies Inc</span>
            </div>
            <p style={{ fontFamily: "var(--font-body)", fontWeight: 300, fontSize: 14, lineHeight: 1.6, color: "var(--fg2)", margin: "20px 0 0", maxWidth: 360 }}>
              Founder-led Shopify CRO. Start with a free 30-minute website walkthrough with Edu. Full Shopify audits start at $1,000.
            </p>
            <a href={CW_BOOKING.url} data-cw-booking="" className="btn btn-primary btn-sm" style={{ marginTop: 24 }}>Book a free walkthrough <i className="ri-arrow-right-line" /></a>
          </div>
          {cols.map((c) => (
            <div key={c.head}>
              <div style={colHead}>{c.head}</div>
              <div style={{ display: "flex", flexDirection: "column", gap: 11 }}>
                {c.links.map(([t, h]) => (
                  <a key={t} href={h} style={link} {...(h.startsWith("http") ? { target: "_blank", rel: "noopener noreferrer" } : {})}
                    onMouseEnter={(e) => (e.currentTarget.style.color = "var(--magenta-300)")}
                    onMouseLeave={(e) => (e.currentTarget.style.color = "var(--fg3)")}>{t}</a>
                ))}
              </div>
            </div>
          ))}
        </div>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "22px 0", borderTop: "1px solid var(--border-subtle)", flexWrap: "wrap", gap: 16 }}>
          <span style={{ fontFamily: "var(--font-body)", fontSize: 13, color: "var(--fg3)" }}>© 2026 Taurist Technologies Inc. All rights reserved.</span>
          <a href="/siteworks" target="_blank" rel="noopener noreferrer" style={{ display: "inline-flex", alignItems: "center", gap: 9, fontFamily: "var(--font-body)", fontSize: 13, color: "var(--fg3)", textDecoration: "none", transition: "color .15s" }}
            onMouseEnter={(e) => (e.currentTarget.style.color = "var(--fg1)")}
            onMouseLeave={(e) => (e.currentTarget.style.color = "var(--fg3)")}>
            Like this site? Built by
            <img src={assetUrl("assets/siteworks-mark.avif")} alt="" width="20" height="20" style={{ display: "block" }} />
            <span style={{ fontWeight: 600, color: "var(--fg1)" }}>Siteworks.</span>
          </a>
          <div style={{ display: "flex", alignItems: "center", gap: 22 }}>
            <a href="/privacy-policy" style={{ fontFamily: "var(--font-body)", fontSize: 13, color: "var(--fg3)", textDecoration: "none" }}>Privacy Policy</a>
            <a href="/terms-conditions" style={{ fontFamily: "var(--font-body)", fontSize: 13, color: "var(--fg3)", textDecoration: "none" }}>Terms of Service</a>
          </div>
        </div>
      </div>
    </footer>
  );
}

function CaseStudyPage() {
  const ids = SECTIONS.map((s) => s.id);
  const active = useScrollSpy(ids);
  useAppReady();
  // cursor-following light on primary/secondary buttons (matches the rest of the site)
  useEffect(() => {
    const onMove = (e) => {
      const btn = e.target.closest(".btn-primary, .btn-secondary");
      if (btn) {
        const r = btn.getBoundingClientRect();
        btn.style.setProperty("--mx", `${((e.clientX - r.left) / r.width) * 100}%`);
        btn.style.setProperty("--my", `${((e.clientY - r.top) / r.height) * 100}%`);
      }
    };
    document.addEventListener("pointermove", onMove);
    return () => document.removeEventListener("pointermove", onMove);
  }, []);
  return (
    <div className="csx-page sw-page public-study-page">
      <SharedCaseNav />
      <React.Fragment>
      <Hero />
      <MetaBand />
      <div className="csx-wrap">
        <MobileTOC active={active} />
        <div className="csx-layout">
          <Rail active={active} />
          <Article />
        </div>
      </div>
      <OtherCases />
      </React.Fragment>
      <CaseFooter />
      <MobileCTA />
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(
  <React.Fragment>
    <CaseStudyPage />
    <BookingDialog />
  </React.Fragment>
);
