/* global React */
const { useState, useEffect } = React;
const { Icon, Imgph } = window.LYTLE_UI;

/* ============= Service data ============= */
const SERVICES = [
  {
    id: 'embroidery',
    name: 'Embroidery',
    blurb: 'Durable stitched designs for premium apparel & custom patches — made in-house.',
    photo: 'EMBROIDERY MACHINE / CLOSE-UP',
    img: 'assets/svc-embroidery.jpg',
    features: [
      { icon: 'Star',   title: 'Premium Look',          body: 'Crisp stitched detail with a tactile, upscale finish.' },
      { icon: 'Spool',  title: 'High Quality Thread',   body: 'Top-quality thread creates crisp stitching, vibrant color, and lasting impact.' },
      { icon: 'Shield', title: 'Long Lasting',          body: 'Made to hold up wash after wash.' },
      { icon: 'Clock',  title: 'In-House Capability',   body: 'Produced in-house for faster turnaround times.' },
    ],
    extras: 'embroidery',
    bestFor: [
      { name: 'Hats', img: 'assets/best-emb-hat.jpg' },
      { name: 'Polos', img: 'assets/best-emb-polo.jpg' },
      { name: 'Jackets', img: 'assets/best-emb-jacket.jpg' },
      { name: 'Custom Patches', img: 'assets/best-emb-patch.jpg' },
      { name: 'Uniforms', img: 'assets/bestfor-embroidery-uniforms.jpg' },
    ],
  },
  {
    id: 'screen',
    name: 'Screen Printing',
    blurb: 'Bold, vibrant color with lasting quality — ideal for larger runs and team orders.',
    photo: 'SCREEN PRINTING PRESS',
    img: 'assets/svc-screen.jpg',
    features: [
      { img: 'assets/sp-bright.png',  title: 'Bright, Solid Colors',     body: 'Vibrant color that looks sharp and clear.' },
      { img: 'assets/sp-durable.png', title: 'Extremely Durable',       body: "Prints that won't crack, fade, or peel." },
      { img: 'assets/sp-bulk.png',    title: 'Cost-Effective At Scale',  body: 'Good for larger quantities with consistent results.' },
    ],
    extras: 'screen',
    bestFor: [
      { name: 'T-Shirts', img: 'assets/best-sp-tshirt.jpg' },
      { name: 'Hoodies', img: 'assets/bestfor-screen-hoodie.jpg' },
      { name: 'Team Apparel', img: 'assets/best-sp-jersey.jpg' },
      { name: 'Bulk Orders', img: 'assets/bestfor-screen-bulk.jpg' },
    ],
  },
  {
    id: 'dtf',
    name: 'DTF Printing',
    blurb: 'Full-color, photo-quality prints on any fabric, ideal for complex designs.',
    photo: 'DTF PRINTER / FILM TRANSFER',
    img: 'assets/svc-dtf.jpg',
    features: [
      { icon: 'Palette', title: 'Full Color Freedom',   body: 'No color limitations — gradients, photos, and complex artwork.' },
      { icon: 'Photo',   title: 'High Detail Printing', body: 'Great for detailed or photo-quality designs.' },
      { icon: 'Clock',   title: 'Fast Production Time', body: 'Perfect for tight deadlines.' },
      { icon: 'Layers',  title: 'Any Fabric',           body: 'Cotton, polyester blends — DTF prints on all of it.' },
    ],
    extras: 'dtf',
    bestFor: [
      { name: 'Custom Runs',   img: 'assets/dtf-2.jpg' },
      { name: 'Multi-Color Art', img: 'assets/dtf-best-multicolor.png' },
      { name: 'Photo Designs', img: 'assets/dtf-best-photo.png' },
    ],
  },
  {
    id: 'laser',
    name: 'Laser Engraving',
    blurb: 'Precision-etched detail on leather, wood, metal, and virtually any surface.',
    img: 'assets/laser-1.jpg',
    features: [
      { icon: 'Sparkle', title: 'Sharp, Clean Detail',    body: "Precise etching that won't fade, peel, or wear off." },
      { icon: 'Tools',   title: 'Works on Most Surfaces',  body: 'Leather, wood, acrylic, metal-coated items, and more.' },
      { icon: 'Star',    title: 'Custom Branding Pieces', body: 'From hat patches to drinkware — branded pieces of all kinds.' },
      { icon: 'Shield',  title: 'Done In-House',          body: 'Engraved under our own roof for fast turnaround and quality control.' },
    ],
    extras: 'laser',
    bestFor: [
      { name: 'Hat Patches',    img: 'assets/laser-patch-hat.png' },
      { name: 'Drinkware',      img: 'assets/laser-tumbler.png' },
      { name: 'Awards & Signage', img: 'assets/laser-wood-plaque.png' },
      { name: 'Bag Accents',    img: 'assets/laser-bag-tag.png' },
    ],
  },
];

/* ============= Display product data ============= */
const DISPLAY_PRODUCTS = [
  {
    id: 'canopy',
    name: 'Canopy Kits',
    tagline: <>Custom canopies in durable materials and a range of sizes — perfect for trade shows, pop-ups, and outdoor events.</>,
    photos: ['assets/canopy-1-scene.png', 'assets/canopy-2-scene.png', 'assets/canopy-3-scene.png'],
    images: [],
    specs: [['Sizes', "5'×5' / 6.5'×6.5' / 10'×10' / 10'×15' / 10'×20'"], ['Material', '600 Denier Polyester']],
    bullets: [
      ['Built to weather it', 'Durable 600D polyester handles weather and repeated use'],
      ['Easy setup', 'Ready for events of any size'],
      ['Pro frame', 'Designed for long-term reliability'],
    ],
  },
  {
    id: 'hstake',
    name: 'H-Stakes',
    tagline: <>Yard-ready Coroplast signs with H-stakes included — perfect for events, open houses, and local advertising.</>,
    photos: ['assets/h-stake-1.png', 'assets/h-stake-2.png', 'assets/h-stake-3.png'],
    images: [],
    specs: [['Sizes', '12"×18" / 18"×24"'], ['Material', '4mm Coroplast']],
    bullets: [
      ['Easy to plant', 'H-stake pushes right into the ground'],
      ['Single or double-sided', 'Visibility from one or both directions'],
      ['Weather-resistant', 'Holds up to outdoor conditions'],
      ['Reusable', 'Pull up, store flat, redeploy later'],
    ],
  },
  {
    id: 'feather',
    name: 'Feather Banners',
    tagline: <>Eye-catching, wind-resistant outdoor banners. One of our most popular event display solutions.</>,
    photos: ['assets/feather-1-scene.png', 'assets/feather-2-scene.png', 'assets/feather-3-scene.png'],
    images: [],
    specs: [['Sizes', "8' / 10' / 12' / 15' / 20'"], ['Options', 'Single-Sided · Double-Sided']],
    bullets: [
      ['Highly visible', 'Hard to miss in any crowd'],
      ['Wind-resistant', 'Holds its shape in outdoor conditions'],
      ['Double-sided', 'Maximizes visibility from all angles'],
      ['Easy to reuse', 'Simple to assemble and transport'],
    ],
  },
  {
    id: 'banner',
    name: 'Banner Stands',
    tagline: <>Sharp print quality with an effortless interlocking frame. Ready to display in minutes — indoors or out.</>,
    photos: ['assets/banner-1-scene.png', 'assets/banner-2-scene.png', 'assets/banner-3-scene.png'],
    images: [],
    specs: [['Sizes', '24"×90" / 36"×90" / 48"×90" / 60"×90"'], ['Options', 'Single-Sided · Double-Sided']],
    bullets: [
      ['Clean, structured look', 'Works in any professional setting'],
      ['Quick changes', 'Pillow-case style graphic slides on and off'],
      ['Multiple widths', 'Fit any booth or space'],
      ['Lightweight', 'Easy to carry between events'],
    ],
  },
  {
    id: 'tube',
    name: 'Premier Tube Displays',
    tagline: <>Sleek and highly visible. Perfect for events where height and visibility matter most.</>,
    photos: ['assets/tube-scene-1.png', 'assets/tube-scene-2.png', 'assets/tube-scene-3.png'],
    images: [],
    specs: [['Sizes', "8' / 10' / 20' / 30'"], ['Material', '4-Way Stretch Polyester']],
    bullets: [
      ['Wrinkle-free finish', 'Stretch polyester stays smooth event after event'],
      ['Tool-free assembly', 'Set up fast for events of any size'],
      ['Up to 30\' tall', 'Maximum vertical impact'],
    ],
  },
  {
    id: 'table',
    name: 'Fitted Table Covers',
    tagline: <>Full-color, dye-sublimated table covers printed on durable 600 denier polyester.</>,
    photos: ['assets/table-1-scene.png', 'assets/table-3-scene.png', 'assets/table-2-scene.png'],
    images: [],
    specs: [['Sizes', "4' / 6' / 8'"], ['Material', '600 Denier Polyester']],
    bullets: [
      ['Edge-to-edge color', 'Maximum brand presence on every side'],
      ['Built to last', 'Holds up through repeated use and washing'],
      ['Stays put', 'Fitted design — no bunching or shifting'],
      ['Indoor + outdoor', 'Works wherever you set up'],
    ],
  },
  {
    id: 'aframe',
    name: 'Coroplast A-Frames',
    tagline: <>Lightweight, portable, and weather-resistant signage perfect for sidelines, storefronts, and events.</>,
    photos: ['assets/aframe-1-scene.png', 'assets/aframe-2-scene.png', 'assets/aframe-3-scene.png'],
    images: [],
    specs: [['Sizes', '23.5"×16" / 47"×16" / 47"×31"'], ['Material', '4mm Coroplast']],
    bullets: [
      ['Lightweight', 'Easy to transport to any location'],
      ['Weather-resistant', 'Built for outdoor conditions'],
      ['No assembly', 'Open and place — that\'s it'],
      ['Cost-effective', 'High-impact signage on a budget'],
    ],
  },
  {
    id: 'popout',
    name: 'Pop-Out Banners',
    tagline: <>Customized portable fabric displays in SM, MED, and LG — built for outdoor brand activations.</>,
    photos: ['assets/popout-1-scene.png', 'assets/tube-2-scene.png', 'assets/tube-1-scene.png'],
    images: [],
    specs: [['Sizes', 'SM / MED / LG'], ['Material', 'Heavy Duty Polyester']],
    bullets: [
      ['Lightweight', 'Easy to pack, transport, and reuse'],
      ['Heavy-duty', 'Built for outdoor conditions'],
      ['Fully customizable', 'Your branding, your colors'],
      ['Three sizes', 'Fit any event footprint'],
    ],
  },
];

/* ============= Mobile detection hook ============= */
function useIsMobile(breakpoint = 880) {
  const [mobile, setMobile] = useState(() => window.matchMedia(`(max-width: ${breakpoint}px)`).matches);
  useEffect(() => {
    const mq = window.matchMedia(`(max-width: ${breakpoint}px)`);
    const handler = (e) => setMobile(e.matches);
    mq.addEventListener('change', handler);
    return () => mq.removeEventListener('change', handler);
  }, [breakpoint]);
  return mobile;
}

/* ============= Compact feature list (mobile) ============= */
function FeatureListMobile({ features }) {
  const [expanded, setExpanded] = useState(null);
  const toggle = (i) => setExpanded(prev => prev === i ? null : i);

  return (
    <div className="feature-list-mobile">
      {features.map((f, i) => {
        const Ic = f.icon ? Icon[f.icon] : null;
        const isOpen = expanded === i;
        return (
          <div key={i} className={'feature-row-wrap' + (isOpen ? ' open' : '')}>
            <button className="feature-row" onClick={() => toggle(i)}>
              <div className="feature-row-icon">
                {f.img
                  ? <img src={f.img} alt="" style={{ width:'100%', height:'100%', objectFit:'contain' }}/>
                  : Ic ? <Ic/> : null
                }
              </div>
              <span className="feature-row-title">{f.title}</span>
              <Icon.Chev className="feature-row-chev" style={{ transform: isOpen ? 'rotate(90deg)' : 'none' }}/>
            </button>
            {isOpen && (
              <div className="feature-row-detail">
                <p>{f.body}</p>
              </div>
            )}
          </div>
        );
      })}
    </div>
  );
}

/* ============= Core Services Section ============= */
function CoreServices({ onQuote, onJump, resetKey }) {
  const [active, setActive] = useState(null);
  const [fading, setFading] = useState(false);
  const isMobile = useIsMobile();

  useEffect(() => { if (resetKey > 0) setActive(null); }, [resetKey]);
  const svc = active ? SERVICES.find(s => s.id === active) : null;

  const onCardClick = (id) => {
    if (active !== null && active !== id) {
      // Switching between services in compact mode — no fade, just swap
      setActive(id);
    } else {
      // Opening from primary or closing back to primary — fade the transition
      const next = active === id ? null : id;
      setFading(true);
      setTimeout(() => {
        // Read layout values before state change triggers collapse animation
        const el = document.getElementById('svc-cards');
        const header = document.querySelector('.site-header');
        const sectionHead = document.querySelector('#services .section');
        const headerH = header ? header.offsetHeight : 84;
        const headingH = sectionHead ? sectionHead.offsetHeight : 0;

        setActive(next);
        setFading(false);

        // Scroll to the compact strip's final position (accounting for heading collapse)
        if (next && el) {
          const top = el.getBoundingClientRect().top + window.scrollY - headerH - headingH + 64;
          window.scrollTo({ top, behavior: 'smooth' });
        }
      }, 200);
    }
  };

  return (
    <section id="services">
      {/* Section heading — always in DOM; folds away smoothly when compact */}
      <div className="section" style={{
        overflow: 'hidden',
        maxHeight: active ? 0 : '300px',
        opacity: active ? 0 : 1,
        paddingTop: 48,
        paddingBottom: active ? 0 : 48,
        transition: 'max-height 0.4s ease, opacity 0.25s ease, padding-bottom 0.35s ease',
      }}>
        <div className="wrap">
          <div className="section-head reveal" style={{ marginBottom: 0 }}>
            <span className="eyebrow">What We Do</span>
            <h2>Our Core Services</h2>
          </div>
        </div>
      </div>

      {/* Card grid / tab strip — fades during content swap */}
      <div id="svc-cards" style={{
        ...(active ? {
          background: '#fff',
          borderBottom: '1px solid var(--line)',
        } : { padding: '0 0 48px' }),
        opacity: fading ? 0 : 1,
        transition: 'opacity 0.2s ease',
      }}>
        <div className="wrap">
          {active ? (
            <div>
              <div style={{ padding: '20px 0 4px', textAlign: 'center' }}>
                <span className="eyebrow" style={{ margin: 0 }}>Core Services</span>
              </div>
              <div className="svc-tabs" style={{ display: 'flex', flexWrap: 'wrap' }}>
              {SERVICES.map(s => (
                <button key={s.id}
                        onClick={() => onCardClick(s.id)}
                        className="svc-tab"
                        style={{
                          flex: '1 1 auto',
                          padding: '18px 12px',
                          background: 'none',
                          border: 'none',
                          borderBottom: active === s.id ? '3px solid var(--red)' : '3px solid transparent',
                          cursor: 'pointer',
                          fontFamily: 'var(--display)',
                          fontWeight: 700,
                          fontSize: 13,
                          letterSpacing: '.08em',
                          textTransform: 'uppercase',
                          color: active === s.id ? 'var(--ink)' : 'var(--muted)',
                          transition: 'color .15s, border-color .15s',
                        }}>
                  {s.name}
                </button>
              ))}
              </div>
            </div>
          ) : (
            <div className="svc-grid">
              {SERVICES.map(s => (
                <button key={s.id}
                        className="svc-card"
                        onClick={() => onCardClick(s.id)}>
                  <div className="img" style={s.img ? { backgroundImage: `url(${s.img})` } : { background: 'repeating-linear-gradient(135deg, #2a2d33 0 12px, #22262b 12px 24px)' }}/>
                  <div className="body">
                    <h3>{s.name.toUpperCase()}</h3>
                    <p>{s.blurb}</p>
                    <span className="link-arrow">Learn More <Icon.Arrow/></span>
                  </div>
                </button>
              ))}
            </div>
          )}
        </div>
      </div>

      {/* Expanded detail panel — only when a card is active */}
      {svc && (
      <div className="svc-detail reveal in" id="svc-detail" key={svc.id}>
        <div className="wrap">
          <h3 style={{
            fontFamily: 'var(--display)',
            fontWeight: 700,
            fontSize: 'clamp(22px, 3vw, 32px)',
            letterSpacing: '.06em',
            textTransform: 'uppercase',
            textAlign: 'center',
            margin: '0 0 12px',
          }}>{svc.name}</h3>
          <p className="lead" style={{ textAlign: 'center', marginBottom: 40 }}>{svc.blurb}</p>

          {isMobile ? (
            <FeatureListMobile features={svc.features}/>
          ) : (
            <div className="svc-features" style={{ gridTemplateColumns: `repeat(${svc.features.length}, 1fr)` }}>
              {svc.features.map((f, i) => {
                const Ic = f.icon ? Icon[f.icon] : null;
                return (
                  <div className="feature" key={i}>
                    <div className="icon">{f.img ? <img src={f.img} alt="" style={{ width:'100%', height:'100%', objectFit:'contain' }}/> : <Ic/>}</div>
                    <h4>{f.title}</h4>
                    <p>{f.body}</p>
                  </div>
                );
              })}
            </div>
          )}

          {svc.extras === 'embroidery' && <EmbroideryExtras/>}
          {(svc.extras === 'screen' || svc.extras === 'dtf') && <ScreenTags/>}
          {svc.extras === 'laser' && <LaserExtras/>}
        </div>

        <div className="wrap bestfor">
          <span className="eyebrow">Best For</span>
          <div className="bestfor-scroll">
            <div className="bestfor-track">
              {svc.bestFor.map((b, i) => (
                <div className="bestfor-card" key={i}>
                  {b.img ? (
                    <div className="bf-img" style={{ backgroundImage:`url(${b.img})` }}/>
                  ) : (
                    <Imgph label={b.name.toUpperCase()} style={{ height:'100%' }}/>
                  )}
                  <div className="name">{b.name}</div>
                </div>
              ))}
            </div>
          </div>
        </div>

        {TICKER_GARMENTS[svc.extras] && <ProductTicker garments={TICKER_GARMENTS[svc.extras]}/>}
        {svc.extras === 'screen' && <TeamStoreStrip onJump={onJump}/>}

        <div className="svc-footer-cta">
          <button className="btn" onClick={onQuote}>Get a Quote</button>
        </div>
      </div>
      )}
    </section>
  );
}

function ScreenTags() {
  return (
    <div style={{ marginTop: 48, borderTop: '1px solid var(--line)', paddingTop: 36 }}>
      <p className="lead" style={{ textAlign: 'center', margin: '0 auto' }}>
        We print on 20+ garment types — t-shirts, hoodies, jerseys, uniforms, and more — across a wide range of fabrics including cotton, fleece, polyester, and recycled blends.
      </p>
    </div>
  );
}

function LaserExtras() {
  return (
    <div style={{ marginTop: 48, borderTop: '1px solid var(--line)', paddingTop: 36 }}>
      <p className="lead" style={{ textAlign: 'center', margin: '0 auto' }}>
        We engrave on leather, wood, acrylic, and metal-coated surfaces — from custom hat patches and bag accents to tumblers, mugs, awards, and signage. All done in-house for fast turnaround.
      </p>
    </div>
  );
}

const TICKER_GARMENTS = {
  embroidery: 'T-SHIRTS · POLOS · BUTTON-DOWNS · OXFORD SHIRTS · WORK SHIRTS · DRESS SHIRTS · JACKETS · FLEECE JACKETS · WINDBREAKERS · VESTS · HOODIES · SWEATSHIRTS · CREWNECKS · HATS · BEANIES · VISORS · BUCKET HATS · CUSTOM PATCHES · UNIFORMS · SCRUBS · APRONS · CHEF COATS · LAB COATS · SHOP COATS · SAFETY VESTS · TEAM JERSEYS · WARM-UP GEAR · BACKPACKS · TOTE BAGS · DUFFEL BAGS · GOLF BAGS · BLANKETS · TOWELS · ROBES · BIBS · BABY ONESIES · PET BANDANAS · LAPTOP SLEEVES · TABLE LINENS · ATHLETIC BAGS · ',
  screen: 'T-SHIRTS · HOODIES · TOTE BAGS · POLOS · BACKPACKS · JERSEYS · SWEATSHIRTS · CREWNECKS · BANDANAS · LONG SLEEVES · TEAM SHIRTS · APRONS · SHORTS · DRAWSTRING BAGS · STAFF SHIRTS · KIDS SHIRTS · TANK TOPS · SPIRIT WEAR · WORK SHIRTS · CROP TOPS · EVENT SHIRTS · YOUTH SHIRTS · SWEATPANTS · WARM-UP SHIRTS · CANVAS BAGS · BLANKETS · ONESIES · UNIFORMS · TABLE COVERS · BANNERS · PILLOW COVERS · RALLY TOWELS · SHOP RAGS · FABRIC SIGNS · FLAGS · ',
  dtf: 'T-SHIRTS · HATS · ATHLETIC WEAR · HOODIES · TOTE BAGS · PERFORMANCE SHIRTS · POLOS · BACKPACKS · BEANIES · LONG SLEEVES · TEAM SHIRTS · SPIRIT WEAR · APRONS · BANDANAS · STAFF SHIRTS · POCKET PRINTS · CREWNECKS · DRAWSTRING BAGS · KIDS SHIRTS · TANK TOPS · CUSTOM PATCH-STYLE PRINTS · SHORTS · WORK SHIRTS · YOUTH SHIRTS · CROP TOPS · ONESIES · SWEATPANTS · BAG PRINTS · CANVAS BAGS · FULL-COLOR LOGOS · UNIFORMS · EVENT SHIRTS · PERSONALIZED SHIRTS · SLEEVES · SWEATSHIRTS · SMALL RUN APPAREL · PROMO APPAREL · JERSEYS · ',
  laser: 'TUMBLERS · LEATHER PATCHES · WATER BOTTLES · KEYCHAINS · COFFEE MUGS · WOOD SIGNS · WOOD PLAQUES · COASTERS · TRAVEL CUPS · PHONE STANDS · GLASS AWARDS · CUTTING BOARDS · METAL AWARDS · NOTEBOOKS · GLASSWARE · PET TAGS · ACRYLIC AWARDS · CHARCUTERIE BOARDS · BADGES · WALLETS · WINE GLASSES · PHOTO FRAMES · NAMEPLATES · KNIVES · DESK SIGNS · BOTTLE OPENERS · USB DRIVES · JOURNALS · DOOR SIGNS · PINT GLASSES · LEATHER TAGS · FLASKS · TABLET CASES · PENS · LAPTOPS · GIFT BOXES · MULTI-TOOLS · ORNAMENTS · SHOT GLASSES · GOLF BALLS · ',
};

function ProductTicker({ garments }) {
  const tickerStyle = { fontFamily: 'var(--display)', fontWeight: 700, fontSize: 13, letterSpacing: '.12em', flexShrink: 0, color: 'var(--red)' };
  return (
    <>
      <style>{`@keyframes ticker-left { from { transform: translateX(0); } to { transform: translateX(-50%); } }`}</style>
      <div style={{ overflow: 'hidden', background: '#fff', padding: '12px 0' }}>
        <div style={{ display: 'inline-flex', whiteSpace: 'nowrap', animation: 'ticker-left 120s linear infinite' }}>
          {[0,1,2,3].map(n => <span key={n} style={tickerStyle}>{garments}</span>)}
        </div>
      </div>
    </>
  );
}

function TeamStoreStrip({ onJump }) {
  return (
    <div className="team-strip" style={{ marginTop: 10, marginLeft: 'calc(50% - 50vw)', marginRight: 'calc(50% - 50vw)', paddingLeft: 'calc(50vw - 600px + 48px)', paddingRight: 'calc(50vw - 600px + 48px)' }}>
      <div>
        <h3>OUTFITTING A SPORTS TEAM?</h3>
        <p>Ask about our Team Stores!<br/>Players and families order in their own sizes.</p>
      </div>
      <button className="btn ghost" onClick={() => onJump('team')}>Visit Team Stores</button>
    </div>
  );
}

function EmbroideryExtras() {
  return (
    <div style={{ marginTop: 64 }}>
      {/* Embroidery Options — 3 column text only */}
      <div style={{ textAlign: 'center', marginBottom: 28 }}>
        <span className="eyebrow">Embroidery Options</span>
      </div>
      <div className="emb-options-grid" style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 20, marginBottom: 64 }}>
        {[
          ['Flat Embroidery', 'A clean, smooth stitch that sits flush with the fabric. Perfect for detailed logos and a classic professional look.', 'assets/emb-flat.png', 'center 50%'],
          ['Puff Embroidery (3D)', 'Raised stitching that adds depth and dimension — most popular on hats for bold, eye-catching designs.', 'assets/emb-puff.png', 'center 50%'],
          ['Tackle Twill', 'Fabric pieces stitched onto garments for a layered look. Commonly used for athletic lettering and large designs.', 'assets/emb-tackle.png', 'center 50%'],
        ].map(([title, body, img, pos], i) => (
          <div key={i} className="image-card">
            <div style={{ background:'#fff', height:185, padding:16, boxSizing:'border-box' }}>
              <img src={img} alt={title} style={{ width:'100%', height:'100%', objectFit:'cover', objectPosition:pos, display:'block' }}/>
            </div>
            <div style={{ padding:'20px 24px 24px' }}>
              <h4 style={{ fontFamily:'var(--display)', fontWeight:700, fontSize:18, letterSpacing:'.06em', textTransform:'uppercase', margin:'0 0 10px' }}>{title}</h4>
              <p style={{ fontSize:13.5, color:'var(--muted)', margin:0, lineHeight:1.55 }}>{body}</p>
            </div>
          </div>
        ))}
      </div>

      {/* Patch Options — grid of cards */}
      <div style={{ textAlign: 'center', marginBottom: 8 }}>
        <span className="eyebrow">Patch Options</span>
      </div>
      <p style={{ textAlign:'center', color:'var(--muted)', fontSize:14, maxWidth:540, margin:'8px auto 28px' }}>
        We offer a wide range of custom patches that can be sewn or heat-applied to your apparel:
      </p>
      <div className="patch-options-grid" style={{ display:'grid', gridTemplateColumns:'repeat(4, 1fr)', gap:14 }}>
        {[
          ['Embroidered Patches', 'Classic stitched look with bold texture', 'assets/patch-embroidered.png'],
          ['Woven Patches', 'Fine detail with a smooth finish', 'assets/patch-woven.png'],
          ['PVC (Rubber) Patches', 'Durable, flexible, and weather-resistant', 'assets/patch-pvc.png'],
          ['Leather Patches', 'For a precision-embroidered, premium finish', 'assets/patch-leather.png'],
        ].map(([title, body, img], i) => (
          <div key={i} className="image-card patch-card">
            <div className="patch-card-img">
              {img
                ? <img src={img} alt={title} style={{ maxWidth:'100%', maxHeight:140, width:'auto', height:'auto', display:'block' }}/>
                : <Imgph label={`${title.toUpperCase()} PATCH`} style={{ height: 110 }}/>
              }
            </div>
            <div className="patch-card-text">
              <h4 style={{ fontFamily:'var(--display)', fontWeight:700, fontSize:14, letterSpacing:'.1em', textTransform:'uppercase', margin:'0 0 6px' }}>{title}</h4>
              <p style={{ fontSize:12.5, color:'var(--muted)', margin:0, lineHeight:1.45 }}>{body}</p>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

/* ============= Shared carousel for a single product ============= */
function ProductCarousel({ product, isMobile }) {
  const [slide, setSlide] = useState(0);

  useEffect(() => { setSlide(0); }, [product.id]);

  const slides = (product.photos && product.photos.length) ? product.photos : [null];
  const total = slides.length;

  if (isMobile) {
    const maxSlide = Math.max(0, total - 1);
    const go = (dir) => setSlide(s => {
      const next = s + dir;
      if (next < 0) return maxSlide;
      if (next > maxSlide) return 0;
      return next;
    });
    return (
      <div className="dp-carousel dp-carousel-mobile" data-product={product.id}>
        <div className="dp-carousel-track" style={{ transform: `translateX(calc(${-slide * 100}% + ${-slide * 12}px))` }}>
          {slides.map((src, i) => (
            <div key={i} className="dp-carousel-slide" style={{ flex: '0 0 100%' }}>
              {src ? (
                <div className="dp-carousel-img" style={{ backgroundImage:`url(${src})` }}/>
              ) : (
                <Imgph label={product.name.toUpperCase()} style={{ width:'100%', height:'100%' }}/>
              )}
            </div>
          ))}
        </div>
        {total > 1 && (
          <>
            <button className="dp-nav prev" onClick={() => go(-1)} aria-label="Previous"><Icon.Chev style={{ transform:'rotate(180deg)' }}/></button>
            <button className="dp-nav next" onClick={() => go(1)} aria-label="Next"><Icon.Chev/></button>
            <div className="dp-dots">
              {Array.from({ length: total }).map((_, i) => (
                <button key={i} className={'dp-dot' + (i === slide ? ' active' : '')} onClick={() => setSlide(i)} aria-label={`View ${i+1}`}/>
              ))}
            </div>
          </>
        )}
      </div>
    );
  }

  const showMulti = total >= 2;
  const maxSlide = showMulti ? Math.max(0, total - 2) : 0;
  const peekMode = total > 2;
  const stepPct = peekMode ? 42 : 50;
  const stepPx = peekMode ? 12 : 6;
  const go = (dir) => setSlide(s => {
    const next = s + dir;
    if (next < 0) return maxSlide;
    if (next > maxSlide) return 0;
    return next;
  });

  return (
    <div className="dp-carousel" data-single={!showMulti} data-product={product.id} data-peek={peekMode}>
      <div className="dp-carousel-track" style={{ transform: showMulti ? `translateX(calc(${-slide * stepPct}% + ${-slide * stepPx}px))` : 'none' }}>
        {slides.map((src, i) => (
          <div key={i} className="dp-carousel-slide" style={!showMulti ? { flex: '0 0 100%' } : undefined}>
            {src ? (
              <div className="dp-carousel-img" style={{ backgroundImage:`url(${src})` }}/>
            ) : (
              <Imgph label={product.images?.[0] || product.name.toUpperCase()} style={{ width:'100%', height:'100%' }}/>
            )}
          </div>
        ))}
      </div>
      {showMulti && maxSlide > 0 && (
        <>
          <button className="dp-nav prev" onClick={() => go(-1)} aria-label="Previous"><Icon.Chev style={{ transform:'rotate(180deg)' }}/></button>
          <button className="dp-nav next" onClick={() => go(1)} aria-label="Next"><Icon.Chev/></button>
          <div className="dp-dots">
            {Array.from({ length: maxSlide + 1 }).map((_, i) => (
              <button key={i} className={'dp-dot' + (i === slide ? ' active' : '')} onClick={() => setSlide(i)} aria-label={`View ${i+1}`}/>
            ))}
          </div>
        </>
      )}
    </div>
  );
}

/* ============= Product detail content (shared) ============= */
function ProductDetail({ product, onQuote }) {
  return (
    <div className="dp-content">
      <h3 style={{ marginTop:0 }}>{product.name.toUpperCase()}</h3>
      <p className="tag-line" style={{ marginBottom:14 }}>{product.tagline}</p>
      {product.specs && (
        <div style={{ display:'flex', gap:10, flexWrap:'wrap', marginBottom:14 }}>
          {product.specs.map(([k, v], i) => (
            <div key={i} style={{ display:'flex', flexDirection:'column', gap:2, padding:'8px 12px', background:'var(--paper-2)', borderLeft:'3px solid var(--red)' }}>
              <span style={{ fontSize:9.5, letterSpacing:'.16em', textTransform:'uppercase', color:'var(--muted)', fontWeight:700 }}>{k}</span>
              <span style={{ fontSize:12.5, fontWeight:600, color:'var(--ink)' }}>{v}</span>
            </div>
          ))}
        </div>
      )}
      <ul className="dp-list" style={{ marginBottom:16 }}>
        {product.bullets.map((b, i) => (
          <li key={i} style={{ padding:'4px 0', fontSize:13 }}>
            <span><strong>{b[0]}</strong>{b[1] ? ' — ' + b[1] : ''}</span>
          </li>
        ))}
      </ul>
      <button className="btn sm" onClick={onQuote}>Get a Quote</button>
    </div>
  );
}

/* ============= Display Products Section ============= */
function DisplayProducts({ onQuote }) {
  const sortedProducts = React.useMemo(() => {
    const pinnedOrder = ['canopy', 'hstake'];
    const pinned = pinnedOrder.map(id => DISPLAY_PRODUCTS.find(p => p.id === id)).filter(Boolean);
    const pinnedIds = new Set(pinnedOrder);
    const rest = DISPLAY_PRODUCTS.filter(p => !pinnedIds.has(p.id)).sort((a, b) => a.name.localeCompare(b.name));
    return [...pinned, ...rest];
  }, []);
  const isMobile = useIsMobile();
  const [active, setActive] = useState(null);
  const hasInitialized = useRef(false);

  useEffect(() => {
    if (hasInitialized.current) return;
    hasInitialized.current = true;
    if (!isMobile) setActive(sortedProducts[0].id);
  }, [isMobile]);

  const toggle = (id) => setActive(prev => prev === id ? null : id);

  return (
    <section className="section dp" id="display">
      <div className="wrap">
        <div className="section-head reveal">
          <span className="eyebrow">Additional Services</span>
          <h2>Promotional Products</h2>
          <p className="lead">From canopies to banners — branded display gear for every event, store, and sideline.</p>
        </div>

        {isMobile ? (
          <div className="dp-accordion">
            {sortedProducts.map(prod => {
              const isOpen = active === prod.id;
              return (
                <div key={prod.id} className={'dp-acc-item' + (isOpen ? ' open' : '')}>
                  <button className="dp-acc-header" onClick={() => toggle(prod.id)}>
                    <span>{prod.name}</span>
                    <Icon.Chev className="chev" style={{ transform: isOpen ? 'rotate(90deg)' : 'none', transition: 'transform .2s' }}/>
                  </button>
                  {isOpen && (
                    <div className="dp-acc-body">
                      <ProductCarousel product={prod} isMobile={true}/>
                      <ProductDetail product={prod} onQuote={onQuote}/>
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        ) : (
          <div className="dp-grid">
            <div className="dp-rail">
              {sortedProducts.map(prod => (
                <button key={prod.id}
                        className={active === prod.id ? 'active' : ''}
                        onClick={() => setActive(prod.id)}>
                  <span>{prod.name}</span>
                  <Icon.Chev className="chev"/>
                </button>
              ))}
            </div>
            {active && (() => {
              const p = DISPLAY_PRODUCTS.find(x => x.id === active);
              return (
                <div className="dp-panel" key={p.id}>
                  <ProductCarousel product={p} isMobile={false}/>
                  <ProductDetail product={p} onQuote={onQuote}/>
                </div>
              );
            })()}
          </div>
        )}
      </div>
    </section>
  );
}

window.LYTLE_SECTIONS = { CoreServices, DisplayProducts, SERVICES, DISPLAY_PRODUCTS };

