/* global React, Reveal, ArrowGlyph */
const { useState: useS, useEffect: useE, useRef: useR } = React;

// =========================================================
// HERO
// =========================================================
function Hero({ layout, headline, onBook, quoteAvatar, bookLabel = "Book a discovery call", eyebrow, showOfferTag = true, availLabel }) {
  // Each headline option is an array of (string | { em: string }) tokens for inline italics.
  const HEADLINES = {
    a: [
    "You don't want an Amazon business. You want ",
    { em: "your life back." }],

    b: [
    "Build the business. ",
    { em: "Get your life back." }],

    c: [
    "The boring, honest way to ",
    { em: "buy back your time." }]

  };
  const tokens = HEADLINES[headline] || HEADLINES.a;

  return (
    <header id="top" className="hero" data-layout={layout}>
      <div className="container">
        <div className="hero__grid">
          {layout === "asym" &&
          <div className="hero__col-stat">
              <div className="stat-card">
                <div className="label-mono">since 2018</div>
                <div className="stat-card__big" style={{ marginTop: 12 }}>
                  <em>$84M+</em>
                </div>
                <div className="label-mono" style={{ marginTop: 6 }}>student GMV coached</div>
              </div>
              <div className="stat-card">
                <div className="label-mono">cohorts run</div>
                <div className="stat-card__big" style={{ marginTop: 12 }}>
                  41
                </div>
                <div className="label-mono" style={{ marginTop: 6 }}>across 6 years</div>
              </div>
            </div>
          }

          <div>
            <div className="hero__eyebrow">
              <span className="eyebrow">{eyebrow || <>Amazon FBA coach &nbsp;·&nbsp; 1:1 &nbsp;·&nbsp; group</>}</span>
            </div>
            <div className="hero__award">
              <span className="hero__award-icon" aria-hidden="true">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
                  <circle cx="12" cy="9" r="6" />
                  <path d="M9 14l-2 7 5-3 5 3-2-7" />
                  <path d="M12 6.3l.9 1.9 2 .3-1.5 1.4.4 2-1.8-.9-1.8.9.4-2-1.5-1.4 2-.3z" fill="currentColor" stroke="none" />
                </svg>
              </span>
              <span>Recognised as one of NZ's <b>“Amazon champions”</b> by Amazon Global Selling</span>
            </div>
            <h1 className="display hero__title" style={{ fontSize: "101px" }}>
              {tokens.map((t, i) => {
                if (typeof t === "string") return <React.Fragment key={i}>{t}</React.Fragment>;
                if (t.em) return <em key={i}>{t.em}</em>;
                if (t.note) return (
                  <span key={i} className="hero__title-note">
                    <span className="hero__title-note__txt">{t.note}</span>
                  </span>
                );
                return null;
              })}
            </h1>
            <p className="hero__tagline">
              Build the business. Get your life back.
              <span className="hero__tagline-em"> No hype, just the honest way out.</span>
            </p>
            <p className="lead">
              You're good at what you do. You just can't picture doing it forever.
              A real Amazon business can be the way out &mdash; your time back, on
              your terms. I'm Jay, and I'll show you the honest path there: no
              fantasy timelines, just the next right move.
            </p>
            <div className="hero__sub">
              <button className="btn btn--primary btn--lg" onClick={onBook}>
                {bookLabel} <ArrowGlyph />
              </button>
              <a className="btn btn--ghost btn--lg" href="#method" onClick={(e) => {
                e.preventDefault();
                const el = document.getElementById("method");
                if (el) window.scrollTo({ top: el.getBoundingClientRect().top + window.pageYOffset, behavior: "smooth" });
              }}>
                See how I work
              </a>
            </div>

            <p className="hero__offer">
              {showOfferTag && <span className="hero__offer-tag">1:1 Coaching</span>}
              <span className="hero__offer-txt">We build and launch it together — all the way to <b>your first sale</b>, and beyond.</span>
            </p>

            <div className="hero__proof">
              <div className="hero__proof-avs" aria-hidden="true">
                <img src="assets/student-danielle.jpg" alt="" />
                <img src="assets/student-jessica.jpg" alt="" />
                <img src="assets/student-tariq.jpg" alt="" />
                <img src="assets/student-tim.jpg" alt="" />
                <img src="assets/student-nikolina.jpg" alt="" />
              </div>
              <div className="hero__proof-text">
                <div className="hero__proof-stars" aria-label="5 out of 5">
                  <StarGlyph /><StarGlyph /><StarGlyph /><StarGlyph /><StarGlyph />
                </div>
                <div className="hero__proof-line">
                  <b>3,000+ Sellers</b> taught — 1:1, cohort &amp; online
                </div>
              </div>
            </div>


            <div className="hero__metrics">
              <div>
                <div className="metric__num">12</div>
                <div className="metric__label">Years, same craft</div>
                <div className="metric__kicker">on Amazon, since 2014</div>
              </div>
              <div>
                <div className="metric__num">300+</div>
                <div className="metric__label">Coached 1:1</div>
                <div className="metric__kicker">by application only</div>
              </div>
              <div>
                <div className="metric__num">90<span style={{ color: "var(--ink-3)" }}>%</span></div>
                <div className="metric__label">1:1 students</div>
                <div className="metric__kicker">1st sale in 90 days</div>
              </div>
            </div>
          </div>

          {layout !== "centered" && <HeroPortraitBlock onBook={onBook} quoteAvatar={quoteAvatar} availLabel={availLabel} />}
        </div>
      </div>
    </header>);

}

// =========================================================
// MARQUEE — student wins
// =========================================================
function Marquee() {
  const items = [
  ["0 → 1 sale, week 9", "Michael · first launch"],
  ["$0 → $9K/mo", "Daniel · home · AU"],
  ["$0 → $10K/mo", "LibiGem · supplements · CA"],
  ["GNC Canada, accepted", "LibiGem · retail '24"],
  ["£0 → £10K/mo", "Waldek · private label · UK"],
  ["$0 → $15K, sold out", "Tim · electronics · 3 mo"],
  ["$0 → $100K · 90 days", "Xtreme Heaters · automotive · US"],
  ["231 units · 3 SKUs", "Tanja · launch"],
  ["147 units · $6,613", "Patricia · december"],
  ["300 units · £7,500", "Mared · first product"]];

  const loop = [...items, ...items];
  return (
    <div className="marquee" aria-label="Student wins">
      <div className="marquee__track">
        {loop.map((it, i) =>
        <div key={i} className="marquee__item">
            <span className="marquee__num">{it[0]}</span>
            <span className="marquee__text">{it[1]}</span>
            <span className="marquee__dot"></span>
          </div>
        )}
      </div>
    </div>);

}

// =========================================================
// PRESS strip
// =========================================================
function Press() {
  return (
    <div className="container">
      <div className="press">
        <div className="press__label">where I show up</div>
        <div className="press__logo">YouTube</div>
        <div className="press__logo press__logo--alt">Skool</div>
        <div className="press__logo">NZ Amazon Community</div>
        <div className="press__logo press__logo--alt">Meetup</div>
        <div className="press__logo">LaunchYou</div>
      </div>
    </div>);

}

// =========================================================
// VENTURES strip — "what I run"
// =========================================================
function Ventures() {
  const items = [
    { tag: "Course", name: "EcomXperts", desc: "Amazon FBA, dropshipping, print on demand, ebooks & Amazon affiliate." },
    { tag: "Consulting", name: "SellerCentral.Consulting", desc: "Hands-on Seller Central support for established brands that need a fix." },
    { tag: "Community", name: "Selling on Amazon New Zealand", desc: "The largest Amazon seller community in New Zealand, by a distance." },
  ];
  return (
    <div className="container">
      <div className="ventures">
        <div className="ventures__label">what I run</div>
        <div className="ventures__grid">
          {items.map((v, i) => (
            <div className="venture" key={i}>
              <span className="venture__tag">{v.tag}</span>
              <div className="venture__name">{v.name}</div>
              <p className="venture__desc">{v.desc}</p>
            </div>
          ))}
        </div>
      </div>
    </div>);

}

// =========================================================
// PLEDGE CARD — handwritten paper note for chapter 04
// =========================================================
function PledgeCard() {
  return (
    <div className="pledge">
      <div className="pledge__paper">
        <div className="pledge__stamp">PLEDGE · '26</div>
        <div className="pledge__head">things I won't do —</div>
        <ul className="pledge__list">
          <li>
            <span className="pledge__check" aria-hidden="true">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><path d="M4 13l5 5L20 6" /></svg>
            </span>
            promise you a number
          </li>
          <li>
            <span className="pledge__check" aria-hidden="true">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><path d="M4 13l5 5L20 6" /></svg>
            </span>
            sell a course &amp; ghost
          </li>
          <li>
            <span className="pledge__check" aria-hidden="true">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><path d="M4 13l5 5L20 6" /></svg>
            </span>
            take you on if you're not ready
          </li>
        </ul>
        <div className="pledge__sig">
          <span>— Jay</span>
          <svg className="pledge__scribble" viewBox="0 0 120 14" fill="none" aria-hidden="true">
            <path d="M2 9 C 20 2, 38 12, 56 7 S 92 3, 118 8" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" fill="none" />
          </svg>
        </div>
      </div>
    </div>);

}

// =========================================================
// STORY — scroll-triggered chapters
// =========================================================
function Story() {
  const chapters = [
  {
    n: "01",
    title: "Before Amazon, before I could drive — I was already designing products.",
    body: <>My first <b>product design class at 14</b> — Year 10 Graphics, <b>Mt. Roskill Grammar</b>, 2004. Brief, research, sketches, final solution. Before any algorithm, I was already obsessed with what makes someone <b>pick a thing up off the shelf</b>.</>,
    visual: "[ mt. roskill grammar · yr 10 graphics · 16/10/04 ]",
    kind: "scrap-school"
  },
  {
    n: "02",
    title: "Seven years on a real shop floor.",
    body: <>I sold electronics on the floor at <b>Dick Smith</b> for seven years. Real shelves, real buyers, real margins, real returns. The stuff Amazon makes invisible. That's where I learned what a <b>real brand actually feels like in someone's hands</b>.</>,
    visual: "[ dick smith · 7 years on the floor ]",
    kind: "scrap-retail"
  },
  {
    n: "03",
    title: "Then I chased every shiny object online.",
    body: <>Affiliate marketing, a web agency, an SEO agency, <b>AI chat funnels back in 2015</b>, blogging, video — I gave each a real go. <b>Amazon is the only one that actually replaced my income.</b> Not the only model that works — the <b>best odds for a normal person with a job</b>. I learned that the <b>expensive way, so you don't have to.</b></>,
    visual: "[ grind days · whiteboard office ]",
    img: "assets/jay-grind-days.jpg"
  },
  {
    n: "04",
    title: "Three years selling on Amazon — before I taught a soul.",
    body: <>My first big break: <b>1,000 units sold online in 30 days</b>, back in <b>2015</b>. Plenty of <b>ups and downs since</b> — multiple brands across kitchen &amp; dining and electronics, <b>two exits</b>. The <b>expensive mistakes</b> taught me more than the wins — what works, what doesn't, how to sell properly. Everything I teach, <b>I shipped first.</b></>,
    visual: "[ early storefront — 2015 ]",
    img: "assets/early-storefront.png",
    receipt: "assets/first-1000-sales.jpg",
    pos: "top left"
  },
  {
    n: "05",
    title: "Most new sellers don't have a strategy problem. They have an execution problem.",
    body: <>They <b>overthink their first product</b>. They jump to ads <b>before listings are ready</b>. They get <b>stuck watching videos</b>, never making the next move. They <b>quit at the first mistake</b> and doubt the whole journey. They make every move <b>in the wrong order</b>. Execution isn't hustle. It's sequence — the <b>right things in the right order</b>.</>,
    visual: "[ setup sequence — steps 6–10 ]",
    img: "assets/workflow-diagram.png"
  },
  {
    n: "06",
    title: "So I built the coaching I wish I'd had before my first sale.",
    body: <>Direct, patient, <b>no-bro-energy</b>. <b>1:1</b> to fix your specific mess. <b>Group programs</b> to compress <b>18 months of learning into 12 weeks</b>. No fluff modules. I take the complicated and make it <b>simple</b> — clear steps you can act on, in the right order.</>,
    visual: "[ cohort workshop — Auckland ]",
    img: "assets/cohort-workshop.avif"
  },
  {
    n: "07",
    title: "What I won't do.",
    body: <><b>I won't promise a number.</b> I won't sell you a course and <b>ghost</b>. I won't take you on if your product or budget isn't ready — <b>I'll tell you straight</b>, and tell you what to fix first. What I <i>will</i> do? Get you across the line — <b>your first real sale.</b></>,
    visual: "[ 1:1 — straight talk ]",
    img: "assets/jay-straight-talk.png"
  }];


  const refs = useR([]);
  const [active, setActive] = useS(0);
  useE(() => {
    // Activate a chapter the moment its top crosses 1/3 down the viewport.
    // Stay active until the next chapter's top crosses the same line.
    const ACTIVATE_AT = 0.33; // 33% from top of viewport
    const onScroll = () => {
      const lineY = window.innerHeight * ACTIVATE_AT;
      let next = 0;
      refs.current.forEach((el, i) => {
        if (!el) return;
        const top = el.getBoundingClientRect().top;
        if (top <= lineY) next = i;
      });
      setActive((prev) => prev === next ? prev : next);
    };
    window.addEventListener("scroll", onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  return (
    <section id="story" className="section">
      <div className="container">
        <Reveal className="s-head">
          <div>
            <div className="eyebrow">The story</div>
            <h2 className="display">How I got here, and why I coach.</h2>
          </div>
          <div className="s-head__right">
            Most "Amazon gurus" only know Amazon. I <b>designed products in school and university</b>, sold on <b>retail shelves for seven years</b>, then spent <b>three years on Amazon</b> — before I taught a soul.
            That order matters.
          </div>
        </Reveal>

        <div className="story">
          <div className="story__sticky">
            <div className="story__stick-inner">
              <div className="eyebrow">chapter {String(active + 1).padStart(2, "0")} / {String(chapters.length).padStart(2, "0")}</div>
              <h2 className="display" style={{ fontSize: "clamp(34px, 3vw, 50px)" }}>
                {(() => {
                  const t = chapters[active].title;
                  const i = t.indexOf(". ");
                  return i === -1 ? t : t.slice(0, i + 1);
                })()}
              </h2>
              <div style={{ display: "flex", gap: 18, alignItems: "center", marginTop: 24 }}>
                <div className="story__progress" style={{ flex: "0 0 2px" }}>
                  <span style={{ height: `${(active + 1) / chapters.length * 100}%` }}></span>
                </div>
                <span className="label-mono">scroll to read</span>
              </div>
            </div>
          </div>

          <div className="story__chapters">
            {chapters.map((c, i) =>
            <div
              key={i}
              ref={(el) => refs.current[i] = el}
              data-idx={i}
              className={"chapter" + (i === active ? " is-active" : "")}>
              
                <div className="chapter__num">{c.n}</div>
                <div>
                  <h3>{c.title}</h3>
                  <p>{c.body}</p>
                  <div className={"chapter__visual" + (c.img ? " has-img" : "") + (c.fit === "contain" ? " is-contain" : "") + (c.kind === "pledge" ? " is-pledge" : "") + (c.kind === "scrap-school" || c.kind === "scrap-retail" ? " is-scrap" : "") + (c.kind === "scrap-school" ? " scrap--school" : "") + (c.kind === "scrap-retail" ? " scrap--retail" : "")}>
                    {c.img && <img src={c.img} alt="" style={c.pos ? { objectPosition: c.pos } : undefined} />}
                    {c.receipt && <div className="chapter__receipt">
                      <img src={c.receipt} alt="Amazon Seller Central sales summary — 1,000 units in 30 days" />
                    </div>}
                    {c.kind === "pledge" && <PledgeCard />}
                    {c.kind === "scrap-school" && <>
                      <div className="scrap-paper scrap-paper--research">
                        <img src="assets/school-research-2004.png" alt="Research page — product references and teacher's grade" />
                      </div>
                      <div className="scrap-tape scrap-tape--research" aria-hidden="true"></div>
                      <div className="scrap-paper scrap-paper--brief">
                        <img src="assets/school-brief-2004.png" alt="Original Year 10 Graphics brief — Mt. Roskill Grammar, 2004" />
                      </div>
                      <div className="scrap-tape scrap-tape--brief" aria-hidden="true"></div>
                      <div className="scrap-paper scrap-paper--sketch">
                        <img src="assets/school-final-sketch.png" alt="Final solution sketch — clock radio" />
                      </div>
                      <div className="scrap-tape scrap-tape--sketch" aria-hidden="true"></div>
                      <div className="scrap-paper scrap-paper--clock">
                        <img src="assets/school-clock-sketch.png" alt="Concept sketch — digital clock radio reading 9:05 AM" />
                      </div>
                      <div className="scrap-tape scrap-tape--clock" aria-hidden="true"></div>
                      <div className="scrap-paper scrap-paper--photo">
                        <img src="assets/school-jay-drawing-2004.png" alt="Jay, age 14, drawing at his desk in Year 10 Graphics" />
                        <span className="scrap-photo__cap">that's me — age 14 ✎</span>
                      </div>
                      <div className="scrap-tape scrap-tape--photo" aria-hidden="true"></div>
                    </>}
                    {c.kind === "scrap-retail" && <>
                      <div className="scrap-paper scrap-paper--store">
                        <img src="assets/dick-smith-storefront.jpg" alt="Dick Smith Electronics storefront" />
                      </div>
                      <div className="scrap-tape scrap-tape--store" aria-hidden="true"></div>
                      <div className="scrap-note">8 yrs · this shelf</div>
                    </>}
                    <span>{c.visual}</span>
                  </div>
                </div>
              </div>
            )}
          </div>
        </div>
      </div>
    </section>);

}

// =========================================================
// HERO PORTRAIT BLOCK — composed cream card that replaces
// the old .hero__portrait. Scoped styles in hero-portrait-block.css.
// =========================================================
function HeroPortraitBlock({ onBook, quoteAvatar, availLabel = "1:1 availability" }) {
  // Availability rolls forward automatically with the calendar month.
  // Window = current month ± (2 past · current · 3 future):
  //   past months    → "booked" (filled, checked)
  //   current month  → "next"   (highlighted — the one you book now)
  //   future months  → "open"   (hollow)
  // In June this reproduces Apr/May booked · Jun next · Jul–Sep open,
  // then advances on its own each month — no manual edits needed.
  const ABBR = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
  const FULL = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
  const curMonth = new Date().getMonth();
  const months = [-2, -1, 0, 1, 2, 3].map((off) => {
    const idx = (curMonth + off + 24) % 12;
    return { name: ABBR[idx], state: off < 0 ? "booked" : off === 0 ? "next" : "open" };
  });
  const curFull = FULL[curMonth];
  const curAbbr = ABBR[curMonth];

  const HpbArrow = () =>
  <svg className="hpb__arrow" viewBox="0 0 16 16" fill="none" aria-hidden="true">
      <path d="M3 8h10M9 4l4 4-4 4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
    </svg>;

  return (
    <div className="hpb">
      <div className="hpb__photo-block" style={{ width: "610px" }}>
        <div className="hpb__blob"></div>
        <div className="hpb__photo-wrap">
          <img className="hpb__photo" src="assets/jay-portrait.png" alt="Jay with a client on the beach" />
        </div>
        <div className="hpb__pulse-pill">
          <span className="hpb__pulse-dot"></span>
          Open for {curFull}
        </div>
        <div className="hpb__quote-card">
          <p className="hpb__quote-text">
            "Today was the biggest day — sold 28 units. It would have never happened if I had not invested in Jay."
          </p>
          <div className="hpb__quote-cite" style={quoteAvatar ? { display: "flex", alignItems: "center", gap: "11px" } : undefined}>
            {quoteAvatar &&
              <img
                src={quoteAvatar}
                alt="Billy M."
                style={{ width: "40px", height: "40px", borderRadius: "50%", objectFit: "cover", flex: "0 0 auto" }}
              />}
            <span><strong>Billy M.</strong> · New Zealand</span>
          </div>
        </div>
        <div className="hpb__scrap">
          <img src="assets/jay-teaching.jpg" alt="Jay coaching a workshop" />
          <div className="hpb__scrap-tag">Auckland · workshop</div>
        </div>
      </div>

      <div className="hpb__avail">
        <div className="hpb__avail-label">{availLabel}</div>
        <div className="hpb__avail-months">
          {months.map((m) =>
          <button key={m.name} className={`hpb__avail-m is-${m.state}`} onClick={onBook} type="button">
              <span className="hpb__avail-m-dot"></span>
              {m.name}
            </button>
          )}
        </div>
        <button className="hpb__avail-cta" onClick={onBook} type="button">
          Book {curAbbr} <HpbArrow />
        </button>
      </div>
    </div>);

}

Object.assign(window, { Hero, HeroPortraitBlock, Marquee, Press, Ventures, Story, PledgeCard });