// cr-top.jsx — Nav, Hero, Triptych, Pillars
const { useState, useEffect, useRef } = React;

/* ---- contact handler: Calendly-ready, falls back to mailto ---- */
const CALENDLY_URL = ""; // <-- drop Calendly link here when ready
const CONTACT_EMAIL = "connect@crenshawanalytics.com";
function startConversation(e){
  if(e) e.preventDefault();
  if(CALENDLY_URL){ window.open(CALENDLY_URL, "_blank", "noopener"); }
  else{ window.location.href = `mailto:${CONTACT_EMAIL}?subject=${encodeURIComponent("Starting a conversation")}`; }
}
window.startConversation = startConversation;

/* ---- icon mark (the logo glyph, simplified for inline use) ---- */
function Arrow(){ return <span className="arr" aria-hidden="true">→</span>; }

/* ---- brand lockup ---- */
function Brand(){
  return (
    <a className="brand" href="#top" aria-label="Crenshaw Analytics home">
      <img className="logo-img" src="assets/logo.png" alt="Crenshaw Analytics" />
    </a>
  );
}

/* ================= NAV ================= */
function Nav(){
  const [stuck, setStuck] = useState(false);
  const [open, setOpen] = useState(false);
  useEffect(() => {
    const onScroll = () => setStuck(window.scrollY > 40);
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  useEffect(() => {
    document.body.style.overflow = open ? "hidden" : "";
    return () => { document.body.style.overflow = ""; };
  }, [open]);
  const links = [
    ["Services", "#pillars"],
    ["How it works", "#primer"],
    ["Approach", "#cadence"],
    ["About", "#about"],
  ];
  return (
    <nav className="nav" data-stuck={stuck} data-open={open}>
      <div className="wrap nav-inner">
        <Brand />
        <button className={"nav-burger"+(open?" open":"")} aria-label={open?"Close menu":"Open menu"} aria-expanded={open} onClick={() => setOpen(o => !o)}>
          <span/><span/><span/>
        </button>
        <div className={open ? "nav-links open" : "nav-links"} onClick={() => setOpen(false)}>
          <span className="nav-links-kick">Menu</span>
          {links.map(([t, h]) => <a key={t} className="item" href={h}>{t}</a>)}
          <a className="nav-cta" href="#contact" onClick={startConversation}>Start a conversation <span className="arr">→</span></a>
        </div>
      </div>
      <div className="nav-backdrop" onClick={() => setOpen(false)}/>
    </nav>
  );
}

/* ================= HERO ================= */
const HEADLINES = {
  action: { lead: "More numbers than ever. Still no clear next move.", em: "We make the answer obvious." },
  punch:  { lead: "All this reporting. Still no clear view.", em: "We build the one you trust." },
  blind:  { lead: "Buried in reports, flying blind.", em: "We build the clear view." },
};

function HeroChart({ play }){
  // a line that draws itself climbing over a small bar field — echoes the logo
  const cls = (b) => "draw-line" + (play ? " go" : "");
  return (
    <svg className="hero-chart" viewBox="0 0 720 720" fill="none" preserveAspectRatio="xMidYMid meet" aria-hidden="true">
      <defs>
        <linearGradient id="lg" x1="0" y1="1" x2="1" y2="0">
          <stop offset="0" stopColor="#82B1FF" stopOpacity="0.5"/>
          <stop offset="1" stopColor="#82B1FF"/>
        </linearGradient>
        <linearGradient id="fill" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0" stopColor="#82B1FF" stopOpacity="0.22"/>
          <stop offset="1" stopColor="#82B1FF" stopOpacity="0"/>
        </linearGradient>
      </defs>
      {/* faint baseline grid */}
      {[200,320,440,560].map((y,i)=>(
        <line key={i} x1="120" y1={y} x2="690" y2={y} stroke="#fff" strokeOpacity="0.06"/>
      ))}
      {/* bars */}
      {[[300,500,90],[400,440,150],[500,360,230],[600,250,340]].map((b,i)=>(
        <rect key={i} className={"bar-rise"+(play?" go":"")} style={{animationDelay:`${1.0+i*0.16}s`}}
          x={b[0]} y={b[1]} width="46" height={b[2]} rx="4"
          fill="#82B1FF" fillOpacity={0.16+i*0.06}/>
      ))}
      {/* area under line */}
      <path className={cls()} pathLength="1" style={{animationDelay:"0.45s"}}
        d="M120 560 C 240 540, 320 470, 420 380 S 580 200, 660 120"
        stroke="url(#lg)" strokeWidth="5" strokeLinecap="round"/>
      {/* arrow head */}
      <path className={"dot-pop"+(play?" go":"")} style={{animationDelay:"2.4s"}}
        d="M660 120 L 626 132 M660 120 L 648 154" stroke="#82B1FF" strokeWidth="5" strokeLinecap="round"/>
      {/* node dots */}
      {[[120,560],[420,380],[660,120]].map((p,i)=>(
        <circle key={i} className={"dot-pop"+(play?" go":"")} style={{animationDelay:`${1.6+i*0.25}s`}}
          cx={p[0]} cy={p[1]} r="7" fill="#fff" stroke="#82B1FF" strokeWidth="3"/>
      ))}
    </svg>
  );
}

function Hero({ headlineKey, heroVisual }){
  const [play, setPlay] = useState(false);
  useEffect(() => { const t = setTimeout(() => setPlay(true), 150); return () => clearTimeout(t); }, []);
  const h = HEADLINES[headlineKey] || HEADLINES.sunday;
  const showChart = heroVisual === "both" || heroVisual === "chart";
  const showMesh = heroVisual === "both" || heroVisual === "mesh";
  return (
    <header className="hero" id="top">
      {showMesh && <div className="hero-mesh"><div className="glow3"/></div>}
      <div className="hero-grid-lines"/>
      {showChart && <HeroChart play={play}/>}
      <div className="wrap hero-inner">
        <div className="hero-content">
          <h1 data-reveal style={{"--reveal-delay":"0.12s"}}>
            {h.lead} <em>{h.em}</em>
          </h1>
          <p className="lede" data-reveal style={{"--reveal-delay":"0.28s"}}>
            A data partnership for mid&#8209;market companies past spreadsheets, ready to lead with their numbers.
          </p>
          <div className="hero-cta" data-reveal style={{"--reveal-delay":"0.4s"}}>
            <a className="btn btn-primary" href="#contact" onClick={startConversation}>Start a conversation <Arrow/></a>
          </div>
        </div>
      </div>
    </header>
  );
}

/* ================= TRIPTYCH ================= */
const ROLES = [
  { role:"CEO", out:<>A whole&#8209;company view that updates <em>while you sleep.</em></>,
    sup:"One screen. Every department. Refreshed overnight, ready before your coffee.",
    glyph:"eye", viz:"ceo" },
  { role:"CFO", out:<>Cost drivers that show up <em>before</em> they hit the financials.</>,
    sup:"See the leak while it's still a drip, not a line item in next quarter's report.",
    glyph:"trend", viz:"cfo" },
  { role:"COO", out:<>Bottlenecks visible. <em>Accountability clear.</em></>,
    sup:"Know where the work slows, and who's positioned to speed it up.",
    glyph:"flow", viz:"flow" },
];
function Glyph({ kind }){
  const common = { fill:"none", stroke:"currentColor", strokeWidth:2, strokeLinecap:"round", strokeLinejoin:"round" };
  if(kind==="eye") return <svg className="glyph" viewBox="0 0 24 24" {...common}><path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12Z"/><circle cx="12" cy="12" r="3"/></svg>;
  if(kind==="trend") return <svg className="glyph" viewBox="0 0 24 24" {...common}><path d="M3 17l6-6 4 4 8-8"/><path d="M21 7v5h-5"/></svg>;
  return <svg className="glyph" viewBox="0 0 24 24" {...common}><circle cx="5" cy="6" r="2"/><circle cx="5" cy="18" r="2"/><circle cx="19" cy="12" r="2"/><path d="M7 6h6a4 4 0 0 1 4 4M7 18h6a4 4 0 0 0 4-4"/></svg>;
}
function TripCard({ r, i }){
  const [ref, seen] = useInView(0.3);
  return (
    <div className="trip-col" ref={ref} data-reveal style={{"--reveal-delay":`${i*0.14}s`}}>
      <div className="trip-viz"><PersonaViz kind={r.viz} seen={seen}/></div>
      <div className="trip-role"><Glyph kind={r.glyph}/>{r.role}</div>
      <p className="trip-out h-display">{r.out}</p>
      <p className="trip-sup">{r.sup}</p>
    </div>
  );
}
function Triptych({ tone }){
  return (
    <section className={"sec "+tone} id="who">
      <div className="wrap">
        <div className="trip-head" data-reveal>
          <h2 className="h-sect">Built for the people who answer for the numbers.</h2>
        </div>
        <div className="trip">
          {ROLES.map((r,i)=> <TripCard key={r.role} r={r} i={i}/>)}
        </div>
      </div>
    </section>
  );
}

/* ================= PILLARS ================= */
function PViz({ kind }){
  const s = { fill:"none", stroke:"currentColor", strokeWidth:1.6, strokeLinecap:"round", strokeLinejoin:"round" };
  if(kind==="ground") return <svg className="p-viz" viewBox="0 0 120 120" {...s}><rect x="20" y="64" width="80" height="40" rx="4"/><line x1="20" y1="80" x2="100" y2="80"/><line x1="48" y1="64" x2="48" y2="104"/><line x1="72" y1="64" x2="72" y2="104"/><path d="M30 64l30-22 30 22"/></svg>;
  if(kind==="monthly") return <svg className="p-viz" viewBox="0 0 120 120" {...s}><circle cx="60" cy="60" r="34"/><path d="M60 34v26l18 10"/><circle cx="60" cy="60" r="3" fill="currentColor"/></svg>;
  return <svg className="p-viz" viewBox="0 0 120 120" {...s}><path d="M40 30h28l16 16v44a4 4 0 0 1-4 4H40a4 4 0 0 1-4-4V34a4 4 0 0 1 4-4Z"/><path d="M68 30v16h16"/><path d="M48 70l8 8 16-18"/></svg>;
}
const PILLARS = [
  { num:"01", name:"Groundwork", title:"Build the foundation.",
    desc:"60–120 day projects that stand up the data warehouse, define your KPIs, and deliver dashboards your team actually trusts.",
    viz:"ground", foot:"Explore Groundwork", href:"#contact" },
  { num:"02", name:"Monthly Partnership", title:"Stay in the work.",
    desc:"A standing partner who knows your business and keeps your numbers sharp. New questions get answered, your dashboards evolve as you grow, and momentum never stalls.",
    viz:"monthly",
    foot:"See the tiers", href:"Monthly Partnership.html" },
  { num:"03", name:"Strategic Builds", title:"Build the thing no template fits.",
    desc:"The ambitious one-offs: civic data platforms, multi-organization products, and the deep, specialized work that needs a room of its own.",
    viz:"bespoke", foot:"Talk through a build", href:"#contact" },
];
function Pillars({ tone }){
  return (
    <section className={"sec "+tone} id="pillars">
      <div className="wrap">
        <div className="pillars-head">
          <div data-reveal>
            <h2 className="h-sect">The work, in three pillars.</h2>
          </div>
          <p className="lede" data-reveal style={{maxWidth:"360px","--reveal-delay":"0.1s"}}>
            Every engagement follows the Crenshaw Strategic Framework: a clear path from first build to everyday use, so the tools we make get trusted and actually used.
          </p>
        </div>
        <div className="pillars">
          {PILLARS.map((p,i)=>(
            <a className="pillar" key={p.name} href={p.href}
               onClick={p.href==="#contact"?startConversation:undefined}
               data-reveal style={{"--reveal-delay":`${i*0.12}s`}}>
              <PViz kind={p.viz}/>
              <div className="p-name">{p.name}</div>
              <div className="p-title h-display">{p.title}</div>
              <p className="p-desc">{p.desc}</p>
              <div className="p-foot"><span className="arrow-link">{p.foot} <Arrow/><span className="line"/></span></div>
            </a>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ================= PRIMER (educational) ================= */
const STEPS = [
  { k:"Today", t:"Your numbers live everywhere.",
    d:"Spreadsheets, your CRM, accounting software, a few people's heads. No two reports ever quite match, and pulling one together eats a day." },
  { k:"Step one", t:"We give them one home.",
    d:"That home is a data warehouse. In plain terms: a single, organized place where every number flows in automatically and stays in sync." },
  { k:"Step two", t:"We make them make sense.",
    d:"A dashboard turns that into one live screen: are we on track, where's the problem, what changed this week. No exporting, no reconciling." },
  { k:"The result", t:"Everyone works off the same picture.",
    d:"Fast, current, and clear enough that the next move is obvious, instead of a debate about whose spreadsheet is right." },
];
function PrimerStep({ s, i }){
  const [ref, seen] = useInView(0.35);
  return (
    <div className="primer-step" ref={ref} data-reveal style={{"--reveal-delay":`${i*0.12}s`}}>
      <div className="ps-top">
        <div className="ps-badge">{i+1}</div>
        <div className="ps-viz"><StepViz kind={i} seen={seen}/></div>
      </div>
      <div className="ps-kick">{s.k}</div>
      <h3 className="ps-title h-display">{s.t}</h3>
      <p className="ps-desc">{s.d}</p>
    </div>
  );
}
function Primer({ tone }){
  return (
    <section className={"sec "+tone+" primer"} id="primer">
      <FloatShapes variant="a"/>
      <div className="wrap">
        <div className="primer-head">
          <h2 className="h-sect" data-reveal>New to this? Here's the whole idea.</h2>
          <p className="lede" data-reveal style={{"--reveal-delay":"0.1s"}}>
            You don't need to <em>speak data</em> to work with us. This is what we actually build, in plain English, and why it changes how the business runs day to day.
          </p>
        </div>
        <div className="primer-flow">
          <div className="primer-rail" aria-hidden="true"/>
          {STEPS.map((s,i)=> <PrimerStep key={s.k} s={s} i={i}/>)}
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { Nav, Hero, Triptych, Primer, Pillars, Brand, Arrow, HEADLINES });
