// NEVEAR JERSEYS — Wholesale Jersey Landing Page
// Mobile-first international football jersey manufacturing site

const { useState, useEffect, useMemo } = React;

const BRAND_NAME = "NEVEAR JERSEYS";
const SITE_URL = "https://jerseys.nevear.com";
const BASE_DESCRIPTION = "NEVEAR JERSEYS manufactures bulk international football jerseys for 100+ piece orders. Fan, player, kids, retro, home and away options delivered in 15 days.";

// ============ DATA ============

const TEAMS = [
  // High-demand international teams for ad landing pages.
  { name: "Argentina", region: "S.America", colors: ["#75AADB", "#FFFFFF", "#75AADB"], hot: true },
  { name: "Brazil", region: "S.America", colors: ["#FFD000", "#009B3A", "#002776"], hot: true },
  { name: "France", region: "Europe", colors: ["#0055A4", "#FFFFFF", "#EF4135"], hot: true },
  { name: "Germany", region: "Europe", colors: ["#FFFFFF", "#000000", "#DD0000"], hot: true },
  { name: "Spain", region: "Europe", colors: ["#C60B1E", "#FFC400", "#C60B1E"], hot: true },
  { name: "England", region: "Europe", colors: ["#FFFFFF", "#CE1124", "#FFFFFF"], hot: true },
  { name: "Portugal", region: "Europe", colors: ["#006600", "#FF0000", "#006600"], hot: true },
  { name: "Netherlands", region: "Europe", colors: ["#FF6C0C", "#FFFFFF", "#21468B"], hot: true },
  { name: "Italy", region: "Europe", colors: ["#0066CC", "#FFFFFF", "#0066CC"] },
  { name: "Belgium", region: "Europe", colors: ["#ED2939", "#000000", "#FFD700"] },
  { name: "Croatia", region: "Europe", colors: ["#FF0000", "#FFFFFF", "#171796"] },
  { name: "USA", region: "N.America", colors: ["#FFFFFF", "#B22234", "#3C3B6E"], host: true },
  { name: "Mexico", region: "N.America", colors: ["#006847", "#FFFFFF", "#CE1126"], host: true, hot: true },
  { name: "Canada", region: "N.America", colors: ["#FF0000", "#FFFFFF", "#FF0000"], host: true },
  { name: "Morocco", region: "Africa", colors: ["#C1272D", "#006233", "#C1272D"], hot: true },
  { name: "Senegal", region: "Africa", colors: ["#00853F", "#FDEF42", "#E31B23"] },
  { name: "Nigeria", region: "Africa", colors: ["#008751", "#FFFFFF", "#008751"] },
  { name: "Egypt", region: "Africa", colors: ["#CE1126", "#FFFFFF", "#000000"] },
  { name: "Ghana", region: "Africa", colors: ["#CE1126", "#FCD116", "#006B3F"] },
  { name: "Japan", region: "Asia", colors: ["#0A2A6B", "#FFFFFF", "#BC002D"] },
  { name: "South Korea", region: "Asia", colors: ["#CD2E3A", "#FFFFFF", "#0047A0"] },
  { name: "Saudi Arabia", region: "Asia", colors: ["#006C35", "#FFFFFF", "#006C35"] },
  { name: "Australia", region: "Oceania", colors: ["#FFD700", "#006633", "#FFD700"] },
  { name: "Uruguay", region: "S.America", colors: ["#7BAFD4", "#FFFFFF", "#7BAFD4"] },
  { name: "Colombia", region: "S.America", colors: ["#FCD116", "#003893", "#CE1126"] },
  { name: "Ecuador", region: "S.America", colors: ["#FFDD00", "#003893", "#CE1126"] },
  { name: "Chile", region: "S.America", colors: ["#FFFFFF", "#0033A0", "#D52B1E"] },
  { name: "Poland", region: "Europe", colors: ["#FFFFFF", "#DC143C", "#FFFFFF"] },
  { name: "Switzerland", region: "Europe", colors: ["#DA291C", "#FFFFFF", "#DA291C"] },
  { name: "Denmark", region: "Europe", colors: ["#C60C30", "#FFFFFF", "#C60C30"] },
  { name: "Serbia", region: "Europe", colors: ["#C6363C", "#FFFFFF", "#0C4076"] },
  { name: "Türkiye", region: "Europe", colors: ["#E30A17", "#FFFFFF", "#E30A17"] },
  { name: "Cameroon", region: "Africa", colors: ["#007A5E", "#CE1126", "#FCD116"] },
  { name: "Ivory Coast", region: "Africa", colors: ["#FF8200", "#FFFFFF", "#009A44"] },
  { name: "Iran", region: "Asia", colors: ["#FFFFFF", "#239F40", "#DA0000"] },
  { name: "Qatar", region: "Asia", colors: ["#8A1538", "#FFFFFF", "#8A1538"] },
];

const KIT_TYPES = [
  { id: "home", name: "Home", desc: "Primary kit, signature colorways" },
  { id: "away", name: "Away", desc: "Travel kit, contrasting palette" },
  { id: "third", name: "Third", desc: "Alternate, statement designs" },
  { id: "gk", name: "Goalkeeper", desc: "GK shirts, bold solo colors" },
  { id: "retro", name: "Retro", desc: "Iconic kits from 70s–00s" },
];

const SIZE_RANGES = [
  { id: "adults", label: "Adults", range: "S → 4XL", icon: "M" },
  { id: "kids", label: "Kids", range: "4y → 14y", icon: "K" },
  { id: "toddlers", label: "Toddlers", range: "12m → 4y", icon: "T" },
];

const TIERS = [
  { qty: 100, price: 14.5, label: "100-199", range: "100-199 pieces" },
  { qty: 200, price: 13.5, label: "200-400", range: "200-400 pieces" },
  { qty: 500, price: 12.0, label: "500-699", range: "500-699 pieces" },
  { qty: 700, price: 11.0, label: "700+", range: "700+ pieces" },
];

const MIN_QTY = 100;
const MAX_QTY = 2000;
const DEFAULT_QTY = 100;
const INITIAL_PRODUCT_COUNT = 24;
const QUICK_QTYS = [100, 200, 500, 700];
const DELIVERY_TEXT = "Delivered in 15 days from order date";

// ============ HELPERS ============

const fmt = (n) => n.toLocaleString("en-US");

function priceFor(qty) {
  const tier = [...TIERS].reverse().find(t => qty >= t.qty) || TIERS[0];
  return tier;
}

function slugify(value) {
  return value
    .toLowerCase()
    .normalize("NFD")
    .replace(/[\u0300-\u036f]/g, "")
    .replace(/[^a-z0-9]+/g, "-")
    .replace(/^-|-$/g, "");
}

function teamUrl(team) {
  return `${rootPrefix()}products/${slugify(team.name)}.html`;
}

function findTeam(slug) {
  return ALL_TEAMS.find(team => slugify(team.name) === slug || team.slug === slug);
}

function rootPrefix() {
  return window.location.pathname.includes("/products/") ? "../" : "./";
}

function siteUrl(pathname = "") {
  return new URL(pathname, SITE_URL).href;
}

function productSlugFromPath() {
  const match = window.location.pathname.match(/\/products\/([^/]+)\.html$/);
  return match ? match[1] : "";
}

function teamCode(team) {
  const parts = team.name.split(/\s+/);
  return (parts.length === 1
    ? team.name.slice(0, 3)
    : parts.map(part => part[0]).join("").slice(0, 3)
  ).toUpperCase();
}

function setMeta(name, content, attr = "name") {
  let node = document.head.querySelector(`meta[${attr}="${name}"]`);
  if (!node) {
    node = document.createElement("meta");
    node.setAttribute(attr, name);
    document.head.appendChild(node);
  }
  node.setAttribute("content", content);
}

function setCanonical(href) {
  let node = document.head.querySelector('link[rel="canonical"]');
  if (!node) {
    node = document.createElement("link");
    node.setAttribute("rel", "canonical");
    document.head.appendChild(node);
  }
  node.setAttribute("href", href);
}

const CATALOG_DATA = window.CATALOG_DATA || { teams: [], productsByTeam: {} };
const FALLBACK_COLORS = ["#F4F0E8", "#E63946", "#0F0F0F"];
const TEAM_ALIASES = {
  "United States": "USA",
  Turkey: "Türkiye",
};

function knownTeamFor(name) {
  const normalized = slugify(TEAM_ALIASES[name] || name);
  return TEAMS.find(team => slugify(team.name) === normalized);
}

function buildAllTeams() {
  const merged = new Map();
  for (const team of TEAMS) {
    merged.set(slugify(team.name), { ...team, slug: slugify(team.name), productCount: 0 });
  }
  for (const catalogTeam of CATALOG_DATA.teams || []) {
    const known = knownTeamFor(catalogTeam.name);
    merged.set(catalogTeam.slug, {
      name: catalogTeam.name,
      slug: catalogTeam.slug,
      region: known?.region || "International",
      colors: known?.colors || FALLBACK_COLORS,
      hot: known?.hot || catalogTeam.productCount >= 20,
      host: known?.host || false,
      productCount: catalogTeam.productCount,
      variants: catalogTeam.variants,
      kits: catalogTeam.kits,
    });
  }
  return [...merged.values()].sort((a, b) => a.name.localeCompare(b.name));
}

const ALL_TEAMS = buildAllTeams();

function productsForTeam(team) {
  return CATALOG_DATA.productsByTeam?.[team.slug || slugify(team.name)] || [];
}

function assetUrl(assetPath) {
  return `${rootPrefix()}${assetPath}`;
}

function productLabel(product) {
  return `${product.variant} · ${product.kit}`;
}

function pickFeaturedProducts(products) {
  const order = [
    product => product.variant === "Fan" && product.kit === "Home",
    product => product.variant === "Fan" && product.kit === "Away",
    product => product.variant === "Player" && product.kit === "Home",
    product => product.kit === "Goalkeeper",
    product => product.kit === "Retro",
  ];
  const picks = [];
  for (const matcher of order) {
    const product = products.find(item => matcher(item) && !picks.includes(item));
    if (product) picks.push(product);
  }
  for (const product of products) {
    if (picks.length >= 4) break;
    if (!picks.includes(product)) picks.push(product);
  }
  return picks;
}

// ============ COMPONENTS ============

function Logo({ className = "" }) {
  return (
    <div className={`logo ${className}`}>
      <svg viewBox="0 0 32 32" width="22" height="22" aria-hidden="true">
        <circle cx="16" cy="16" r="15" fill="none" stroke="currentColor" strokeWidth="2" />
        <path d="M16 4 L20 14 L30 14 L22 20 L25 30 L16 24 L7 30 L10 20 L2 14 L12 14 Z"
              fill="currentColor" transform="scale(0.55) translate(13 13)" />
      </svg>
      <span>{BRAND_NAME}</span>
    </div>
  );
}

function JerseyIcon({ colors = ["#E63946", "#FFFFFF", "#0F0F0F"], number = "10", name = "", className = "" }) {
  // SVG jersey illustration — simple, brand-neutral
  const [c1, c2, c3] = colors;
  const markFill = "#FFFFFF";
  const markStroke = "#0F0F0F";
  // Stripe pattern variants based on team feel
  return (
    <svg viewBox="0 0 200 220" className={`jersey-svg ${className}`} aria-hidden="true">
      <defs>
        <clipPath id={`jersey-clip-${number}-${name}`}>
          <path d="M50 20 L75 10 L85 22 Q100 32 115 22 L125 10 L150 20 L180 35 L172 75 L150 70 L150 200 Q100 215 50 200 L50 70 L28 75 L20 35 Z" />
        </clipPath>
      </defs>
      {/* Body */}
      <path d="M50 20 L75 10 L85 22 Q100 32 115 22 L125 10 L150 20 L180 35 L172 75 L150 70 L150 200 Q100 215 50 200 L50 70 L28 75 L20 35 Z"
            fill={c1} stroke="#0F0F0F" strokeWidth="2.5" strokeLinejoin="round" />
      {/* Stripes (alternating pattern) */}
      <g clipPath={`url(#jersey-clip-${number}-${name})`}>
        <rect x="80" y="0" width="20" height="220" fill={c2} opacity="0.95" />
        <rect x="115" y="0" width="20" height="220" fill={c2} opacity="0.95" />
      </g>
      {/* Collar */}
      <path d="M85 22 Q100 32 115 22 L110 38 Q100 44 90 38 Z" fill={c3} stroke="#0F0F0F" strokeWidth="2" strokeLinejoin="round" />
      {/* Number */}
      <text x="100" y="140" textAnchor="middle" fontFamily="Anton, sans-serif"
            fontSize="62" fill={markFill} stroke={markStroke} strokeWidth="3" paintOrder="stroke">{number}</text>
      {/* Name banner */}
      {name && (
        <text x="100" y="90" textAnchor="middle" fontFamily="Anton, sans-serif"
              fontSize="14" letterSpacing="3" fill={markFill} stroke={markStroke}
              strokeWidth="1.5" paintOrder="stroke">{name.toUpperCase()}</text>
      )}
    </svg>
  );
}

function Header({ onQuote, navBase = "" }) {
  const [open, setOpen] = useState(false);
  return (
    <header className="site-header">
      <div className="header-inner">
        <Logo />
        <nav className="desktop-nav">
          <a href={`${navBase}#kits`}>Kits</a>
          <a href={`${navBase}#teams`}>Teams</a>
          <a href={`${navBase}#pricing`}>Pricing</a>
          <a href={`${navBase}#process`}>Process</a>
        </nav>
        <button className="cta-btn cta-btn--sm desktop-only" onClick={onQuote}>
          Get Quote →
        </button>
        <button className="menu-btn mobile-only" onClick={() => setOpen(!open)} aria-label="Menu">
          <span className={`menu-icon ${open ? "open" : ""}`}>
            <span></span><span></span><span></span>
          </span>
        </button>
      </div>
      {open && (
        <div className="mobile-menu">
          <a href={`${navBase}#kits`} onClick={() => setOpen(false)}>Kits</a>
          <a href={`${navBase}#teams`} onClick={() => setOpen(false)}>Teams</a>
          <a href={`${navBase}#pricing`} onClick={() => setOpen(false)}>Pricing</a>
          <a href={`${navBase}#process`} onClick={() => setOpen(false)}>Process</a>
          <button className="cta-btn" onClick={() => { setOpen(false); onQuote(); }}>
            Get Quote →
          </button>
        </div>
      )}
    </header>
  );
}

function Hero({ onQuote }) {
  return (
    <section className="hero">
      <div className="hero-grid">
        <div className="hero-copy">
          <div className="kicker">
            <span className="dot"></span>
            <span>BULK MANUFACTURING · INTERNATIONAL TEAMS</span>
          </div>
          <h1 className="hero-title">
            <span>Bulk kits </span>
            <span>for every </span>
            <span className="hero-accent">nation.</span>
          </h1>
          <p className="hero-sub">
            Bulk-manufactured international football jerseys for retailers, fan shops,
            clubs, schools, and ad-driven drops. Home, away, third, goalkeeper, retro,
            fan, and player jerseys for adults, kids, and toddlers.
            <strong> Minimum order 100 pieces.</strong>
          </p>
          <div className="hero-ctas">
            <button className="cta-btn cta-btn--lg" onClick={onQuote}>
              Request bulk quote →
            </button>
            <a href="#pricing" className="link-btn">See price tiers</a>
          </div>
          <div className="hero-stats">
            <div><strong>100</strong><span>piece minimum</span></div>
            <div><strong>15d</strong><span>delivered from order</span></div>
            <div><strong>All</strong><span>international teams</span></div>
          </div>
        </div>
        <div className="hero-visual">
          <div className="jersey-stack">
            <div className="jersey jersey-1">
              <JerseyIcon colors={["#75AADB", "#FFFFFF", "#0F0F0F"]} number="10" name="ARG" />
            </div>
            <div className="jersey jersey-2">
              <JerseyIcon colors={["#FFD000", "#009B3A", "#002776"]} number="9" name="BRA" />
            </div>
            <div className="jersey jersey-3">
              <JerseyIcon colors={["#006847", "#FFFFFF", "#CE1126"]} number="14" name="MEX" />
            </div>
          </div>
          <div className="hero-badge">
            <div className="badge-ring">
              <span>100+ PIECES</span>
              <span>· BULK ·</span>
              <span>15 DAYS</span>
              <span>· MFG ·</span>
            </div>
            <div className="badge-core">15d</div>
          </div>
        </div>
      </div>
      <Marquee />
    </section>
  );
}

function Marquee() {
  const items = [
    "100 PIECE MINIMUM", "BULK MANUFACTURING", "ALL INTERNATIONAL TEAMS", "HOME · AWAY · THIRD",
    "GOALKEEPER · RETRO", "ADULT · KIDS · TODDLER", "FAN & PLAYER JERSEYS",
    "CUSTOM SPONSOR PRINT", "WHITE-LABEL TAGGING", "15 DAYS DELIVERED",
  ];
  return (
    <div className="marquee">
      <div className="marquee-track">
        {[...items, ...items, ...items].map((it, i) => (
          <span key={i} className="marquee-item">
            <span className="marquee-dot">●</span> {it}
          </span>
        ))}
      </div>
    </div>
  );
}

function Categories() {
  const [tab, setTab] = useState("kit");
  return (
    <section id="kits" className="section">
      <div className="section-head">
        <span className="eyebrow">/01 — PRODUCTS</span>
        <h2>Every kit, every body, every era.</h2>
        <p>Build mixed bulk orders across kit type, age range, and grade. We split the 100-piece minimum across SKUs so your order can mix teams, sizes, and styles.</p>
      </div>

      <div className="tabs">
        <button className={tab === "kit" ? "active" : ""} onClick={() => setTab("kit")}>Kit type</button>
        <button className={tab === "age" ? "active" : ""} onClick={() => setTab("age")}>Age range</button>
        <button className={tab === "grade" ? "active" : ""} onClick={() => setTab("grade")}>Grade</button>
      </div>

      {tab === "kit" && (
        <div className="cat-grid">
          {KIT_TYPES.map((k, i) => (
            <article key={k.id} className="cat-card">
              <div className="cat-jersey" data-kit={k.id}>
                {k.id === "home" && <JerseyIcon colors={["#E63946", "#FFFFFF", "#FFFFFF"]} number="7" />}
                {k.id === "away" && <JerseyIcon colors={["#0F0F0F", "#E63946", "#FFFFFF"]} number="9" />}
                {k.id === "third" && <JerseyIcon colors={["#7CCF3C", "#0F0F0F", "#0F0F0F"]} number="11" />}
                {k.id === "gk" && <JerseyIcon colors={["#FFD60A", "#0F0F0F", "#0F0F0F"]} number="1" />}
                {k.id === "retro" && <JerseyIcon colors={["#F4F0E8", "#E63946", "#0F0F0F"]} number="10" />}
              </div>
              <div className="cat-meta">
                <span className="cat-idx">0{i + 1}</span>
                <h3>{k.name}</h3>
                <p>{k.desc}</p>
              </div>
            </article>
          ))}
        </div>
      )}

      {tab === "age" && (
        <div className="age-grid">
          {SIZE_RANGES.map((s) => (
            <article key={s.id} className="age-card">
              <div className="age-icon">{s.icon}</div>
              <h3>{s.label}</h3>
              <div className="age-range">{s.range}</div>
              <ul className="age-list">
                <li>Fan grade · 160gsm poly</li>
                <li>Player grade · 130gsm AeroPoly</li>
                <li>Heat-pressed badges</li>
                <li>Custom name/number print</li>
              </ul>
            </article>
          ))}
        </div>
      )}

      {tab === "grade" && (
        <div className="grade-grid">
          <article className="grade-card">
            <div className="grade-tag">FAN</div>
            <h3>Replica fan jerseys</h3>
            <div className="grade-price">volume pricing from <strong>$11.00</strong> / unit</div>
            <ul>
              <li>160gsm polyester knit</li>
              <li>Heat-transfer crest & sponsor</li>
              <li>Standard stitched collar</li>
              <li>Retail tag-ready (white-label OK)</li>
            </ul>
            <div className="grade-note">Best for: stadium shops, ad retailers, school PE kits.</div>
          </article>
          <article className="grade-card grade-card--player">
            <div className="grade-tag">PLAYER</div>
            <h3>Player-issue jerseys</h3>
            <div className="grade-price">quoted by volume tier and build spec</div>
            <ul>
              <li>130gsm bonded AeroPoly mesh</li>
              <li>Laser-cut ventilation panels</li>
              <li>Sublimated crest & sponsor</li>
              <li>Slim athletic cut, taped seams</li>
            </ul>
            <div className="grade-note">Best for: clubs, academies, premium fan retail.</div>
          </article>
        </div>
      )}
    </section>
  );
}

function PricingPanel({ onQuote, defaultQty = DEFAULT_QTY, className = "" }) {
  const [qty, setQty] = useState(defaultQty);
  const tier = priceFor(qty);
  const subtotal = qty * tier.price;

  return (
      <div className={`calc ${className}`}>
        <div className="calc-top">
          <div className="calc-label">Order quantity</div>
          <div className="calc-qty">
            <span className="calc-qty-num">{fmt(qty)}</span>
            <span className="calc-qty-unit">pieces</span>
          </div>
        </div>

        <input
          type="range" min={MIN_QTY} max={MAX_QTY} step="100"
          value={qty} onChange={(e) => setQty(+e.target.value)}
          className="calc-slider"
        />

        <div className="calc-ticks">
          {TIERS.map(t => (
            <button key={t.qty} className={`calc-tick ${qty >= t.qty ? "hit" : ""}`} onClick={() => setQty(t.qty)}>
              <span>{t.label}</span>
            </button>
          ))}
        </div>

        <div className="calc-result">
          <div className="calc-tier">
            <span className="calc-tier-label">Price band</span>
            <span className="calc-tier-name">{tier.range}</span>
          </div>
          <div className="calc-unit">
            <span>${tier.price.toFixed(2)}</span>
            <small>/ unit</small>
          </div>
          <div className="calc-total">
            <span>Total before shipping</span>
            <strong>${fmt(Math.round(subtotal))}</strong>
          </div>
          <div className="calc-margin">
            <span>Delivery</span>
            <strong>15 days</strong>
            <small>from order date</small>
          </div>
        </div>

        <button className="cta-btn cta-btn--lg cta-btn--full" onClick={() => onQuote({ qty })}>
          Start {fmt(qty)}-piece bulk quote →
        </button>
        <div className="calc-fine">
          Pricing shown before shipping · final quote depends on jersey grade, print complexity, packaging, and destination
        </div>
      </div>
  );
}

function PricingCalc({ onQuote }) {
  return (
    <section id="pricing" className="section section--alt">
      <div className="section-head">
        <span className="eyebrow">/02 — PRICING</span>
        <h2>Bulk pricing<br/>before shipping.</h2>
        <p>Minimum order is 100 pieces. Mix teams, kit styles, adult, kids, toddler, fan, and player jerseys in one manufacturing order.</p>
      </div>

      <PricingPanel onQuote={onQuote} />
    </section>
  );
}

function TeamsGrid({ onTeam }) {
  const [q, setQ] = useState("");
  const [region, setRegion] = useState("All");
  const regions = ["All", ...new Set(ALL_TEAMS.map(team => team.region))];

  const filtered = useMemo(() => {
    return ALL_TEAMS.filter(t => {
      if (region !== "All" && t.region !== region) return false;
      if (q && !t.name.toLowerCase().includes(q.toLowerCase())) return false;
      return true;
    });
  }, [q, region]);

  return (
    <section id="teams" className="section">
      <div className="section-head">
        <span className="eyebrow">/03 — ROSTER</span>
        <h2>International teams.<br/>Pick your market.</h2>
        <p>We manufacture bulk jerseys for all international teams. Browse high-demand ad markets below, or request any country directly in the quote form.</p>
      </div>

      <div className="team-controls">
        <input
          type="search"
          className="team-search"
          placeholder="Search nation…"
          value={q}
          onChange={(e) => setQ(e.target.value)}
        />
        <div className="region-chips">
          {regions.map(r => (
            <button key={r} className={r === region ? "active" : ""} onClick={() => setRegion(r)}>
              {r}
            </button>
          ))}
        </div>
      </div>

      <div className="teams-count">
        <strong>{filtered.length}</strong> of {ALL_TEAMS.length} nations
      </div>

      <div className="teams-grid">
        {filtered.map(t => (
          <a key={t.name} href={teamUrl(t)} className="team-card" aria-label={`View ${t.name} bulk jersey manufacturing page`}
            onClick={(e) => { e.preventDefault(); onTeam(t); }}>
            <div className="team-flag">
              {t.colors.map((c, i) => (
                <span key={i} style={{ background: c }}></span>
              ))}
            </div>
            <div className="team-meta">
              <h4>{t.name}</h4>
              <span>{t.region}</span>
            </div>
            <div className="team-tags">
              {t.host && <span className="tag tag--host">HOST '26</span>}
              {t.hot && <span className="tag tag--hot">HIGH DEMAND</span>}
              {!!t.productCount && <span className="tag">{t.productCount} STYLES</span>}
            </div>
          </a>
        ))}
        {filtered.length === 0 && (
          <div className="empty">No nations match. Try clearing filters.</div>
        )}
      </div>
    </section>
  );
}

function ProductPage({ team, onBack, onQuote }) {
  const code = teamCode(team);
  const products = productsForTeam(team);
  const featuredProducts = pickFeaturedProducts(products);
  const mainProduct = featuredProducts[0];
  const [filter, setFilter] = useState("All");
  const [showAllProducts, setShowAllProducts] = useState(false);
  const productFilters = useMemo(() => {
    const filters = ["All"];
    const variants = new Set(products.map(product => product.variant));
    for (const label of ["Fan", "Player", "Kids", "Baby", "Women"]) {
      if (variants.has(label)) filters.push(label);
    }
    if (products.some(product => product.kit === "Retro")) filters.push("Retro");
    if (products.some(product => product.kit === "Goalkeeper")) filters.push("Goalkeeper");
    return filters;
  }, [team.slug]);
  const visibleProducts = useMemo(() => {
    if (filter === "All") return products;
    if (filter === "Retro" || filter === "Goalkeeper") {
      return products.filter(product => product.kit === filter);
    }
    return products.filter(product => product.variant === filter);
  }, [team.slug, filter]);
  const displayedProducts = showAllProducts ? visibleProducts : visibleProducts.slice(0, INITIAL_PRODUCT_COUNT);

  useEffect(() => {
    setFilter("All");
  }, [team.slug]);

  useEffect(() => {
    setShowAllProducts(false);
  }, [team.slug, filter]);

  useEffect(() => {
    if (window.location.hash === "#catalog") {
      requestAnimationFrame(() => {
        document.getElementById("catalog")?.scrollIntoView({ block: "start" });
      });
    }
  }, [team.slug, products.length]);

  const awayColors = [team.colors[1] || "#FFFFFF", team.colors[2] || "#0F0F0F", team.colors[0] || "#E63946"];
  const thirdColors = [team.colors[2] || "#0F0F0F", team.colors[0] || "#E63946", team.colors[1] || "#FFFFFF"];

  return (
    <>
      <section className="product-hero">
        <div className="product-hero-inner">
          <div className="product-topline">
            <a href={`${rootPrefix()}#teams`} className="link-btn product-back" onClick={(e) => { e.preventDefault(); onBack(); }}>
              ← All countries
            </a>
            <span>100+ piece bulk manufacturing</span>
          </div>

          <div className="product-grid">
            <div className="product-copy">
              <div className="kicker product-kicker">
                <span className="dot"></span>
                <span>Bulk {team.name} jersey manufacturer</span>
              </div>
              <h1>Bulk {team.name} jerseys delivered in 15 days.</h1>
              <p>
                Manufacture {team.name} home, away, third, goalkeeper, and retro jerseys
                for adults, kids, and toddlers. Fan and player-grade builds available.
                Minimum order is <strong>100 pieces</strong>, with pricing shown before shipping.
              </p>
              <div className="product-ctas">
                <button className="cta-btn cta-btn--lg" onClick={() => onQuote({ team: team.name, qty: DEFAULT_QTY })}>
                  Get {team.name} quote →
                </button>
                {!!products.length && <a href="#catalog" className="link-btn">View styles</a>}
              </div>
              <div className="hero-stats product-stats">
                <div><strong>{products.length || "All"}</strong><span>styles available</span></div>
                <div><strong>100</strong><span>piece minimum</span></div>
                <div><strong>15d</strong><span>delivered from order</span></div>
              </div>
              <div className="product-pills">
                <span>Fan + player jerseys</span>
                <span>Adults, kids + toddlers</span>
                <span>Home, away, third + retro</span>
                {!!products.length && <span>{products.length} styles available</span>}
              </div>
            </div>

            <div className="product-showcase" aria-label={`${team.name} jersey product images`}>
              <div className="product-main-jersey">
                {mainProduct ? (
                  <img src={assetUrl(mainProduct.image)} alt={`${team.name} ${mainProduct.title}`} />
                ) : (
                  <JerseyIcon colors={team.colors} number="10" name={code} />
                )}
              </div>
              <div className="product-kit-row">
                {featuredProducts.length ? featuredProducts.slice(0, 3).map(product => (
                  <div key={product.id}>
                    <img src={assetUrl(product.image)} alt={`${team.name} ${product.title}`} loading="lazy" />
                    <span>{productLabel(product)}</span>
                  </div>
                )) : (
                  <>
                    <div>
                      <JerseyIcon colors={team.colors} number="10" name="HOME" />
                      <span>Home</span>
                    </div>
                    <div>
                      <JerseyIcon colors={awayColors} number="9" name="AWAY" />
                      <span>Away</span>
                    </div>
                    <div>
                      <JerseyIcon colors={thirdColors} number="1" name="GK" />
                      <span>Third / GK</span>
                    </div>
                  </>
                )}
              </div>
            </div>
          </div>

          <PricingPanel className="product-calc" onQuote={(data) => onQuote({ ...data, team: team.name })} />
        </div>
      </section>
      <Marquee />

      {!!products.length && (
        <section id="catalog" className="section section--alt product-catalog-section">
          <div className="section-head">
            <span className="eyebrow">/ AVAILABLE JERSEYS</span>
            <h2>{team.name} jersey styles for bulk orders.</h2>
            <p>Browse current fan, player, kids, women, baby, retro, goalkeeper, home, and away options when available. Every style can be quoted for 100+ piece manufacturing orders.</p>
          </div>

          <div className="product-filter-tabs">
            {productFilters.map(label => (
              <button key={label} className={filter === label ? "active" : ""} onClick={() => setFilter(label)}>
                {label}
              </button>
            ))}
          </div>

          <div className="product-card-grid">
            {displayedProducts.map(product => (
              <article key={product.id} className="product-card">
                <div className="product-card-image">
                  <img src={assetUrl(product.image)} alt={`${team.name} ${product.title}`} loading="lazy" />
                </div>
                <div className="product-card-body">
                  <div className="product-card-kicker">{productLabel(product)}</div>
                  <h3>{product.title}</h3>
                  <button className="product-card-quote" onClick={() => onQuote({
                    team: team.name,
                    qty: DEFAULT_QTY,
                    grade: product.variant === "Player" ? "player" : "fan",
                    product: product.title,
                  })}>
                    Quote this style →
                  </button>
                </div>
              </article>
            ))}
          </div>

          {visibleProducts.length > displayedProducts.length && (
            <div className="catalog-load-more">
              <button onClick={() => setShowAllProducts(true)}>
                Show all {visibleProducts.length} {team.name} styles
              </button>
            </div>
          )}
        </section>
      )}

      <section className="section product-section">
        <div className="section-head">
          <span className="eyebrow">/ BULK ORDER DETAILS</span>
          <h2>Manufacturing details for wholesale buyers.</h2>
          <p>Designed for retailers, fan shops, clubs, schools, and campaign-based bulk jersey orders.</p>
        </div>
        <div className="product-detail-grid">
          <article>
            <h3>Kit styles</h3>
            <p>Home, away, third, goalkeeper, retro, and custom sponsor-print variants.</p>
          </article>
          <article>
            <h3>Size runs</h3>
            <p>Adults, kids, and toddlers with mixed size breakdowns under one order.</p>
          </article>
          <article>
            <h3>Grades</h3>
            <p>Fan jerseys for resale volume and player jerseys for premium buyers.</p>
          </article>
          <article>
            <h3>Branding</h3>
            <p>White-label tags, polybags, custom sponsor art, names, and numbers.</p>
          </article>
          <article>
            <h3>Fulfillment</h3>
            <p>Delivered in 15 days from order date after artwork and order details are confirmed.</p>
          </article>
          <article>
            <h3>Bulk pricing</h3>
            <p>Starts at 100 pieces, with per-unit pricing clearly separated before shipping.</p>
          </article>
        </div>
      </section>

      <section className="cta-banner product-cta">
        <div className="cta-banner-inner">
          <h2>Manufacture {team.name} jerseys in bulk.</h2>
          <p>100 piece minimum. Delivered in 15 days from order date.</p>
          <button className="cta-btn cta-btn--lg cta-btn--inverse" onClick={() => onQuote({ team: team.name, qty: DEFAULT_QTY })}>
            Get {team.name} quote →
          </button>
        </div>
      </section>
    </>
  );
}

function Process() {
  const steps = [
    { n: "01", t: "Send brief", d: "Tell us country, kit style, grade, sizes, quantity, sponsor print, and destination." },
    { n: "02", t: "Confirm order", d: "We lock pricing, production details, and invoice the bulk manufacturing order." },
    { n: "03", t: "Manufacture", d: "Cut, sublimate, print, sew, and finish fan or player jerseys to your spec." },
    { n: "04", t: "QC + pack", d: "Every order is checked, folded, packed, and prepared for delivery." },
    { n: "05", t: "Deliver", d: "Delivered in 15 days from the date your order is placed." },
  ];
  return (
    <section id="process" className="section section--dark">
      <div className="section-head">
        <span className="eyebrow eyebrow--light">/04 — PROCESS</span>
        <h2>Bulk jerseys<br/>delivered in 15 days.</h2>
      </div>
      <ol className="process">
        {steps.map((s) => (
          <li key={s.n} className="process-step">
            <div className="process-n">{s.n}</div>
            <div>
              <h3>{s.t}</h3>
              <p>{s.d}</p>
            </div>
          </li>
        ))}
      </ol>
    </section>
  );
}

function QuoteForm({ open, onClose, prefilled }) {
  const [step, setStep] = useState(1);
  const [data, setData] = useState({
    qty: prefilled?.qty || DEFAULT_QTY,
    grade: prefilled?.grade || "fan",
    teams: prefilled?.team ? [prefilled.team] : [],
    name: "", email: "", company: "", country: "",
    notes: prefilled?.product ? `Interested in: ${prefilled.product}` : ""
  });
  const [sent, setSent] = useState(false);

  useEffect(() => {
    setData(d => ({
      ...d,
      qty: prefilled?.qty || d.qty || DEFAULT_QTY,
      grade: prefilled?.grade || d.grade,
      teams: prefilled?.team && !d.teams.includes(prefilled.team)
        ? [prefilled.team, ...d.teams]
        : d.teams,
      notes: prefilled?.product && !d.notes.includes(prefilled.product)
        ? `Interested in: ${prefilled.product}${d.notes ? `\n${d.notes}` : ""}`
        : d.notes
    }));
  }, [prefilled]);

  useEffect(() => {
    if (open) { setStep(1); setSent(false); document.body.style.overflow = "hidden"; }
    else document.body.style.overflow = "";
    return () => { document.body.style.overflow = ""; };
  }, [open]);

  if (!open) return null;

  const toggleTeam = (name) => {
    setData(d => ({
      ...d,
      teams: d.teams.includes(name) ? d.teams.filter(t => t !== name) : [...d.teams, name]
    }));
  };

  const submit = (e) => {
    e.preventDefault();
    setSent(true);
  };

  return (
    <div className="quote-overlay" onClick={onClose}>
      <div className="quote-modal" onClick={(e) => e.stopPropagation()}>
        <button className="quote-close" onClick={onClose} aria-label="Close">×</button>

        {!sent ? (
          <>
            <div className="quote-progress">
              <span className={step >= 1 ? "active" : ""}>1 · Order</span>
              <span className={step >= 2 ? "active" : ""}>2 · Teams</span>
              <span className={step >= 3 ? "active" : ""}>3 · Contact</span>
            </div>

            {step === 1 && (
              <div className="quote-step">
                <h3>What are you ordering?</h3>
                <label className="q-label">Total quantity</label>
                <div className="q-qty-row">
                  <input type="number" min={MIN_QTY} step="50" value={data.qty}
                    onChange={(e) => setData({ ...data, qty: +e.target.value })} />
                  <span>pieces</span>
                </div>
                <div className="q-qty-quick">
                  {QUICK_QTYS.map(n => (
                    <button key={n} type="button"
                      className={data.qty === n ? "active" : ""}
                      onClick={() => setData({ ...data, qty: n })}>{fmt(n)}</button>
                  ))}
                </div>

                <label className="q-label">Grade</label>
                <div className="q-grade">
                  <button type="button" className={data.grade === "fan" ? "active" : ""}
                    onClick={() => setData({ ...data, grade: "fan" })}>
                    <strong>Fan</strong><span>bulk tier</span>
                  </button>
                  <button type="button" className={data.grade === "player" ? "active" : ""}
                    onClick={() => setData({ ...data, grade: "player" })}>
                    <strong>Player</strong><span>pro spec</span>
                  </button>
                  <button type="button" className={data.grade === "mixed" ? "active" : ""}
                    onClick={() => setData({ ...data, grade: "mixed" })}>
                    <strong>Mixed</strong><span>both grades</span>
                  </button>
                </div>

                <div className="quote-actions">
                  <button type="button" className="cta-btn cta-btn--full" onClick={() => setStep(2)}>
                    Continue →
                  </button>
                </div>
              </div>
            )}

            {step === 2 && (
              <div className="quote-step">
                <h3>Which nations?</h3>
                <p className="q-sub">Pick all that apply. If a country is not shown, add it in the notes and we'll manufacture it.</p>
                <div className="q-teams">
                  {ALL_TEAMS.map(t => (
                    <button key={t.name} type="button"
                      className={`q-team ${data.teams.includes(t.name) ? "active" : ""}`}
                      onClick={() => toggleTeam(t.name)}>
                      <span className="q-team-flag">
                        {t.colors.map((c, i) => <span key={i} style={{ background: c }}></span>)}
                      </span>
                      {t.name}
                    </button>
                  ))}
                </div>
                <div className="q-teams-count">
                  {data.teams.length} selected
                </div>
                <div className="quote-actions">
                  <button type="button" className="link-btn" onClick={() => setStep(1)}>← Back</button>
                  <button type="button" className="cta-btn" onClick={() => setStep(3)}>Continue →</button>
                </div>
              </div>
            )}

            {step === 3 && (
              <form className="quote-step" onSubmit={submit}>
                <h3>Where do we send the quote?</h3>
                <label className="q-label">Name</label>
                <input required value={data.name} onChange={(e) => setData({ ...data, name: e.target.value })} />
                <label className="q-label">Work email</label>
                <input required type="email" value={data.email} onChange={(e) => setData({ ...data, email: e.target.value })} />
                <div className="q-row">
                  <div>
                    <label className="q-label">Company</label>
                    <input value={data.company} onChange={(e) => setData({ ...data, company: e.target.value })} />
                  </div>
                  <div>
                    <label className="q-label">Country</label>
                    <input value={data.country} onChange={(e) => setData({ ...data, country: e.target.value })} />
                  </div>
                </div>
                <label className="q-label">Anything else?</label>
                <textarea rows="3" placeholder="Sponsor prints, delivery deadlines, retro years…"
                  value={data.notes} onChange={(e) => setData({ ...data, notes: e.target.value })} />

                <div className="quote-actions">
                  <button type="button" className="link-btn" onClick={() => setStep(2)}>← Back</button>
                  <button type="submit" className="cta-btn">Send quote request →</button>
                </div>
              </form>
            )}
          </>
        ) : (
          <div className="quote-success">
            <div className="success-mark">✓</div>
            <h3>Brief received.</h3>
            <p>We'll have your locked quote + digital mockups in your inbox within <strong>24 hours</strong>. Check spam if it doesn't land.</p>
            <button className="cta-btn cta-btn--full" onClick={onClose}>Back to site</button>
          </div>
        )}
      </div>
    </div>
  );
}

function FAQ() {
  const items = [
    { q: "What's your minimum order?", a: "100 pieces total per order. You can mix teams, kit types (home/away/third/goalkeeper/retro), sizes (adult/kids/toddler), and grades (fan/player)." },
    { q: "How fast is delivery?", a: "Orders are delivered in 15 days from the date the order is placed, after the final quantity, artwork, sizes, and destination are confirmed." },
    { q: "Do you do custom name & number printing?", a: "Yes — sublimation, heat-press or stitch-twill. Send us a roster spreadsheet and we'll print to spec for bulk manufacturing orders." },
    { q: "Which retro years do you cover?", a: "1970-2010 across major international teams. Send us the year and country, and we'll confirm the build spec." },
    { q: "How does shipping work?", a: "The pricing shown is before shipping. We quote shipping by destination and order size so you can see product cost and logistics separately." },
    { q: "Can we white-label?", a: "Yes — neutral hangtags, your own woven brand label, your own polybag. We'll never put our brand on resale stock." },
    { q: "What about IP / licensing?", a: "These are unlicensed replicas inspired by national colorways — no federation, club or brand logos. If you have your own licensed crests, send the artwork and we'll print them." },
  ];
  const [open, setOpen] = useState(0);
  return (
    <section className="section section--faq">
      <div className="section-head">
        <span className="eyebrow">/05 — FAQ</span>
        <h2>Straight answers.</h2>
      </div>
      <div className="faq">
        {items.map((it, i) => (
          <div key={i} className={`faq-item ${open === i ? "open" : ""}`}>
            <button onClick={() => setOpen(open === i ? -1 : i)}>
              <span>{it.q}</span>
              <span className="faq-icon">{open === i ? "−" : "+"}</span>
            </button>
            {open === i && <div className="faq-a">{it.a}</div>}
          </div>
        ))}
      </div>
    </section>
  );
}

function CTABanner({ onQuote }) {
  return (
    <section className="cta-banner">
      <div className="cta-banner-inner">
        <h2>Ready to manufacture in bulk?</h2>
        <p>100 piece minimum. Delivered in 15 days from order date.</p>
        <button className="cta-btn cta-btn--lg cta-btn--inverse" onClick={onQuote}>
          Get my quote →
        </button>
        <div className="cta-banner-meta">
          <span>WhatsApp: +62 811 0000 0000</span>
          <span>·</span>
          <span>orders@nevearjerseys.com</span>
        </div>
      </div>
    </section>
  );
}

function Footer() {
  return (
    <footer className="site-footer">
      <div className="footer-top">
        <Logo />
        <div className="footer-cols">
          <div>
            <h5>Products</h5>
            <a href="#kits">Kit types</a>
            <a href="#teams">All nations</a>
            <a href="#pricing">Pricing</a>
          </div>
          <div>
            <h5>Company</h5>
            <a href="#process">Process</a>
            <a href="#">Factories</a>
            <a href="#">Shipping</a>
          </div>
          <div>
            <h5>Contact</h5>
            <a href="#">WhatsApp</a>
            <a href="#">Email</a>
            <a href="#">Sample request</a>
          </div>
        </div>
      </div>
      <div className="footer-bottom">
        <span>© 2026 {BRAND_NAME} · Bandung · Sialkot · Guangzhou</span>
        <span>Unlicensed replicas · Not affiliated with FIFA or any federation</span>
      </div>
    </footer>
  );
}

function StickyBar({ onQuote }) {
  const [show, setShow] = useState(false);
  useEffect(() => {
    const onScroll = () => setShow(window.scrollY > 600);
    window.addEventListener("scroll", onScroll);
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  return (
    <div className={`sticky-bar ${show ? "show" : ""}`}>
      <div className="sticky-bar-text">
        <strong>100+ pieces · 15 days</strong>
        <span>Bulk manufacturing quote</span>
      </div>
      <button className="cta-btn cta-btn--sm" onClick={onQuote}>Quote →</button>
    </div>
  );
}

// ============ APP ============

function App() {
  const readActiveTeam = () => {
    const params = new URLSearchParams(window.location.search);
    const pathSlug = productSlugFromPath();
    const initialSlug = pathSlug ? window.INITIAL_TEAM : "";
    return findTeam(pathSlug || params.get("team") || initialSlug || "") || null;
  };

  const [activeTeam, setActiveTeam] = useState(readActiveTeam);
  const [quoteOpen, setQuoteOpen] = useState(false);
  const [prefilled, setPrefilled] = useState(null);

  const openQuote = (data) => {
    setPrefilled(data || null);
    setQuoteOpen(true);
  };

  const openTeam = (team) => {
    window.history.pushState({}, "", teamUrl(team));
    setActiveTeam(team);
    window.scrollTo({ top: 0, behavior: "smooth" });
  };

  const backToTeams = () => {
    window.history.pushState({}, "", `${rootPrefix()}#teams`);
    setActiveTeam(null);
    requestAnimationFrame(() => {
      document.getElementById("teams")?.scrollIntoView({ block: "start" });
    });
  };

  useEffect(() => {
    const onPopState = () => setActiveTeam(readActiveTeam());
    window.addEventListener("popstate", onPopState);
    return () => window.removeEventListener("popstate", onPopState);
  }, []);

  useEffect(() => {
    const baseTitle = `${BRAND_NAME} — Bulk International Football Jersey Manufacturer`;
    const baseDescription = BASE_DESCRIPTION;
    const jsonId = "product-jsonld";
    let jsonNode = document.getElementById(jsonId);

    if (activeTeam) {
      const slug = slugify(activeTeam.name);
      const url = siteUrl(`products/${slug}.html`);
      const productCount = productsForTeam(activeTeam).length;
      const styleText = `${productCount} available jersey style${productCount === 1 ? "" : "s"}`;
      const title = `Bulk ${activeTeam.name} Jerseys | ${BRAND_NAME}`;
      const description = `${BRAND_NAME} manufactures bulk ${activeTeam.name} jerseys with ${styleText}. Fan, player, kids, retro, home and away options. 100 piece minimum, delivered in 15 days.`;

      document.title = title;
      setMeta("description", description);
      setMeta("og:title", title, "property");
      setMeta("og:description", description, "property");
      setMeta("og:type", "product", "property");
      setMeta("og:url", url, "property");
      setCanonical(url);

      if (!jsonNode) {
        jsonNode = document.createElement("script");
        jsonNode.id = jsonId;
        jsonNode.type = "application/ld+json";
        document.head.appendChild(jsonNode);
      }
      jsonNode.textContent = JSON.stringify({
        "@context": "https://schema.org",
        "@type": "Product",
        name: `Bulk ${activeTeam.name} Football Jerseys`,
        description,
        brand: { "@type": "Brand", name: BRAND_NAME },
        category: "Wholesale football jerseys",
        offers: {
          "@type": "AggregateOffer",
          lowPrice: "11.00",
          highPrice: "14.50",
          priceCurrency: "USD",
          offerCount: "4",
          availability: "https://schema.org/InStock",
          url
        }
      });
    } else {
      document.title = baseTitle;
      setMeta("description", baseDescription);
      setMeta("og:title", baseTitle, "property");
      setMeta("og:description", baseDescription, "property");
      setMeta("og:type", "website", "property");
      setMeta("og:url", siteUrl(""), "property");
      setCanonical(siteUrl(""));
      if (jsonNode) jsonNode.remove();
    }
  }, [activeTeam]);

  return (
    <>
      <Header onQuote={() => openQuote()} navBase={activeTeam ? rootPrefix() : ""} />
      <main>
        {activeTeam ? (
          <ProductPage team={activeTeam} onBack={backToTeams} onQuote={openQuote} />
        ) : (
          <>
            <Hero onQuote={() => openQuote()} />
            <Categories />
            <PricingCalc onQuote={openQuote} />
            <TeamsGrid onTeam={openTeam} />
            <Process />
            <FAQ />
            <CTABanner onQuote={() => openQuote()} />
          </>
        )}
      </main>
      <Footer />
      <StickyBar onQuote={() => openQuote()} />
      <QuoteForm open={quoteOpen} onClose={() => setQuoteOpen(false)} prefilled={prefilled} />
    </>
  );
}

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