/* global React */
const { useState, useEffect, useRef } = React;

// ============ ICONS (Lucide, inline) ============
const Icon = {
  ArrowRight: (p) => (
    <svg viewBox="0 0 24 24" width={p.size || 18} height={p.size || 18} fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="square" strokeLinejoin="miter" {...p}>
      <path d="M5 12h14M13 5l7 7-7 7" />
    </svg>
  ),
  Menu: (p) => (
    <svg viewBox="0 0 24 24" width={p.size || 20} height={p.size || 20} fill="none" stroke="currentColor" strokeWidth="1.5" {...p}>
      <path d="M4 7h16M4 12h16M4 17h16" />
    </svg>
  ),
  X: (p) => (
    <svg viewBox="0 0 24 24" width={p.size || 20} height={p.size || 20} fill="none" stroke="currentColor" strokeWidth="1.5" {...p}>
      <path d="M6 6l12 12M18 6L6 18" />
    </svg>
  ),
  Check: (p) => (
    <svg viewBox="0 0 24 24" width={p.size || 18} height={p.size || 18} fill="none" stroke="currentColor" strokeWidth="1.5" {...p}>
      <path d="M5 13l4 4L19 7" />
    </svg>
  ),
  Plus: (p) => (
    <svg viewBox="0 0 24 24" width={p.size || 18} height={p.size || 18} fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="square" {...p}>
      <path d="M12 5v14M5 12h14" />
    </svg>
  ),
  ChevronRight: (p) => (
    <svg viewBox="0 0 24 24" width={p.size || 14} height={p.size || 14} fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="square" strokeLinejoin="miter" {...p}>
      <path d="M9 6l6 6-6 6" />
    </svg>
  ),
  Linkedin: (p) => (
    <svg viewBox="0 0 24 24" width={p.size || 18} height={p.size || 18} fill="none" stroke="currentColor" strokeWidth="1.5" {...p}>
      <rect x="3" y="3" width="18" height="18" rx="0.5" />
      <path d="M8 10v7M8 7v.01M12 17v-5M12 17V12c0-1.1.9-2 2-2s2 .9 2 2v5" />
    </svg>
  ),
};

// ============ REVEAL ON SCROLL ============
function useReveal() {
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current; if (!el) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting) { e.target.classList.add('in'); io.unobserve(e.target); }
      });
    }, { threshold: 0.12, rootMargin: '0px 0px -40px 0px' });
    el.querySelectorAll('.mf-reveal').forEach((n) => io.observe(n));
    return () => io.disconnect();
  }, []);
  return ref;
}

// ============ LOGO LOCKUP ============
// V1 Care-label mark + Newsreader wordmark. Three variants: horizontal | stacked | reverse.
const MarkSvg = () => (
  <svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="Market Fit Group">
    <g fill="currentColor">
      <rect x="20" y="28" width="60" height="1.5" />
      <text x="50" y="64" fontFamily="'Newsreader', 'Tiempos Headline', Georgia, serif" fontWeight="400" fontSize="36" letterSpacing="2" textAnchor="middle">M·F</text>
      <rect x="20" y="74" width="60" height="1" />
      <text x="50" y="86" fontFamily="'Instrument Sans', sans-serif" fontSize="7" letterSpacing="2" textAnchor="middle">EST · 1974</text>
    </g>
  </svg>
);
function Lockup({ variant = 'horizontal', reverse = false, size, href = null, className = '', ariaLabel = 'Market Fit Group' }) {
  const cls = [
    'mf-lockup',
    variant === 'stacked' ? 'mf-lockup--stacked' : '',
    size === 'lg' ? 'mf-lockup--lg' : '',
    reverse ? 'mf-lockup--reverse' : '',
    className,
  ].filter(Boolean).join(' ');
  const inner = (
    <React.Fragment>
      <span className="mf-lockup-mark" aria-hidden="true"><MarkSvg /></span>
      <span className="mf-wordmark">Market Fit <em>Group</em></span>
    </React.Fragment>
  );
  if (href !== null) {
    return <a href={href} className={cls} aria-label={ariaLabel}>{inner}</a>;
  }
  return <span className={cls} aria-label={ariaLabel} role="img">{inner}</span>;
}

// ============ NAV ============
function Nav() {
  const [scrolled, setScrolled] = useState(false);
  const [open, setOpen] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 40);
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  const links = [
    { label: 'Solutions',      href: '/solutions' },
    { label: 'Our Network',    href: '/our-network' },
    { label: 'Sustainability', href: '/sustainability' },
    { label: 'About',          href: '/about' },
    { label: 'Insights',       href: '/insights' },
  ];
  return (
    <React.Fragment>
      <nav className={`mf-nav ${scrolled ? 'scrolled' : ''}`}>
        <div className="mf-nav-inner">
          <Lockup href="/" />
          <div className="mf-nav-links">
            {links.map((l) => <a key={l.label} href={l.href}>{l.label}</a>)}
          </div>
          <div className="mf-nav-right">
            <span className="mf-nav-lang" data-mf-lang-switch="nav"></span>
            <a href="/contact" className="mf-btn-p">Start your next collection</a>
            <button className="mf-menu-btn" onClick={() => setOpen(!open)} aria-label="Menu">
              {open ? <Icon.X /> : <Icon.Menu />}
            </button>
          </div>
        </div>
      </nav>
      <div className={`mf-mobile-menu ${open ? 'open' : ''}`}>
        {links.map((l) => <a key={l.label} href={l.href} onClick={() => setOpen(false)}>{l.label}</a>)}
        <a href="/contact" className="mf-btn-p" style={{ marginTop: 32, alignSelf: 'flex-start' }} onClick={() => setOpen(false)}>
          Start your next collection <Icon.ArrowRight />
        </a>
      </div>
    </React.Fragment>
  );
}

// ============ HERO ============
function Hero() {
  // Fallback frames (crossfade) while a real factory loop is provided by the family.
  const frames = [
    '/assets/images/img-01.png',
    '/assets/images/img-03.png',
    '/assets/images/img-12.png',
    '/assets/images/img-18.png',
  ];
  const [idx, setIdx] = useState(0);
  const videoRef = useRef(null);
  useEffect(() => {
    const t = setInterval(() => setIdx((i) => (i + 1) % frames.length), 4200);
    return () => clearInterval(t);
  }, []);
  return (
    <section className="mf-hero" id="hero">
      {/* Real <video> element, silent + looped. Uses the poster as a visual placeholder
          until a factory-floor clip is supplied. */}
      <video
        ref={videoRef}
        className="mf-hero-video"
        autoPlay muted loop playsInline
        poster="/assets/images/img-01.png"
        aria-hidden="true"
      >
        {/* Video source intentionally empty — placeholder until the family supplies a loop. */}
      </video>
      <div className="mf-hero-frames">
        {frames.map((f, i) => (
          <div key={f} className={`mf-hero-frame ${i === idx ? 'active' : ''}`} style={{ backgroundImage: `url(${f})` }} />
        ))}
      </div>
      <div className="mf-hero-vignette" />
      <div className="mf-hero-eyebrow">Market Fit Group &nbsp;/&nbsp; Since 1974</div>
      <div className="mf-hero-content">
        <h1>The ODM partner for<br /><em>contemporary fashion brands.</em></h1>
        <p className="mf-hero-sub">
          From tech-pack to costed sample in seven days. Owned production floors across a seven-country network. Fifty-two years of practice.
        </p>
        <div className="mf-hero-ctas">
          <a href="/contact" className="mf-btn-p">Send a tech-pack <Icon.ArrowRight /></a>
          <a href="#solutions" className="mf-btn-hero">See how we work <Icon.ArrowRight size={16} /></a>
        </div>
      </div>
      <div className="mf-hero-scroll">
        <span>SCROLL</span>
        <div className="mf-hero-scroll-line" />
      </div>
    </section>
  );
}

// ============ CREDENTIALS ============
function Credentials() {
  const data = [
    { num: '52', unit: 'Years', label: 'Family-owned since 1974' },
    { num: '7', unit: 'Countries', label: 'Asia, Middle East, and Europe' },
    { num: '13', unit: 'Sites', label: 'Offices and factories across seven countries' },
    { num: '7', unit: 'Days', label: 'Sample turnaround' },
  ];
  return (
    <section className="mf-creds">
      <div className="mf-creds-grid">
        {data.map((d, i) => (
          <div key={i} className="mf-cred mf-reveal" style={{ transitionDelay: `${i * 60}ms` }}>
            <div className="mf-cred-num">{d.num}</div>
            <div className="mf-cred-unit">{d.unit}</div>
            <div className="mf-cred-label">{d.label}</div>
          </div>
        ))}
      </div>
    </section>
  );
}

// ============ SOLUTIONS ============
function Solutions() {
  const items = [
    { title: 'ODM and design development', desc: 'From sketch to production-ready garment. In-house technical and design teams.', img: '/assets/images/img-02.png', href: '/solutions/odm' },
    { title: 'Sampling', desc: 'Seven days from brief to costed sample on your desk. Sample rooms in Vietnam and Suzhou run the cadence.', img: '/assets/images/img-03.png', href: '/solutions/sampling' },
    { title: 'Fabric and trim sourcing', desc: 'Owned fabric warehouse in Shaoxing. Vietnam mills growing alongside under Tier 2 audit. Full chain visibility.', img: '/assets/images/img-05.png', href: '/solutions/fabric' },
    { title: 'Small-batch production', desc: 'MOQ from 300 pieces in Suzhou, 500 in Vietnam. We run the schedule on floors we own. Premium quality at contemporary volumes.', img: '/assets/images/img-21.png', href: '/solutions/production' },
    { title: 'Quality and compliance', desc: 'Ten audit standards held across the network. Reports on request.', img: '/assets/images/img-04.png', href: '/solutions/quality' },
  ];
  return (
    <section className="mf-section" id="solutions">
      <div className="mf-section-head">
        <div className="mf-reveal">
          <div className="mf-eyebrow">What we do</div>
          <h2>Built for brands that lead on <em>design.</em></h2>
        </div>
        <p className="mf-lead mf-reveal" style={{ transitionDelay: '80ms' }}>
          We work with contemporary premium brands from first sketch to finished garment. Fabric sourced. Samples developed. Production planned. Quality audited. Each stage handled by the specialist who does that stage best.
        </p>
      </div>
      <div className="mf-solutions-grid">
        {items.map((s, i) => (
          <a key={s.title} href={s.href} className="mf-solution mf-reveal" style={{ transitionDelay: `${i * 60}ms`, textDecoration: 'none', color: 'inherit', borderBottom: '1px solid var(--mf-ink-10)' }}>
            <div className="mf-solution-media">
              <div className="mf-solution-num">{String(i + 1).padStart(2, '0')}</div>
              <img src={s.img} alt={s.title} width="1600" height="1200" loading="lazy" decoding="async" />
            </div>
            <div className="mf-solution-body">
              <h3 className="mf-solution-title">{s.title}</h3>
              <p className="mf-solution-desc">{s.desc}</p>
            </div>
          </a>
        ))}
      </div>
    </section>
  );
}

// ============ PROGRAMMES ============
// Self-recognition section: visitors find their archetype before reading
// the capability list. Number-led editorial cards, no images, restrained.
function Programmes() {
  const items = [
    {
      num: '01',
      title: 'First contemporary capsule',
      desc: 'For brands launching their first ODM-led collection. We start with sampling and small runs from a single country, scaling as the line proves out.',
      spec: '500-piece MOQ floor · 7-day sampling cycle',
      href: '/solutions/sampling',
    },
    {
      num: '02',
      title: 'China-plus-one diversification',
      desc: 'For established books rebalancing capacity outside China. We move selected styles into Vietnam, Bangladesh, India, or Turkey while keeping your China relationships intact.',
      spec: 'Multi-country production · consolidated reporting',
      href: '/our-network',
    },
    {
      num: '03',
      title: 'Certified-supply collection',
      desc: 'For sustainability-forward brands building GRS, GOTS, or OEKO-TEX-certified ranges. Chain-of-custody documentation from fibre to finished garment.',
      spec: 'Audit-ready · all production countries',
      href: '/sustainability',
    },
    {
      num: '04',
      title: 'Premium handling',
      desc: 'For the work other factories return. Low-GSM jersey, fine lace, hand-cut sequin, structured outerwear with fusing and shoulder pads. The pieces that need pattern makers who read the seam.',
      spec: 'Difficult fabrics · structured construction',
      href: '/our-network',
    },
    {
      num: '05',
      title: 'Drop-cycle production',
      desc: 'For contemporary brands running 4-6 drops per year. Repeatable 6-8 week production cycles across knits, wovens, and small jersey programmes.',
      spec: '6-8 week cycles · 4-6 drops per year',
      href: '/solutions/production',
    },
  ];
  return (
    <section className="mf-section" id="programmes">
      <div className="mf-section-head">
        <div className="mf-reveal">
          <div className="mf-eyebrow">Programmes</div>
          <h2>Find the shape <em>that fits.</em></h2>
        </div>
        <p className="mf-lead mf-reveal" style={{ transitionDelay: '80ms' }}>
          Most of what we do falls into one of these five archetypes. Pick the one that sounds like you, or send a brief that doesn't quite fit — we'll meet you where you are.
        </p>
      </div>
      <div className="mf-programmes">
        {items.map((p, i) => (
          <a key={p.num} href={p.href} className="mf-programme mf-reveal" style={{ transitionDelay: `${i * 50}ms` }}>
            <div className="mf-programme-num">{p.num}</div>
            <div className="mf-programme-rule" />
            <h3 className="mf-programme-title">{p.title}</h3>
            <p className="mf-programme-desc">{p.desc}</p>
            <div className="mf-programme-spec">{p.spec}</div>
          </a>
        ))}
      </div>
    </section>
  );
}

// ============ NETWORK (Map only) ============
// The 8-country card grid was removed because the Asia map below it does
// the same job — country chips at the bottom of the map double as the
// nav into individual country pages. Section wrapper preserves the
// #our-network anchor target referenced from about.jsx / about-fr.jsx.
function Network() {
  return (
    <section id="our-network">
      <WorldMap />
    </section>
  );
}

// ============ ASIA MAP ============
// Focus: Middle East → East Asia. Simple equirectangular slice roughly spanning
// lon 25°E–125°E, lat 42°N–10°N. Coordinates are hand-placed from real city
// locations, then scaled to the 1000×560 viewBox below.
function WorldMap() {
  // Real city coords then mapped: x = (lon - 25) * 10, y = (42 - lat) * 17.5
  const loc = (lon, lat) => ({ x: (lon - 25) * 10, y: (42 - lat) * 17.5 });
  const countries = [
    { name: 'Turkey',     slug: 'turkey',     ...loc(29.0, 41.0), city: 'Istanbul',        info: 'Istanbul — founding HQ, 1974' },
    { name: 'Pakistan',   slug: 'pakistan',   ...loc(67.0, 24.9), city: 'Karachi / Lahore', info: 'Cotton, knits' },
    { name: 'India',      slug: 'india',      ...loc(77.2, 28.6), city: 'Delhi / Mumbai',  info: 'Embellishment, embroidery' },
    { name: 'Bangladesh', slug: 'bangladesh', ...loc(90.4, 23.8), city: 'Dhaka',            info: 'Knits, basics at volume' },
    { name: 'Vietnam',    slug: 'vietnam',    ...loc(106.6, 17.5), city: 'Ho Chi Minh / Tien Giang', info: 'Owned floor in Tien Giang · trend-led womenswear' },
    { name: 'China',      slug: 'china',      ...loc(121.5, 31.2), city: 'Shanghai',        info: 'Suzhou, Nanjing, Hubei, Shaoxing — core network' },
    { name: 'Hong Kong',  slug: 'hong-kong',  ...loc(114.2, 22.3), city: 'Hong Kong',       info: 'Group HQ, sourcing & merchandising' },
  ];
  const countryHref = (slug) => `/our-network/${slug}`;

  // Connecting hairline path — west to east through the network.
  const routeOrder = ['Turkey', 'Pakistan', 'India', 'Bangladesh', 'China', 'Hong Kong', 'Vietnam'];
  const byName = Object.fromEntries(countries.map(c => [c.name, c]));
  const route = routeOrder.map(n => `${byName[n].x},${byName[n].y}`).join(' ');

  const [active, setActive] = useState(null);
  const [tt, setTt] = useState(null);
  const mapRef = useRef(null);

  return (
    <div className="mf-map-wrap mf-reveal" ref={mapRef}>
      <div className="mf-map-head">
        <div className="mf-eyebrow">Footprint</div>
        <h3>Seven sourcing countries. One accountable partner for each one.</h3>
      </div>
      <div className="mf-map" style={{ position: 'relative' }}>
        <svg viewBox="0 0 1000 560" preserveAspectRatio="xMidYMid meet">
          <AsiaPath />
          {/* Connecting hairline path */}
          <polyline
            points={route}
            fill="none"
            stroke="rgba(250,250,247,0.35)"
            strokeWidth="1"
            strokeDasharray="2 4"
          />
          {countries.map((c) => (
            <a
              key={c.name}
              href={countryHref(c.slug)}
              aria-label={`${c.name} — view country page`}
            >
              <g
                className={`mf-map-country ${active === c.name ? 'active' : ''}`}
                onMouseEnter={(e) => {
                  setActive(c.name);
                  const rect = mapRef.current.querySelector('.mf-map').getBoundingClientRect();
                  const svg = e.currentTarget.ownerSVGElement;
                  const pt = svg.createSVGPoint(); pt.x = c.x; pt.y = c.y;
                  const ctm = svg.getScreenCTM();
                  const s = pt.matrixTransform(ctm);
                  setTt({ x: s.x - rect.left, y: s.y - rect.top, name: c.name, city: c.city, info: c.info });
                }}
                onMouseLeave={() => { setActive(null); setTt(null); }}
              >
                <circle className="mf-map-dot-halo" cx={c.x} cy={c.y} r={18} />
                <circle className="mf-map-dot-halo" cx={c.x} cy={c.y} r={11} />
                <circle className="mf-map-dot" cx={c.x} cy={c.y} r={5} />
                <text className="mf-map-label" x={c.x} y={c.y + 26} textAnchor="middle">{c.name.toUpperCase()}</text>
              </g>
            </a>
          ))}
        </svg>
        {tt && (
          <div className="mf-map-tooltip show" style={{ left: tt.x, top: tt.y }}>
            <strong style={{ display: 'block', marginBottom: 2, fontFamily: 'var(--font-display)', fontSize: 16, fontWeight: 500 }}>{tt.name}</strong>
            <div style={{ fontSize: 11, textTransform: 'uppercase', letterSpacing: '0.12em', color: 'var(--mf-ink-40)', marginBottom: 4 }}>{tt.city}</div>
            {tt.info}
          </div>
        )}
      </div>
      <div className="mf-map-legend">
        {countries.map((c) => (
          <a key={c.name}
            href={countryHref(c.slug)}
            className={`mf-map-legend-item ${active === c.name ? 'active' : ''}`}
            onMouseEnter={() => setActive(c.name)}
            onMouseLeave={() => setActive(null)}
          >
            — {c.name}
          </a>
        ))}
      </div>
    </div>
  );
}

// Stylized dot-stipple landmass for Asia + Middle East.
// Uses bounds checks for rough country silhouettes on the 1000×560 canvas
// (same lon/lat basis as WorldMap · 25°E–125°E, 42°N–9°N).
function AsiaPath() {
  // Landmass regions as rectangles in lon/lat, converted to canvas space.
  // Each region is sampled as a dot grid. Kept intentionally rough — editorial, not cartographic.
  const toX = (lon) => (lon - 25) * 10;
  const toY = (lat) => (42 - lat) * 17.5;
  const dots = [];
  const step = 10;
  for (let lon = 25; lon <= 125; lon += 1.1) {
    for (let lat = 9; lat <= 42; lat += 0.9) {
      const x = toX(lon); const y = toY(lat);
      // Hand-tuned silhouettes
      const inTurkeyAnatolia = lon > 26 && lon < 45 && lat > 36 && lat < 42;
      const inMiddleEast = lon > 34 && lon < 60 && lat > 13 && lat < 37 && !(lon < 42 && lat < 22);
      const inCentralAsia = lon > 50 && lon < 80 && lat > 34 && lat < 42;
      const inIndiaSub = (lon > 67 && lon < 92 && lat > 8 && lat < 34) && !(lon > 88 && lat < 22);
      const inSEAsia = (lon > 92 && lon < 110 && lat > 9 && lat < 23);
      const inChina = (lon > 75 && lon < 123 && lat > 22 && lat < 42) && !(lon > 115 && lat > 38);
      const inKorea = lon > 124 && lon < 126 && lat > 34 && lat < 38;
      if (inTurkeyAnatolia || inMiddleEast || inCentralAsia || inIndiaSub || inSEAsia || inChina || inKorea) {
        // Noise check — skip ~15% of dots for organic feel
        if ((Math.sin(lon * 12.9898 + lat * 78.233) * 43758.5453 % 1 + 1) % 1 > 0.15) {
          dots.push({ x, y });
        }
      }
    }
  }
  return (
    <g opacity="0.32">
      {dots.map((d, i) => (
        <circle key={i} cx={d.x} cy={d.y} r="1.5" fill="rgba(250,250,247,0.55)" />
      ))}
    </g>
  );
}

// ============ COMPLIANCE ============
function Compliance() {
  const certs = [
    { label: 'amfori BSCI',     mark: <BSCIMark /> },
    { label: 'GRS 4.0',         img: '/assets/certifications/globalrecycledstandard.jpg' },
    { label: 'Higg Index',      img: '/assets/certifications/higgindex.png' },
    { label: 'OEKO-TEX',        img: '/assets/certifications/oekotex.png' },
    { label: 'Textile Genesis', img: '/assets/certifications/textilegenesis.jpg' },
  ];
  return (
    <section className="mf-section warm" id="sustainability">
      <div className="mf-section-head">
        <div className="mf-reveal">
          <div className="mf-eyebrow">Compliance</div>
          <h2>Audited to the standard <em>that matters.</em></h2>
        </div>
        <p className="mf-lead mf-reveal" style={{ transitionDelay: '80ms' }}>
          Buyers at contemporary premium brands don't have time to audit their own supply chain. We've already done it. Across our network we hold the major social, environmental, and material-traceability standards, including amfori BSCI, Higg FSLM, Higg FEM, ISO 14001, GRS, OEKO-TEX, and Textile Genesis. Different standards live at different sites. The per-site breakdown sits on our <a href="/sustainability">sustainability page</a>, and reports are available on request.
        </p>
      </div>
      <div className="mf-certs">
        {certs.map((c) => (
          <div key={c.label} className="mf-cert">
            <div className="mf-cert-mark">{c.img ? <img src={c.img} alt={c.label} loading="lazy" decoding="async" /> : c.mark}</div>
            <div className="mf-cert-label">{c.label}</div>
          </div>
        ))}
      </div>
      <p className="mf-certs-plus">
        Plus <em>ISO 14001</em> across the network.
      </p>
    </section>
  );
}

function GRSMark() {
  return (
    <svg viewBox="0 0 120 48" width="110" height="44">
      <circle cx="20" cy="24" r="14" fill="none" stroke="#2B8287" strokeWidth="1.8" />
      <path d="M8 24 Q20 16 32 24 Q20 32 8 24 Z" fill="none" stroke="#2B8287" strokeWidth="1.4" />
      <path d="M20 10 Q26 24 20 38" fill="none" stroke="#2B8287" strokeWidth="1.4" />
      <text x="42" y="21" fontFamily="var(--font-body)" fontSize="11" fontWeight="700" fill="#0B2B5C" letterSpacing="0.1em">GRS</text>
      <text x="42" y="35" fontFamily="var(--font-body)" fontSize="7" fill="#0B2B5C" letterSpacing="0.08em">Global Recycled</text>
    </svg>
  );
}
function SMETAMark() {
  return (
    <svg viewBox="0 0 120 48" width="110" height="44">
      <rect x="4" y="10" width="56" height="28" fill="#0B2B5C" />
      <text x="32" y="29" fontFamily="var(--font-body)" fontSize="11" fontWeight="700" fill="#FAFAF7" textAnchor="middle" letterSpacing="0.12em">SMETA</text>
      <text x="64" y="21" fontFamily="var(--font-body)" fontSize="8" fontWeight="600" fill="#0B2B5C" letterSpacing="0.06em">Sedex</text>
      <text x="64" y="33" fontFamily="var(--font-body)" fontSize="7" fill="#0B2B5C" letterSpacing="0.04em">4-pillar</text>
    </svg>
  );
}
function BSCIMark() {
  return (
    <svg viewBox="0 0 120 48" width="110" height="44">
      <circle cx="18" cy="24" r="11" fill="#A61D1D" />
      <text x="18" y="28" fontFamily="var(--font-body)" fontSize="11" fontWeight="700" fill="#FAFAF7" textAnchor="middle">a</text>
      <text x="36" y="21" fontFamily="var(--font-body)" fontSize="9" fontWeight="700" fill="#A61D1D" letterSpacing="0.04em">amfori</text>
      <text x="36" y="33" fontFamily="var(--font-body)" fontSize="9" fontWeight="700" fill="#0B2B5C" letterSpacing="0.12em">BSCI</text>
    </svg>
  );
}
function ClientMark({ label, small }) {
  const w = small ? 90 : 110; const h = small ? 34 : 44;
  return (
    <svg viewBox="0 0 120 48" width={w} height={h}>
      <rect x="4" y="10" width="112" height="28" fill="none" stroke="#1A1A1A" strokeWidth="1" />
      <text x="60" y="29" fontFamily="var(--font-display)" fontSize="14" fontWeight="500" fill="#1A1A1A" textAnchor="middle" letterSpacing="0.2em">{label}</text>
    </svg>
  );
}

// ============ BRANDS ============
function Brands() {
  const brands = [
    { name: 'Anthropologie', desc: 'American lifestyle retailer',     logo: '/assets/client-logos/anthropologie.png' },
    { name: 'Whistles',      desc: 'London contemporary womenswear',  logo: '/assets/client-logos/whistles.png' },
    { name: 'IKKS',          desc: 'Contemporary ready-to-wear',      logo: '/assets/client-logos/ikks.png' },
    { name: 'Kiabi',         desc: 'Value fashion retailer',          logo: '/assets/client-logos/kiabi.png' },
    { name: 'Oliver Bonas',  desc: 'Contemporary lifestyle retailer', logo: '/assets/client-logos/oliver-bonas.png' },
    { name: 'Mayoral',       desc: 'Spanish childrenswear',           logo: '/assets/client-logos/mayoral.png' },
    { name: 'The Warehouse', desc: 'National retail group',           logo: '/assets/client-logos/warehouse.png' },
    { name: 'Fransa',        desc: 'Danish womenswear brand',         logo: '/assets/client-logos/fransa.png' },
    { name: 'Sosandar',      desc: 'UK direct-to-consumer womenswear', logo: '/assets/client-logos/sosandar.webp' },
  ];
  return (
    <section className="mf-section">
      <div className="mf-section-head">
        <div className="mf-reveal">
          <div className="mf-eyebrow">Clients</div>
          <h2 style={{ fontSize: 'var(--fs-display-m)' }}>Working with brands that <em>lead on design.</em></h2>
        </div>
        <p className="mf-lead mf-reveal" style={{ transitionDelay: '80ms' }}>
          Premium and contemporary houses across Europe, the UK, and Asia-Pacific.
        </p>
      </div>
      <div className="mf-brands">
        {brands.map((b, i) => (
          <div key={b.name} className="mf-brand mf-reveal" style={{ transitionDelay: `${i * 40}ms` }}>
            <div className="mf-brand-logo-wrap">
              <img className="mf-brand-logo" src={b.logo} alt={b.name} loading="lazy" decoding="async" />
            </div>
            <div className="mf-brand-name">{b.name}</div>
            <div className="mf-brand-desc">{b.desc}</div>
          </div>
        ))}
      </div>
    </section>
  );
}

// ============ STORY ============
function Story() {
  return (
    <section className="mf-section" id="about">
      <div className="mf-story">
        <div className="mf-reveal">
          <div className="mf-story-img">
            <img src="/assets/images/img-19.png" alt="Market Fit Group, fifty-two years in fashion" width="1600" height="1200" loading="lazy" decoding="async" />
          </div>
        </div>
        <div className="mf-story-text mf-reveal" style={{ transitionDelay: '80ms' }}>
          <div className="mf-eyebrow">Our story</div>
          <h2>Fifty-two years of fashion, <em>in one family.</em></h2>
          <p>
            A family business, founded in Istanbul in 1974 — starting in leather and moving into textiles. We've operated continuously through five decades of fashion cycles, always returning to the same question: how do we help the brands we care about make better clothes, more efficiently, with less waste.
          </p>
          <a href="#" className="mf-btn-g">Read our story <span className="arrow"><Icon.ArrowRight size={16} /></span></a>
        </div>
      </div>
    </section>
  );
}

// ============ CONTACT ============
function Contact() {
  const [state, setState] = useState({ name: '', brand: '', email: '', msg: '' });
  const [sent, setSent] = useState(false);
  const onChange = (k) => (e) => setState({ ...state, [k]: e.target.value });
  const onSubmit = (e) => { e.preventDefault(); setSent(true); };
  return (
    <section className="mf-section warm" id="contact">
      <div className="mf-contact">
        <div className="mf-reveal">
          <div className="mf-eyebrow" style={{ textAlign: 'center' }}>Start</div>
          <h2>Let's make your <em>next collection.</em></h2>
          <p className="mf-lead" style={{ textAlign: 'center', margin: '0 auto var(--s-5)' }}>
            Tell us what you're building and we'll get back within 24 hours with a conversation about fit, capacity, and timeline.
          </p>
        </div>
        {!sent ? (
          <form className="mf-form mf-reveal" onSubmit={onSubmit} style={{ transitionDelay: '80ms' }}>
            <div className="mf-field">
              <label>Name</label>
              <input type="text" value={state.name} onChange={onChange('name')} required />
            </div>
            <div className="mf-field">
              <label>Brand</label>
              <input type="text" value={state.brand} onChange={onChange('brand')} required />
            </div>
            <div className="mf-field full">
              <label>Email</label>
              <input type="email" value={state.email} onChange={onChange('email')} required />
            </div>
            <div className="mf-field full">
              <label>What are you working on?</label>
              <textarea rows="3" value={state.msg} onChange={onChange('msg')} />
            </div>
            <div className="mf-form-submit">
              <button type="submit" className="mf-btn-p">Send <Icon.ArrowRight /></button>
            </div>
          </form>
        ) : (
          <div className="mf-reveal in" style={{ padding: 'var(--s-8) 0', fontFamily: 'var(--font-display)', fontSize: 28, letterSpacing: '-0.01em', color: 'var(--mf-ink)' }}>
            Thanks. We'll be in touch within 24 hours.
          </div>
        )}
        <div className="mf-contact-info mf-reveal">
          <div className="mf-contact-block">
            <div className="mf-eyebrow">HQ — Hong Kong</div>
            Unit 2102, 21/F., Golden Centre<br />188 Des Voeux Road Central
          </div>
          <div className="mf-contact-block">
            <div className="mf-eyebrow">General inquiry</div>
            <a href="mailto:jordan@market-fit.com">jordan@market-fit.com</a>
          </div>
          <div className="mf-contact-block">
            <div className="mf-eyebrow">China office</div>
            <a href="mailto:tony@market-fit.com">tony@market-fit.com</a>
          </div>
          <div className="mf-contact-block">
            <div className="mf-eyebrow">Careers</div>
            <a href="mailto:CVApply@market-fit.com">CVApply@market-fit.com</a>
          </div>
        </div>
      </div>
    </section>
  );
}

// ============ BREADCRUMBS ============
// Trail: array of { label, href? }. Last item is the current page (no href).
function Breadcrumbs({ trail }) {
  if (!trail || trail.length === 0) return null;
  return (
    <nav className="mf-crumbs" aria-label="Breadcrumb">
      <ol className="mf-crumbs-list">
        {trail.map((item, i) => {
          const isLast = i === trail.length - 1;
          return (
            <li key={i} className="mf-crumb">
              {item.href && !isLast ? (
                <a href={item.href} className="mf-crumb-link">{item.label}</a>
              ) : (
                <span className="mf-crumb-current" aria-current={isLast ? 'page' : undefined}>{item.label}</span>
              )}
              {!isLast ? <span className="mf-crumb-sep" aria-hidden="true"><Icon.ChevronRight /></span> : null}
            </li>
          );
        })}
      </ol>
    </nav>
  );
}

// ============ FAQ ACCORDION ============
// items: [{ q, a }]. eyebrow + heading optional.
function Faq({ items, eyebrow, heading, headingEm }) {
  const [openIx, setOpenIx] = useState(-1);
  if (!items || items.length === 0) return null;
  return (
    <section className="mf-faq" id="faq">
      <div className="mf-faq-inner">
        <div className="mf-faq-head mf-reveal">
          {eyebrow ? <div className="mf-eyebrow">{eyebrow}</div> : null}
          <h2 className="mf-faq-h">
            {heading || 'Frequently asked'} {headingEm ? <em>{headingEm}</em> : null}
          </h2>
        </div>
        <ul className="mf-faq-list">
          {items.map((it, i) => {
            const open = openIx === i;
            return (
              <li key={i} className={`mf-faq-item mf-reveal ${open ? 'open' : ''}`} style={{ transitionDelay: `${i * 30}ms` }}>
                <button
                  type="button"
                  className="mf-faq-q"
                  aria-expanded={open}
                  onClick={() => setOpenIx(open ? -1 : i)}
                >
                  <span className="mf-faq-q-text">{it.q}</span>
                  <span className="mf-faq-q-icon" aria-hidden="true"><Icon.Plus /></span>
                </button>
                <div className="mf-faq-a-wrap" role="region">
                  <div className="mf-faq-a-inner">
                    <div className="mf-faq-a">{it.a}</div>
                  </div>
                </div>
              </li>
            );
          })}
        </ul>
      </div>
    </section>
  );
}

// ============ LINK TARGETS REGISTRY ============
// Single source of truth for canonical internal links + Related card metadata.
const LINK_TARGETS = {
  // Solutions
  'sol-odm':        { href: '/solutions/odm',        eyebrow: 'SOLUTION', title: 'ODM & Development',       desc: 'Sketch to production-ready garment, in-house.', img: '/assets/images/img-06.png' },
  'sol-sampling':   { href: '/solutions/sampling',   eyebrow: 'SOLUTION', title: 'Sampling in 7 days',      desc: '500 styles a month from our owned sample room.', img: '/assets/images/img-24.jpg' },
  'sol-fabric':     { href: '/solutions/fabric',     eyebrow: 'SOLUTION', title: 'Fabric & trim sourcing',  desc: 'Owned warehouse in Shaoxing, 8,000+ active fabrics.', img: '/assets/images/img-17.png' },
  'sol-production': { href: '/solutions/production', eyebrow: 'SOLUTION', title: 'Small-batch production',  desc: '500-piece MOQ. Audited factories. Same quality bar.', img: '/assets/images/img-21.png' },
  'sol-quality':    { href: '/solutions/quality',    eyebrow: 'SOLUTION', title: 'Quality & compliance',    desc: 'GRS, SMETA, BSCI across the network.', img: '/assets/images/img-04.png' },
  'sol-hub':        { href: '/solutions',            eyebrow: 'SOLUTIONS', title: 'All five solutions',     desc: 'How development, sampling, sourcing, production and quality fit together.', img: '/assets/images/img-25.jpg' },
  // Network parent + countries
  'net-hub':        { href: '/our-network',          eyebrow: 'NETWORK',  title: 'The full network',        desc: 'Thirteen offices and factories across seven countries.', img: '/assets/photography/cad-digital-cutter.jpg' },
  'net-china':      { href: '/our-network/china',        eyebrow: 'CHINA',    title: 'China operations',        desc: 'Shanghai sourcing office plus five specialist factories.', img: '/assets/network/china-hero.jpg' },
  'net-vietnam':    { href: '/our-network/vietnam',      eyebrow: 'VIETNAM',  title: 'Vietnam',                  desc: 'Owned floor in Tien Giang, design office in Ho Chi Minh City. Trend-led womenswear.', img: '/assets/network/vietnam-hero.jpg' },
  'net-bangladesh': { href: '/our-network/bangladesh',   eyebrow: 'BANGLADESH', title: 'Bangladesh',             desc: 'Buying agent for Europe since 2002. In-house lab.', img: '/assets/network/bangladesh-hero.jpg' },
  'net-pakistan':   { href: '/our-network/pakistan',     eyebrow: 'PAKISTAN', title: 'Pakistan',                 desc: 'Woven garments and sporting goods, deep cotton.', img: '/assets/network/pakistan-hero.jpg' },
  'net-turkey':     { href: '/our-network/turkey',       eyebrow: 'TURKEY',   title: 'Turkey',                   desc: 'The original office. The model for everything since.', img: '/assets/network/turkey-hero.jpg' },
  'net-india':      { href: '/our-network/india',        eyebrow: 'INDIA',    title: 'India',                    desc: 'Gurgaon sourcing and design — woven, embellishment, leather.', img: '/assets/network/india-hero.jpg' },
  'net-hongkong':   { href: '/our-network/hong-kong',    eyebrow: 'HONG KONG', title: 'Hong Kong',               desc: 'The headquarters since 2009.', img: '/assets/network/hongkong-hero.jpg' },
  // Factories (China)
  'fac-mf-suzhou':  { href: '/our-network/china/market-fit-suzhou',    eyebrow: 'FACTORY',  title: 'Market Fit Suzhou',        desc: 'Our owned facility for compliance-heavy programmes.', img: '/assets/photography/cad-room-mannequin.jpg' },
  'fac-tongxiang':  { href: '/our-network/china/tongxiang-yinshi',     eyebrow: 'FACTORY',  title: 'Tongxiang Yinshi',         desc: 'Dresses, blouses, tops. Light-woven specialist.', img: '/assets/photography/hand-finishing-green-blouse.jpg' },
  'fac-mupai':      { href: '/our-network/china/suzhou-mupai',         eyebrow: 'FACTORY',  title: 'Suzhou Mupai',             desc: 'Outerwear specialist. Padded and tailored coats.', img: '/assets/photography/sewing-room-wide.jpg' },
  'fac-suho':       { href: '/our-network/china/suho-fashion-nanjing', eyebrow: 'FACTORY',  title: 'Suho Fashion Nanjing',     desc: 'Suits, coats, shirts, workwear, casual.', img: '/assets/photography/seamstress-jack-machine.jpg' },
  'fac-sainty':     { href: '/our-network/china/suho-fashion-nanjing', eyebrow: 'FACTORY',  title: 'Suho Fashion Nanjing',     desc: 'Suits, coats, shirts, workwear, casual.', img: '/assets/photography/seamstress-jack-machine.jpg' },
  'fac-hubei':      { href: '/our-network/china/hubei',                eyebrow: 'FACTORY',  title: 'Hubei facility',           desc: 'Light-woven capacity for higher-volume programmes.', img: '/assets/photography/cad-digital-cutter.jpg' },
  'fac-mf-vietnam': { href: '/our-network/vietnam/market-fit-vietnam', eyebrow: 'FACTORY',  title: 'Market Fit Vietnam',       desc: 'Wholly-owned floor in Tien Giang. Premium handling for knit and woven womenswear.', img: '/assets/photography/sewing-room-wide.jpg' },
  // Editorial pages
  'about':          { href: '/about',                eyebrow: 'ABOUT',    title: 'Fifty-two years of fashion', desc: 'A family business since 1974.', img: '/assets/images/img-05.png' },
  'sustain':        { href: '/sustainability',       eyebrow: 'SUSTAINABILITY', title: 'Compliance is non-negotiable', desc: 'Our certifications, materials, and DPP roadmap.', img: '/assets/images/img-09.png' },
  'contact':        { href: '/contact',              eyebrow: 'CONTACT',  title: 'Start a conversation',     desc: 'Tell us what you\'re building.', img: '/assets/photography/cad-digital-cutter.jpg' },
  'insights':       { href: '/insights',             eyebrow: 'INSIGHTS', title: 'Sourcing strategy, written down', desc: 'Country guides and operational realities.', img: '/assets/photography/warehouse-boxes.jpg' },
};

function relatedFor(keys) {
  return keys.map((k) => {
    const t = LINK_TARGETS[k];
    if (!t) return null;
    return { href: t.href, eyebrow: t.eyebrow, title: t.title, desc: t.desc, img: t.img };
  }).filter(Boolean);
}

// ============ RELATED CONTENT (image card variant) ============
// items: [{ href, eyebrow, title, desc, img }]
function RelatedContent({ heading = 'Connected to this work', items }) {
  if (!items || items.length === 0) return null;
  return (
    <section className="mf-rc">
      <div className="mf-rc-inner">
        <div className="mf-eyebrow mf-reveal">Related</div>
        <h2 className="mf-rc-h mf-reveal" style={{ transitionDelay: '60ms' }}>{heading}</h2>
        <ul className="mf-rc-grid">
          {items.map((it, i) => (
            <li key={i} className="mf-reveal" style={{ transitionDelay: `${80 + i * 60}ms` }}>
              <a href={it.href} className="mf-rc-card">
                {it.img ? (
                  <span className="mf-rc-img">
                    <img src={it.img} alt="" width="600" height="400" loading="lazy" decoding="async" />
                  </span>
                ) : null}
                <span className="mf-rc-body">
                  {it.eyebrow ? <span className="mf-rc-eye">{it.eyebrow}</span> : null}
                  <span className="mf-rc-title">{it.title}</span>
                  {it.desc ? <span className="mf-rc-desc">{it.desc}</span> : null}
                  <span className="mf-rc-arrow" aria-hidden="true"><Icon.ArrowRight size={14} /></span>
                </span>
              </a>
            </li>
          ))}
        </ul>
      </div>
    </section>
  );
}

// ============ RELATED LINKS (legacy, text-only) ============
// Contextual link block. items: [{ href, label, eyebrow }]
function RelatedLinks({ heading, items }) {
  if (!items || items.length === 0) return null;
  return (
    <section className="mf-related">
      <div className="mf-related-inner">
        {heading ? <div className="mf-eyebrow mf-reveal">{heading}</div> : null}
        <ul className="mf-related-list">
          {items.map((it, i) => (
            <li key={i} className="mf-reveal" style={{ transitionDelay: `${i * 40}ms` }}>
              <a href={it.href} className="mf-related-card">
                {it.eyebrow ? <span className="mf-related-eye">{it.eyebrow}</span> : null}
                <span className="mf-related-label">{it.label}</span>
                <span className="mf-related-arrow" aria-hidden="true"><Icon.ArrowRight size={16} /></span>
              </a>
            </li>
          ))}
        </ul>
      </div>
    </section>
  );
}

// ============ FOOTER ============
function Footer() {
  return (
    <footer className="mf-footer">
      <div className="mf-footer-inner">
        <div className="mf-footer-grid">
          <div>
            <Lockup href="/" reverse className="mf-footer-lockup" />
            <div className="mf-footer-tag">The ODM partner for contemporary fashion. Small batches. No compromise.</div>
          </div>
          <div className="mf-footer-col">
            <h6>Company</h6>
            <ul>
              <li><a href="/about">About</a></li>
              <li><a href="/careers">Careers</a></li>
              <li><a href="/insights">Insights</a></li>
              <li><a href="/sustainability">Sustainability</a></li>
              <li><a href="/contact">Contact</a></li>
            </ul>
          </div>
          <div className="mf-footer-col">
            <h6>Solutions</h6>
            <ul>
              <li><a href="/solutions/odm">ODM & development</a></li>
              <li><a href="/solutions/sampling">Sampling</a></li>
              <li><a href="/solutions/fabric">Fabric sourcing</a></li>
              <li><a href="/solutions/production">Small-batch production</a></li>
              <li><a href="/solutions/quality">Quality & compliance</a></li>
            </ul>
          </div>
          <div className="mf-footer-col">
            <h6>Network</h6>
            <ul>
              <li><a href="/our-network">All countries</a></li>
              <li><a href="/our-network/china">China</a></li>
              <li><a href="/our-network/turkey">Turkey</a></li>
              <li><a href="/our-network/vietnam">Vietnam</a></li>
              <li><a href="/our-network/india">India</a></li>
              <li><a href="/our-network/hong-kong">Hong Kong (HQ)</a></li>
            </ul>
          </div>
          <div className="mf-footer-col">
            <h6>Contact</h6>
            <ul>
              <li>Unit 2102, 21/F., Golden Centre<br />188 Des Voeux Road Central<br />Hong Kong</li>
              <li><a href="mailto:jordan@market-fit.com">jordan@market-fit.com</a></li>
              <li><a href="mailto:CVApply@market-fit.com">CVApply@market-fit.com</a></li>
              <li style={{ marginTop: 16 }}><a href="#" style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}><Icon.Linkedin size={16} /> LinkedIn</a></li>
            </ul>
          </div>
        </div>
        <div className="mf-footer-bottom">
          <div>© 1974–2026 Market Fit Group Ltd.</div>
          <div style={{ display: 'flex', gap: 18, opacity: 0.6 }}>
            <span style={{ fontFamily: 'var(--font-body)', fontSize: 11, letterSpacing: '0.12em', textTransform: 'uppercase' }}>GRS 4.0</span>
            <span style={{ fontFamily: 'var(--font-body)', fontSize: 11, letterSpacing: '0.12em', textTransform: 'uppercase' }}>SMETA</span>
            <span style={{ fontFamily: 'var(--font-body)', fontSize: 11, letterSpacing: '0.12em', textTransform: 'uppercase' }}>amfori BSCI</span>
          </div>
          <div className="mf-footer-legal">
            <a href="#">Privacy</a>
            <a href="#">Terms</a>
            <span className="mf-footer-lang" data-mf-lang-switch="footer" style={{ marginLeft: 18 }}></span>
          </div>
        </div>
      </div>
    </footer>
  );
}

// ============ APP ============
function App() {
  const ref = useReveal();
  return (
    <div ref={ref}>
      <Nav />
      <Hero />
      <Credentials />
      <Brands />
      <Programmes />
      <Solutions />
      <Network />
      <Compliance />
      <Story />
      <Contact />
      <Footer />
    </div>
  );
}

Object.assign(window, { App, Nav, Footer, Breadcrumbs, Faq, RelatedLinks, Icon });
