/* eslint-disable */
// CoachingCards365 — single-page brand site.
// Sections: Header / Hero / Sport switcher / Featured spotlight / Shop grid /
//           Inside the pack / Story / Schools / Testimonials / FAQ / Footer.

const scrollTo = (id) => document.getElementById(id)?.scrollIntoView({ behavior: "smooth" });

// ── Cart drawer ─────────────────────────────────────────────────────────────

function CartDrawer({ cart, onClose, onUpdateQty, onRemove }) {
  const count = cart.reduce((s, i) => s + i.qty, 0);
  const total = cart.reduce((s, i) => s + i.price * i.qty, 0);
  const freeDelivery = total >= 30;
  return (
    <>
      <div className="drawer-overlay" onClick={onClose} />
      <div className="cart-drawer">
        <div className="cart-drawer-head">
          <h3>Your bag {count > 0 && <span className="cart-count-badge">{count}</span>}</h3>
          <button className="cart-close" aria-label="Close bag" onClick={onClose}>✕</button>
        </div>

        {cart.length === 0 ? (
          <div className="cart-empty">
            <div className="cart-empty-icon">🛍</div>
            <p>Your bag is empty.</p>
            <button className="btn" onClick={onClose}>Browse decks →</button>
          </div>
        ) : (
          <>
            <div className="cart-items">
              {cart.map((item) => {
                const sport = SPORT_BY_ID(item.sport);
                return (
                  <div className="cart-item" key={item.id}>
                    <div className="cart-item-photo">
                      <img src={item.img} alt={sport.label} />
                    </div>
                    <div className="cart-item-info">
                      <div className="cart-item-sport">{sport.label}</div>
                      <div className="cart-item-name">
                        {item.special ? "Stay-at-Home Cricket Games" : `Coaching Cards · ${item.edition}`}
                      </div>
                      <div className="cart-item-price">£{item.price.toFixed(2)}</div>
                      <div className="cart-item-controls">
                        <div className="qty">
                          <button onClick={() => onUpdateQty(item.id, item.qty - 1)}>−</button>
                          <span>{String(item.qty).padStart(2, "0")}</span>
                          <button onClick={() => onUpdateQty(item.id, item.qty + 1)}>+</button>
                        </div>
                        <button className="cart-remove" onClick={() => onRemove(item.id)}>Remove</button>
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>
            <div className="cart-footer">
              <div className={`cart-delivery-bar ${freeDelivery ? "met" : ""}`}>
                {freeDelivery
                  ? "✓ Free UK delivery included"
                  : `Add £${(30 - total).toFixed(2)} more for free UK delivery`}
              </div>
              <div className="cart-total">
                <span>Total</span>
                <span>£{total.toFixed(2)} <small>incl. VAT</small></span>
              </div>
              <button className="btn lg" style={{ width: "100%", justifyContent: "center", marginTop: 14 }}>
                Checkout →
              </button>
              <button className="btn ghost" style={{ width: "100%", justifyContent: "center", marginTop: 10 }} onClick={onClose}>
                Continue shopping
              </button>
            </div>
          </>
        )}
      </div>
    </>
  );
}

// ── Sign-in modal ────────────────────────────────────────────────────────────

function SignInModal({ onClose }) {
  const [email, setEmail] = React.useState("");
  const [password, setPassword] = React.useState("");
  const [submitted, setSubmitted] = React.useState(false);

  const handleSubmit = (e) => {
    e.preventDefault();
    if (email && password) setSubmitted(true);
  };

  return (
    <>
      <div className="modal-overlay" onClick={onClose} />
      <div className="modal">
        <div className="modal-head">
          <img src="assets/cc365-app-icon.png" alt="" className="modal-logo" />
          <button className="modal-close" aria-label="Close" onClick={onClose}>✕</button>
        </div>
        {submitted ? (
          <div className="modal-success">
            <div className="modal-success-icon">✓</div>
            <h3>Welcome back!</h3>
            <p>You're signed in to CoachingCards365.</p>
            <button className="btn lg" style={{ width: "100%", justifyContent: "center", marginTop: 16 }} onClick={onClose}>
              Continue shopping →
            </button>
          </div>
        ) : (
          <form className="modal-body" onSubmit={handleSubmit}>
            <h3 style={{ margin: "0 0 6px", fontSize: 22, fontWeight: 800, letterSpacing: "-0.01em" }}>Sign in</h3>
            <p style={{ margin: "0 0 22px", fontSize: 14, color: "var(--sub)" }}>
              Access your orders and saved decks.
            </p>
            <div className="form-field">
              <label>Email</label>
              <input
                type="email" required placeholder="you@example.com"
                value={email} onChange={(e) => setEmail(e.target.value)}
              />
            </div>
            <div className="form-field">
              <label>Password</label>
              <input
                type="password" required placeholder="••••••••"
                value={password} onChange={(e) => setPassword(e.target.value)}
              />
            </div>
            <button type="submit" className="btn lg" style={{ width: "100%", justifyContent: "center", marginTop: 8 }}>
              Sign in →
            </button>
            <div style={{ textAlign: "center", marginTop: 16, fontSize: 13, color: "var(--sub)" }}>
              No account?{" "}
              <a href="#" style={{ color: "var(--grass)", fontWeight: 700 }}>Create one →</a>
            </div>
          </form>
        )}
      </div>
    </>
  );
}

// ── Toast notification ───────────────────────────────────────────────────────

function Toast({ message, onDone }) {
  React.useEffect(() => {
    const t = setTimeout(onDone, 2800);
    return () => clearTimeout(t);
  }, [message]);
  return <div className="toast">{message}</div>;
}

// ── Page components ──────────────────────────────────────────────────────────

function Header({ cartCount, onCartOpen, onSignIn }) {
  const [menuOpen, setMenuOpen] = React.useState(false);
  const close = () => setMenuOpen(false);
  return (
    <header className="header">
      <div className="header-inner">
        <a className="wordmark" href="#top" aria-label="CoachingCards365 home">
          <img src="assets/cc365-lockup-horizontal.png" alt="CoachingCards365" />
        </a>
        <nav className="nav-links">
          <a className="on" href="#shop">Shop</a>
          <a href="#sports">Sports</a>
          <a href="#story">Our story</a>
          <a href="#faq">Help</a>
        </nav>
        <div className="header-actions">
          <button className="btn ghost" style={{ padding: "9px 16px", fontSize: 13 }} onClick={onSignIn}>
            Sign in
          </button>
          <button className="btn" onClick={onCartOpen}>
            Bag{cartCount > 0 ? ` · ${String(cartCount).padStart(2, "0")}` : ""}
          </button>
        </div>
        <button className="nav-mobile-btn" aria-label={menuOpen ? "Close menu" : "Open menu"} onClick={() => setMenuOpen(!menuOpen)}>
          <span /><span /><span />
        </button>
      </div>
      {menuOpen && (
        <nav className="nav-mobile">
          <a href="#shop" onClick={close}>Shop</a>
          <a href="#sports" onClick={close}>Sports</a>
          <a href="#story" onClick={close}>Our story</a>
          <a href="#faq" onClick={close}>Help</a>
          <div className="nav-mobile-actions">
            <button className="btn ghost" onClick={() => { close(); onSignIn(); }}>Sign in</button>
            <button className="btn" onClick={() => { close(); onCartOpen(); }}>
              Bag{cartCount > 0 ? ` · ${cartCount}` : ""}
            </button>
          </div>
        </nav>
      )}
    </header>
  );
}

function Hero({ featured, onAddToCart }) {
  const sport = SPORT_BY_ID(featured);
  const pack = FIRST_ED_BY_SPORT(featured);
  return (
    <section className="hero" id="top">
      <div className="hero-grid">
        <div className="hero-copy">
          <div className="hero-tag">
            <span className="dot" />
            New for 2026 · {sport.label} Coaching Cards
          </div>
          <h1 className="h-display h-1">
            Better questions.<br />
            Better <strong>coaches</strong>.<br />
            <span className="ital seam" style={{ color: "var(--grass)" }}>Every season.</span>
          </h1>
          <p className="hero-lede">
            Printed coaching-question decks for the working coach — goal-setting,
            feedback, session structure and player development. In partnership with
            Cricket Coach 365, now across five sports.
          </p>
          <div className="hero-cta">
            <button className="btn lg red" onClick={() => onAddToCart(pack.id, 1)}>
              Shop {sport.label.toLowerCase()} · £{pack.price.toFixed(2)} →
            </button>
            <button className="btn lg ghost" onClick={() => scrollTo("inside")}>
              See what's inside
            </button>
          </div>
          <div className="hero-trust">
            <div className="hero-trust-meta">
              <strong>Free UK delivery</strong> over £30 ·<br />
              posted next working day
            </div>
          </div>
        </div>

        <div className="hero-visual">
          <div className="hero-field" />
          <div className="hero-photo" key={sport.id}>
            <img src={pack.img} alt={`${sport.label} Coaching Cards on grass`} />
          </div>
          <div className="hero-chip hero-chip--cards">
            <span className="big">{pack.cardCount}</span>
            <span className="sub">question<br />cards inside</span>
          </div>
          <div className="hero-badge">
            <img src="assets/cc365-app-icon.png" alt="" />
            <span>In partnership with<br /><strong>Cricket Coach 365</strong></span>
          </div>
        </div>
      </div>
    </section>
  );
}

function SportSwitch({ featured, onChange }) {
  return (
    <div className="sport-switch" id="sports">
      <span className="mono-label" style={{ marginRight: 4 }}>Choose a sport →</span>
      {SPORTS.map((s) => (
        <button
          key={s.id}
          data-sport={s.id}
          className={`sport-chip ${s.id === featured ? "on" : ""}`}
          onClick={() => onChange(s.id)}
        >
          <span className="swatch" />
          {s.label}
        </button>
      ))}
    </div>
  );
}

function Spotlight({ featured, onAddToCart }) {
  const sport = SPORT_BY_ID(featured);
  const pack = FIRST_ED_BY_SPORT(featured);
  const isCricket = featured === "cricket";
  const [qty, setQty] = React.useState(1);

  React.useEffect(() => { setQty(1); }, [featured]);

  return (
    <section className="spotlight reveal" id="spotlight">
      <div className="spot-grid">
        <div className="spot-photo">
          <img src={pack.img} alt={`${sport.label} Coaching Cards on grass`} />
          <div className="photo-tag">
            <span className="dot" /> Posted on waterproof card
          </div>
        </div>
        <div>
          <div className="eyebrow">Featured · {sport.label}</div>
          <h2 className="h-display h-2" style={{ marginTop: 14 }}>
            {sport.label} Coaching Cards.<br />
            <span style={{ color: "var(--grass)" }}>{pack.edition}.</span>
          </h2>
          <p className="lede" style={{ marginTop: 22, maxWidth: 540 }}>
            {pack.lede}
          </p>

          <div className="spec-table">
            {[
              ["Cards in deck", `${pack.cardCount} question prompts`],
              ["Card size",     "65 × 95 mm · linen-finish poker card"],
              ["Designed for",  pack.audience],
              ["Format",        "Tuck-box · 350gsm cover · matte-laminated"],
              ["Posted",        "Royal Mail tracked · 2–3 working days"],
            ].map(([k, v]) => (
              <div className="spec-row" key={k}>
                <span className="k">{k}</span>
                <span>{v}</span>
              </div>
            ))}
          </div>

          <div className="buy-row">
            <div className="price">£{pack.price.toFixed(2)}<small>incl. VAT</small></div>
            <div className="qty">
              <button onClick={() => setQty((q) => Math.max(1, q - 1))}>−</button>
              <span>{String(qty).padStart(2, "0")}</span>
              <button onClick={() => setQty((q) => q + 1)}>+</button>
            </div>
            <button className="btn lg" onClick={() => onAddToCart(pack.id, qty)}>Add to bag →</button>
          </div>

          {isCricket && (
            <div className="partnership">
              <div>
                <div className="small">In partnership with</div>
                <div className="name">Cricket Coach 365</div>
              </div>
              <a href="https://cricketcoach365.co.uk" target="_blank" rel="noreferrer">
                cricketcoach365.co.uk ↗
              </a>
            </div>
          )}
        </div>
      </div>
    </section>
  );
}

function ShopGrid({ featured, onSelect, onAddToCart, onNavigate }) {
  return (
    <section className="shop reveal" id="shop">
      <div className="shop-head">
        <div>
          <div className="eyebrow">Shop</div>
          <h2 className="h-display h-2" style={{ marginTop: 14 }}>
            Every deck, on grass.
          </h2>
        </div>
        <span className="mono-label">Sort · Coach's pick ▾</span>
      </div>
      <div className="grid">
        {PACKS.map((p, i) => {
          const sport = SPORT_BY_ID(p.sport);
          return (
            <div
              className={`product-card reveal delay-${(i % 4) + 1}`}
              key={p.id}
              onClick={() => onNavigate(p.id)}
              style={{ cursor: "pointer" }}
            >
              <div className="product-photo">
                <img src={p.img} alt={`${sport.label} Coaching Cards`} />
                {p.isNew && <span className="tag new">New</span>}
                {p.special && <span className="tag special">Special edition</span>}
              </div>
              <div className="product-meta">
                <span className={`sport ${p.sport === "gymnastics" ? "gym" : ""}`}>{sport.label}</span>
                <h3 className="title">{p.special ? "Stay-at-Home Cricket Games" : `Coaching Cards · ${p.edition}`}</h3>
                <p className="lede">{p.lede}</p>
                <div className="row-bottom">
                  <span className="price-sm">£{p.price.toFixed(2)}</span>
                  <button
                    className="add"
                    onClick={(e) => { e.stopPropagation(); onAddToCart(p.id, 1); }}
                  >
                    Add to bag →
                  </button>
                </div>
              </div>
            </div>
          );
        })}
      </div>
    </section>
  );
}

function ProductPage({ packId, onAddToCart, onBack, cartCount, onCartOpen, onSignIn }) {
  const pack = PACKS.find((p) => p.id === packId);
  const sport = pack ? SPORT_BY_ID(pack.sport) : null;
  const [qty, setQty] = React.useState(1);

  React.useEffect(() => { window.scrollTo(0, 0); }, [packId]);

  if (!pack) return (
    <div className="site">
      <div style={{ padding: "120px 64px", textAlign: "center" }}>
        <p>Product not found.</p>
        <button className="btn" onClick={onBack}>← Back to shop</button>
      </div>
    </div>
  );

  const relatedPacks = PACKS.filter((p) => p.id !== packId && p.sport === pack.sport);

  return (
    <div className="site">
      <Header cartCount={cartCount} onCartOpen={onCartOpen} onSignIn={onSignIn} />
      <div className="pdp-wrap row">
        <button className="pdp-back" onClick={onBack}>← Back to shop</button>
        <div className="pdp-grid">
          <div className="pdp-photo">
            <img src={pack.img} alt={`${sport.label} Coaching Cards`} />
            {pack.isNew && <span className="tag new">New</span>}
            {pack.special && <span className="tag special">Special edition</span>}
          </div>
          <div className="pdp-detail">
            <div className="eyebrow">{sport.label}</div>
            <h1 className="h-display h-2" style={{ marginTop: 10 }}>
              {pack.special ? "Stay-at-Home Cricket Games" : `Coaching Cards · ${pack.edition}`}
            </h1>

            {pack.cardCount && (
              <div className="pdp-card-count">
                <span className="pdp-count-num">{pack.cardCount}</span>
                <span className="pdp-count-label">question cards inside</span>
              </div>
            )}

            <div className="pdp-description">
              {(pack.description || pack.lede).split("\n\n").map((para, i) => (
                <p key={i}>{para}</p>
              ))}
            </div>

            <div className="spec-table" style={{ marginTop: 28 }}>
              {[
                pack.cardCount && ["Cards in deck", `${pack.cardCount} question prompts`],
                ["Card size",     "65 × 95 mm · linen-finish poker card"],
                ["Designed for",  pack.audience],
                ["Format",        "Tuck-box · 350gsm cover · matte-laminated"],
                ["Posted",        "Royal Mail tracked · 2–3 working days"],
              ].filter(Boolean).map(([k, v]) => (
                <div className="spec-row" key={k}>
                  <span className="k">{k}</span>
                  <span>{v}</span>
                </div>
              ))}
            </div>

            <div className="buy-row" style={{ marginTop: 32 }}>
              <div className="price">£{pack.price.toFixed(2)}<small>incl. VAT</small></div>
              <div className="qty">
                <button onClick={() => setQty((q) => Math.max(1, q - 1))}>−</button>
                <span>{String(qty).padStart(2, "0")}</span>
                <button onClick={() => setQty((q) => q + 1)}>+</button>
              </div>
              <button className="btn lg" onClick={() => onAddToCart(pack.id, qty)}>Add to bag →</button>
            </div>

            <div className="pdp-trust">
              <span>✓ Free UK delivery over £30</span>
              <span>✓ Posted next working day</span>
              <span>✓ 30-day returns on unopened decks</span>
            </div>
          </div>
        </div>

        {relatedPacks.length > 0 && (
          <div className="pdp-related">
            <div className="eyebrow" style={{ marginBottom: 20 }}>More {sport.label} decks</div>
            <div className="grid" style={{ gridTemplateColumns: "repeat(auto-fill, minmax(220px, 1fr))" }}>
              {relatedPacks.map((p) => (
                <div
                  key={p.id}
                  className="product-card"
                  style={{ cursor: "pointer" }}
                  onClick={() => { window.location.hash = `/product/${p.id}`; }}
                >
                  <div className="product-photo">
                    <img src={p.img} alt={`${sport.label} Coaching Cards`} />
                    {p.isNew && <span className="tag new">New</span>}
                    {p.special && <span className="tag special">Special edition</span>}
                  </div>
                  <div className="product-meta">
                    <span className={`sport`}>{sport.label}</span>
                    <h3 className="title">{p.special ? "Stay-at-Home Cricket Games" : `Coaching Cards · ${p.edition}`}</h3>
                    <div className="row-bottom">
                      <span className="price-sm">£{p.price.toFixed(2)}</span>
                      <button className="add" onClick={(e) => { e.stopPropagation(); onAddToCart(p.id, 1); }}>Add to bag →</button>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}
      </div>
      <Footer onCartOpen={onCartOpen} onSignIn={onSignIn} />
    </div>
  );
}

function InsidePack() {
  return (
    <section className="inside reveal" id="inside">
      <div className="inside-head">
        <div className="eyebrow on-dark">Inside the deck</div>
        <h2 className="h-display h-2" style={{ marginTop: 14 }}>
          Every card.<br />One <em>better</em> session.
        </h2>
        <p>
          Each deck is built to live in your kit bag. Pull a card at the start of training,
          mid-session, or post-match — the question changes the conversation.
        </p>
      </div>
      <div className="inside-grid">
        {[
          ["01", "Goal-setting", "Open every session with a question that lands. Cards prompt players to name what they're working on — coach-led, not coach-told."],
          ["02", "Feedback",     "Mid-session prompts that move past 'good job'. Direct, specific, and tied to what the player can actually change."],
          ["03", "Structure",    "When the plan goes sideways, the structure cards bring you back to a clear next-block — without breaking flow."],
          ["04", "Development",  "Post-session cards that turn one training into a season's worth of growth. Reflection, not just reps."],
        ].map(([n, k, v], i) => (
          <div className={`inside-card reveal delay-${i + 1}`} key={n}>
            <div className="n">{n}</div>
            <h3>{k}</h3>
            <p>{v}</p>
          </div>
        ))}
      </div>

      {/* Fanned sample cards */}
      <div className="fan-stage reveal">
        {[
          { num: "Card 03 · Goal-setting",  q: "What does a great session look like for you today?", rot: -22 },
          { num: "Card 12 · Feedback",      q: "If we replayed that, what would you change first?",  rot: -11 },
          { num: "Card 18 · Structure",     q: "What's the next block your group is ready for?",     rot: 0 },
          { num: "Card 27 · Feedback",      q: "Name one thing your teammate did that helped you.",  rot: 11 },
          { num: "Card 34 · Development",   q: "What did this week ask of you that last week didn't?", rot: 22 },
        ].map((c, i) => (
          <div key={i} className="fan-card" style={{
            transform: `translateY(${Math.abs(c.rot) * 0.8}px) rotate(${c.rot}deg)`,
            zIndex: 5 - Math.abs(c.rot) / 11,
          }}>
            <div className="num">{c.num}</div>
            <div className="q">"{c.q}"</div>
            <div className="fcard-foot">
              <span>365</span>
              <span>Q. {String(i * 7 + 3).padStart(2, "0")} / 40</span>
            </div>
          </div>
        ))}
      </div>
    </section>
  );
}

function Story({ onToast }) {
  return (
    <section className="story reveal" id="story">
      <div className="story-photo">
        <img src="uploads/C2-1.jpg" alt="Cricket Coaching Cards on grass" />
      </div>
      <div>
        <div className="eyebrow">Our story · in partnership with Cricket Coach 365</div>
        <h2 className="h-display h-2" style={{ marginTop: 14 }}>
          It started with one deck. Now there's a&nbsp;league.
        </h2>
        <p className="body" style={{ marginTop: 22, fontSize: 17.5, maxWidth: 540 }}>
          Cricket Coach 365 wrote the first edition for coaches who wanted to ask better
          questions, not memorise more drills. The decks travelled — into football clubs,
          school PE departments, hockey academies, tennis programmes, gymnastics halls.
          Each new sport is authored in-house, with a head coach in the discipline,
          and printed in the UK.
        </p>
        <div style={{ marginTop: 32, display: "flex", gap: 14, flexWrap: "wrap" }}>
          <button className="btn" onClick={() => onToast("The journal is coming soon!")}>Read the journal →</button>
          <button className="btn ghost" onClick={() => onToast("Meet the coaches is coming soon!")}>Meet the coaches</button>
        </div>
      </div>
    </section>
  );
}

function Schools({ onToast }) {
  const [email, setEmail] = React.useState("");
  const [error, setError] = React.useState("");
  const [sent, setSent] = React.useState(false);

  const submit = (e) => {
    e.preventDefault();
    const trimmed = email.trim();
    if (!trimmed) { setError("Please enter your school email."); return; }
    if (!trimmed.includes("@")) { setError("Please enter a valid email address."); return; }
    setError("");
    setSent(true);
    onToast("Quote request sent! We'll be in touch within one working day.");
  };

  return (
    <section className="schools reveal" id="schools">
      <div>
        <div className="eyebrow on-dark">For schools &amp; academies</div>
        <h2 className="h-display h-2" style={{ marginTop: 14 }}>
          Class sets <em>on invoice</em>.<br />
          Free delivery, every term.
        </h2>
        <p>
          PE departments and academy coach groups can order class sets billed to the school —
          no card needed up front. We post within two working days and invoice the bursar.
          Mixed-sport bundles available.
        </p>
        {sent ? (
          <div className="schools-sent">
            <span className="schools-sent-icon">✓</span>
            <div>
              <div style={{ fontWeight: 800, fontSize: 16 }}>Request received!</div>
              <div style={{ fontSize: 13, opacity: 0.8, marginTop: 3 }}>We'll email a quote within one working day.</div>
            </div>
          </div>
        ) : (
          <form className="form" onSubmit={submit} noValidate>
            <input
              type="email"
              placeholder="Your school email"
              value={email}
              onChange={(e) => { setEmail(e.target.value); setError(""); }}
            />
            <button type="submit" className="btn">Get a quote →</button>
          </form>
        )}
        {error && <div className="schools-error">{error}</div>}
        <div className="mono-label" style={{ marginTop: 18, color: "#9aa094" }}>
          schools@coachingcards365.co.uk · 0113 555 0414
        </div>
      </div>
      <div className="schools-list">
        {[
          { letter: "S", name: "St. Mary's Primary, Leeds",     sub: "PE department · 6-deck mixed bundle" },
          { letter: "B", name: "Bradford Cricket Academy",      sub: "Cricket First + Second editions · 24 sets" },
          { letter: "Y", name: "Yorkshire Gymnastics Hub",       sub: "Gymnastics First Edition · 12 sets" },
          { letter: "K", name: "King James's School, Knaresborough", sub: "Hockey + Football · 8 sets" },
        ].map((s) => (
          <div key={s.name} className="item">
            <div className="icon">{s.letter}</div>
            <div>
              <div className="name">{s.name}</div>
              <div className="sub">{s.sub}</div>
            </div>
          </div>
        ))}
      </div>
    </section>
  );
}

function Testimonials() {
  return (
    <section className="testimonials reveal">
      <div className="testimonials-head">
        <div>
          <div className="eyebrow">From the touchline</div>
          <h2 className="h-display h-2" style={{ marginTop: 14 }}>What coaches say.</h2>
        </div>
      </div>
      <div className="t-grid">
        {[
          {
            stars: "★★★★★",
            q: "Saved me three hours of planning a week. The kids ask for the cards by number — that's a first.",
            by: "Lou Fairhurst",
            role: "Head of PE · St. Mary's Primary, Leeds",
          },
          {
            stars: "★★★★★",
            q: "The conversation cards changed how the U13s talk to each other on a Saturday. Worth every penny.",
            by: "James Okafor",
            role: "Head Coach · Bradford Cricket Academy",
          },
          {
            stars: "★★★★★",
            q: "I keep a deck in the gym bag. Pull a card, run the session. They've made me a calmer coach.",
            by: "Priya Mehta",
            role: "Head of Gymnastics · Yorkshire Hub",
          },
        ].map((t) => (
          <div className="t-card reveal" key={t.by}>
            <div className="stars">{t.stars}</div>
            <p className="q">"{t.q}"</p>
            <div className="by">{t.by}</div>
            <div className="role">{t.role}</div>
          </div>
        ))}
      </div>
    </section>
  );
}

function FAQItem({ q, a, defaultOpen = false }) {
  const [open, setOpen] = React.useState(defaultOpen);
  return (
    <div className={`faq-item ${open ? "open" : ""}`} onClick={() => setOpen(!open)}>
      <div className="q-row">
        <div className="q-text">{q}</div>
        <div className="toggle">{open ? "−" : "+"}</div>
      </div>
      <div className="a-text">{a}</div>
    </div>
  );
}

function FAQ() {
  return (
    <section className="faq reveal" id="faq">
      <div className="faq-grid">
        <div>
          <div className="eyebrow">Help</div>
          <h2 className="h-display h-2" style={{ marginTop: 14 }}>Common questions.</h2>
          <p className="body" style={{ marginTop: 22 }}>
            Can't find what you need? Email us at <strong>hello@coachingcards365.co.uk</strong>{" "}
            — a real coach answers, usually within a working day.
          </p>
        </div>
        <div className="faq-list">
          <FAQItem
            q="Are these drill cards or question cards?"
            a="Question cards. Each deck is a set of coaching prompts designed to be pulled at training — goal-setting, feedback, session structure, player development. The aim is to change the conversation, not give you another drill diagram."
            defaultOpen
          />
          <FAQItem
            q="What ages are the decks for?"
            a="The question prompts are written to work from U8 through to academy and adult coaching. The coach selects which cards land for the group in front of them — the deck flexes."
          />
          <FAQItem
            q="What's the partnership with Cricket Coach 365?"
            a="The original Cricket Coaching Cards were written by Cricket Coach 365. CoachingCards365 is the sister brand that extends the format across football, hockey, tennis and gymnastics, with the same editorial team. Each sport is authored in-house with a head coach in the discipline."
          />
          <FAQItem
            q="Can schools be invoiced instead of paying by card?"
            a="Yes — class-set orders for schools, academies and clubs can be invoiced to the bursar. Email schools@coachingcards365.co.uk for a quote."
          />
          <FAQItem
            q="Do you post outside the UK?"
            a="Yes, to most of Europe and the Commonwealth. Shipping is calculated at checkout. Free UK delivery on orders over £30."
          />
          <FAQItem
            q="Are returns accepted?"
            a="30-day returns on unopened decks. We rarely see one come back — but if it doesn't suit, we'll refund."
          />
        </div>
      </div>
    </section>
  );
}

function Footer({ onCartOpen, onSignIn }) {
  return (
    <footer className="footer">
      <div className="foot-grid">
        <div>
          <a className="foot-wordmark" href="#top" aria-label="CoachingCards365">
            <img src="assets/cc365-app-icon.png" alt="" />
            <span>CoachingCards<span className="r">365</span></span>
          </a>
          <p style={{ marginTop: 22, fontSize: 14.5, color: "#9aa094", maxWidth: 360, lineHeight: 1.6 }}>
            Printed coaching-question decks for the working coach. In partnership with
            Cricket Coach 365. Authored, printed and posted from West Yorkshire.
          </p>
        </div>
        <div>
          <h4>Shop</h4>
          <a href="#shop">All decks</a>
          <a href="#shop">Cricket</a>
          <a href="#shop">Football</a>
          <a href="#shop">Hockey</a>
          <a href="#shop">Tennis</a>
          <a href="#shop">Gymnastics</a>
        </div>
        <div>
          <h4>CoachingCards365</h4>
          <a href="#story">Our story</a>
          <a href="#story">The journal</a>
          <a href="#story">Meet the coaches</a>
          <a href="#story">Press</a>
        </div>
        <div>
          <h4>Help</h4>
          <a href="#faq">Postage &amp; returns</a>
          <a href="#faq">Bulk orders</a>
          <a href="#faq">Contact</a>
          <a href="#" onClick={(e) => { e.preventDefault(); onSignIn(); }}>Account</a>
        </div>
      </div>
      <div className="foot-base">
        <span>© 2026 CoachingCards365 · in partnership with Cricket Coach 365</span>
        <span>hello@coachingcards365.co.uk · @coachingcards365</span>
      </div>
    </footer>
  );
}

// ── Site root ────────────────────────────────────────────────────────────────

function useHashRoute() {
  const getRoute = () => {
    const hash = window.location.hash.replace(/^#\/?/, "");
    if (hash.startsWith("product/")) return { page: "product", packId: hash.replace("product/", "") };
    return { page: "home" };
  };
  const [route, setRoute] = React.useState(getRoute);
  React.useEffect(() => {
    const handler = () => setRoute(getRoute());
    window.addEventListener("hashchange", handler);
    return () => window.removeEventListener("hashchange", handler);
  }, []);
  return route;
}

function Site() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const featured = t.featuredSport || "cricket";
  const route = useHashRoute();
  useReveal();

  const [cart, setCart] = React.useState([]);
  const [cartOpen, setCartOpen] = React.useState(false);
  const [signInOpen, setSignInOpen] = React.useState(false);
  const [toast, setToast] = React.useState(null);

  const addToCart = (packId, qty = 1) => {
    const pack = PACKS.find((p) => p.id === packId);
    if (!pack) return;
    setCart((prev) => {
      const existing = prev.find((i) => i.id === packId);
      if (existing) return prev.map((i) => i.id === packId ? { ...i, qty: i.qty + qty } : i);
      return [...prev, { ...pack, qty }];
    });
    setCartOpen(true);
  };

  const updateCartQty = (packId, qty) => {
    if (qty <= 0) { removeFromCart(packId); return; }
    setCart((prev) => prev.map((i) => i.id === packId ? { ...i, qty } : i));
  };

  const removeFromCart = (packId) => {
    setCart((prev) => prev.filter((i) => i.id !== packId));
  };

  const cartCount = cart.reduce((s, i) => s + i.qty, 0);
  const onSelect = (sport) => setTweak("featuredSport", sport);
  const showToast = (msg) => setToast(msg);
  const navigateTo = (packId) => { window.location.hash = `/product/${packId}`; };
  const navigateHome = () => { window.location.hash = ""; };

  if (route.page === "product") {
    return (
      <React.Fragment>
        <ProductPage
          packId={route.packId}
          onAddToCart={addToCart}
          onBack={navigateHome}
          cartCount={cartCount}
          onCartOpen={() => setCartOpen(true)}
          onSignIn={() => setSignInOpen(true)}
        />
        {cartOpen && (
          <CartDrawer cart={cart} onClose={() => setCartOpen(false)} onUpdateQty={updateCartQty} onRemove={removeFromCart} />
        )}
        {signInOpen && <SignInModal onClose={() => setSignInOpen(false)} />}
        {toast && <Toast message={toast} onDone={() => setToast(null)} />}
      </React.Fragment>
    );
  }

  return (
    <React.Fragment>
      <div className="site">
        <Header cartCount={cartCount} onCartOpen={() => setCartOpen(true)} onSignIn={() => setSignInOpen(true)} />
        <Hero featured={featured} onAddToCart={addToCart} />
        <SportSwitch featured={featured} onChange={onSelect} />
        <Spotlight featured={featured} onAddToCart={addToCart} />
        <ShopGrid featured={featured} onSelect={onSelect} onAddToCart={addToCart} onNavigate={navigateTo} />
        <InsidePack />
        <Story onToast={showToast} />
        <FAQ />
        <Footer onCartOpen={() => setCartOpen(true)} onSignIn={() => setSignInOpen(true)} />
      </div>

      {cartOpen && (
        <CartDrawer
          cart={cart}
          onClose={() => setCartOpen(false)}
          onUpdateQty={updateCartQty}
          onRemove={removeFromCart}
        />
      )}

      {signInOpen && <SignInModal onClose={() => setSignInOpen(false)} />}

      {toast && <Toast message={toast} onDone={() => setToast(null)} />}

      <TweaksPanel title="Tweaks">
        <TweakSection label="Hero" />
        <TweakSelect
          label="Featured sport"
          value={featured}
          options={SPORTS.map((s) => ({ value: s.id, label: s.label }))}
          onChange={(v) => setTweak("featuredSport", v)}
        />
        <div style={{ fontSize: 11, color: "#888", padding: "6px 0 2px", lineHeight: 1.4 }}>
          Swaps the hero pack (animates), the featured deck spotlight, and the headline accent.
          Try Gymnastics to see the blue colour-way.
        </div>
        <TweakSection label="Motion" />
        <TweakToggle
          label="Ambient photo float"
          value={t.float}
          onChange={(v) => setTweak("float", v)}
        />
        <TweakToggle
          label="Reveal on scroll"
          value={t.reveal}
          onChange={(v) => setTweak("reveal", v)}
        />
      </TweaksPanel>

      {/* Motion-controlled styles */}
      <style>{`
        ${!t.float ? `.hero-photo { animation: none !important; }` : ""}
        ${!t.reveal ? `.reveal { opacity: 1 !important; transform: none !important; }` : ""}
      `}</style>
    </React.Fragment>
  );
}

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "featuredSport": "cricket",
  "float": true,
  "reveal": true
}/*EDITMODE-END*/;

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