// Services & Case Studies pages

function ServiceVisual({type}) {
  // Subtle abstract visual per service
  const visuals = {
    onboard: (
      <svg viewBox="0 0 400 360" style={{width: '100%', height: '100%'}}>
        <defs>
          <linearGradient id="sv1" x1="0" y1="0" x2="1" y2="1">
            <stop offset="0%" stopColor="#1a1a2e"/><stop offset="100%" stopColor="#16213e"/>
          </linearGradient>
        </defs>
        <rect width="400" height="360" fill="url(#sv1)"/>
        {[1,2,3,4].map((w, i) => (
          <g key={w} transform={`translate(40, ${40 + i*72})`}>
            <rect width="320" height="56" rx="10" fill="rgba(255,255,255,0.04)" stroke="rgba(232,96,76,0.2)"/>
            <circle cx="28" cy="28" r="14" fill={i < 2 ? '#E8604C' : 'rgba(255,255,255,0.1)'}/>
            <text x="28" y="33" textAnchor="middle" fill="white" fontSize="13" fontFamily="Plus Jakarta Sans" fontWeight="700">{w}</text>
            <text x="56" y="26" fill="white" fontSize="13" fontFamily="JetBrains Mono">WEEK {w}</text>
            <text x="56" y="44" fill="rgba(255,255,255,0.5)" fontSize="11" fontFamily="DM Sans">{['Vendor registration','Catalogue setup','Stock allocation','First orders live'][i]}</text>
          </g>
        ))}
      </svg>
    ),
    listing: (
      <svg viewBox="0 0 400 360" style={{width: '100%', height: '100%'}}>
        <rect width="400" height="360" fill="#FAFAFA"/>
        <rect x="40" y="40" width="140" height="180" rx="12" fill="white" stroke="#E5E7EB"/>
        <rect x="56" y="56" width="108" height="80" rx="6" fill="#F0F0F0"/>
        <rect x="56" y="148" width="80" height="8" rx="2" fill="#1A1A1A"/>
        <rect x="56" y="164" width="100" height="6" rx="2" fill="#E5E7EB"/>
        <rect x="56" y="178" width="60" height="6" rx="2" fill="#E5E7EB"/>
        <rect x="56" y="196" width="50" height="14" rx="3" fill="#E8604C"/>
        <g transform="translate(220, 60)">
          {['Title','Images','Bullets','A+ content','Keywords'].map((l, i) => (
            <g key={l} transform={`translate(0, ${i*30})`}>
              <circle cx="8" cy="8" r="6" fill={i < 3 ? '#E8604C' : '#E5E7EB'}/>
              <text x="22" y="12" fill="#1A1A1A" fontSize="13" fontFamily="DM Sans" fontWeight="500">{l}</text>
            </g>
          ))}
        </g>
        <rect x="40" y="240" width="320" height="80" rx="10" fill="white" stroke="#E5E7EB"/>
        <text x="56" y="266" fill="#6B7280" fontSize="10" fontFamily="JetBrains Mono">LISTING QUALITY SCORE</text>
        <text x="56" y="298" fill="#E8604C" fontSize="32" fontFamily="Plus Jakarta Sans" fontWeight="800">94</text>
        <text x="100" y="298" fill="#6B7280" fontSize="14">/100</text>
        <rect x="160" y="280" width="180" height="6" rx="3" fill="#F0F0F0"/>
        <rect x="160" y="280" width="170" height="6" rx="3" fill="#E8604C"/>
      </svg>
    ),
    ads: (
      <svg viewBox="0 0 400 360" style={{width: '100%', height: '100%'}}>
        <rect width="400" height="360" fill="#FAFAFA"/>
        {[60,90,120,80,140,100,160].map((h, i) => (
          <g key={i}>
            <rect x={50 + i*42} y={280-h} width="28" height={h} rx="3" fill="#E8604C" opacity={0.3 + i*0.1}/>
          </g>
        ))}
        <line x1="40" y1="280" x2="360" y2="280" stroke="#E5E7EB"/>
        <text x="40" y="60" fontSize="11" fontFamily="JetBrains Mono" fill="#6B7280">ROAS BY PLATFORM</text>
        <text x="40" y="100" fontSize="36" fontFamily="Plus Jakarta Sans" fontWeight="800" fill="#1A1A1A">4.8x</text>
        <text x="120" y="100" fontSize="13" fontFamily="DM Sans" fill="#E8604C">↑ 32%</text>
      </svg>
    ),
    stock: (
      <svg viewBox="0 0 400 360" style={{width: '100%', height: '100%'}}>
        <defs>
          <linearGradient id="sv2" x1="0" y1="0" x2="0" y2="1"><stop offset="0%" stopColor="#1a1a2e"/><stop offset="100%" stopColor="#16213e"/></linearGradient>
        </defs>
        <rect width="400" height="360" fill="url(#sv2)"/>
        <text x="40" y="50" fontSize="11" fontFamily="JetBrains Mono" fill="rgba(255,255,255,0.5)">OOS REDUCTION · 60 DAYS</text>
        <text x="40" y="90" fontSize="14" fontFamily="DM Sans" fill="white">14%</text>
        <text x="320" y="90" fontSize="14" fontFamily="DM Sans" fill="#E8604C" textAnchor="end">3%</text>
        <path d="M 40 110 Q 120 110, 200 180 T 360 280" stroke="#E8604C" strokeWidth="2.5" fill="none"/>
        <circle cx="40" cy="110" r="5" fill="white"/>
        <circle cx="360" cy="280" r="5" fill="#E8604C"/>
        {/* Dark store nodes */}
        <g transform="translate(40, 310)">
          {[0,1,2,3,4,5,6,7].map(i => (
            <g key={i} transform={`translate(${i*40}, 0)`}>
              <rect width="30" height="20" rx="3" fill="rgba(232,96,76,0.2)" stroke="#E8604C"/>
              <text x="15" y="14" textAnchor="middle" fontSize="9" fontFamily="JetBrains Mono" fill="white">N{i+1}</text>
            </g>
          ))}
        </g>
      </svg>
    ),
    reports: (
      <svg viewBox="0 0 400 360" style={{width: '100%', height: '100%'}}>
        <rect width="400" height="360" fill="#FAFAFA"/>
        <rect x="40" y="40" width="320" height="280" rx="12" fill="white" stroke="#E5E7EB"/>
        <text x="60" y="74" fontSize="11" fontFamily="JetBrains Mono" fill="#6B7280">MONTHLY REPORT · APR 2026</text>
        <text x="60" y="104" fontSize="20" fontFamily="Plus Jakarta Sans" fontWeight="700" fill="#1A1A1A">Brand Performance</text>
        {[
          ['Sales velocity', '+24%'],
          ['Share of shelf', '18.2%'],
          ['Ad ROAS', '4.8x'],
          ['SLA compliance', '98%'],
        ].map(([k, v], i) => (
          <g key={k} transform={`translate(60, ${140 + i*36})`}>
            <text fontSize="13" fontFamily="DM Sans" fill="#6B7280">{k}</text>
            <text x="280" textAnchor="end" fontSize="14" fontFamily="Plus Jakarta Sans" fontWeight="600" fill="#E8604C">{v}</text>
            <line x1="0" y1="14" x2="280" y2="14" stroke="#F0F0F0"/>
          </g>
        ))}
      </svg>
    ),
    portfolio: (
      <svg viewBox="0 0 400 360" style={{width: '100%', height: '100%'}}>
        <defs>
          <linearGradient id="sv3" x1="0" y1="0" x2="1" y2="1"><stop offset="0%" stopColor="#1a1a2e"/><stop offset="100%" stopColor="#16213e"/></linearGradient>
        </defs>
        <rect width="400" height="360" fill="url(#sv3)"/>
        {/* Grid of brand tiles */}
        {Array.from({length: 30}).map((_, i) => {
          const col = i % 6, row = Math.floor(i / 6);
          return <rect key={i} x={40 + col*54} y={40 + row*54} width="40" height="40" rx="6" 
            fill={`rgba(232,96,76,${0.1 + (i%5)*0.08})`} 
            stroke="rgba(232,96,76,0.3)"/>
        })}
        <text x="40" y="320" fontSize="11" fontFamily="JetBrains Mono" fill="rgba(255,255,255,0.5)">30 BRANDS · 210+ SKUS</text>
        <text x="40" y="340" fontSize="11" fontFamily="JetBrains Mono" fill="#E8604C">4 PLATFORMS · DAILY OPS</text>
      </svg>
    ),
  };
  return <div className="service-visual">{visuals[type]}</div>;
}

function ServicesPage({navigate}) {
  const services = [
    {
      type: 'onboard',
      title: 'Live on any platform in 30 days.',
      tag: 'PLATFORM ONBOARDING',
      body: "We handle the entire onboarding process — vendor registration, documentation, compliance checks, catalogue setup, and stock feed configuration. Whether you're launching on Talabat Mart, Noon Minutes, Careem Quik, or Amazon.ae, we've done it across 30 brands and know exactly what each platform requires.",
      bullets: ['Vendor registration and documentation','Product catalogue setup and SKU mapping','Platform-specific compliance and labeling review','Stock feed integration and dark-store allocation','First order within 30 days of engagement'],
    },
    {
      type: 'listing',
      title: 'Product pages that actually show up and sell.',
      tag: 'LISTING & CONTENT',
      body: "Your product detail page is your shelf space. We optimize titles, images, bullet points, descriptions, and A+ content for each platform's search algorithm. This isn't generic SEO — it's platform-specific listing optimization based on how Talabat, Noon, and Amazon rank products differently.",
      bullets: ['Platform-specific title and keyword optimization','Product image guidelines and creation','A+ content and enhanced brand pages','Regular content audits and score tracking','Listing Quality Score framework across 12 levers'],
    },
    {
      type: 'ads',
      title: 'Ad spend that you can actually measure.',
      tag: 'ADVERTISING',
      body: "We manage your sponsored listings, flash deals, banner ads, and promotional campaigns across every platform. Every dirham spent is tracked against actual sales performance — not vanity metrics.",
      bullets: ['Sponsored product and brand campaigns','Flash deal and promotion planning','ROAS tracking and spend optimization','Platform-specific ad strategy','Monthly ad performance reporting'],
    },
    {
      type: 'stock',
      title: 'Stockouts cost you more than you think.',
      tag: 'STOCK & FORECASTING',
      body: "We track stock levels across every dark store and platform warehouse. Our forecasting models account for seasonality, Ramadan demand spikes, platform promotions, and historical velocity — so your products are in stock when customers search for them.",
      bullets: ['Real-time stock monitoring across all nodes','MSL planning per dark store','Demand forecasting for peak seasons (Ramadan, Eid, DSF)','Automated reorder trigger alerts','OOS reduction: from 14% to 3%'],
    },
    {
      type: 'reports',
      title: 'Reports your brand principals actually want to read.',
      tag: 'REPORTING & ANALYTICS',
      body: "Monthly performance reports that cover what matters: sales velocity, share of digital shelf, ad ROAS, SLA compliance, stock health, and competitive positioning. Not 40-page decks — clear, actionable insights your team can act on.",
      bullets: ['Monthly brand performance reports','Platform-by-platform sales breakdown','Share of search and share of shelf tracking','SLA compliance scorecards','Quarterly business reviews and strategy'],
    },
    {
      type: 'portfolio',
      title: 'Your outsourced e-commerce department.',
      tag: 'FULL PORTFOLIO MANAGEMENT',
      body: "This is the A-to-Z offer. We become an extension of your team — managing your entire brand portfolio across all platforms, every day. Onboarding, content, ads, stock, reporting, platform relationships — all handled. You focus on selling and distributing. We handle the digital shelf.",
      bullets: ['Dedicated account management','Daily platform operations across Talabat, Noon, Amazon, Careem','Cross-platform strategy and coordination','Platform relationship management','Scalable from 5 to 50+ brands'],
    },
  ];

  return (
    <div data-screen-label="Services">
      <section className="hero hero-half bg-navy" style={{position: 'relative'}}>
        <div className="hero-grid"></div>
        <div className="hero-glow hero-glow-1"></div>
        <div className="container hero-content">
          <FadeUp><span className="eyebrow">OUR SERVICES</span></FadeUp>
          <FadeUp delay={120}><h1 style={{fontSize: 'clamp(36px, 5vw, 64px)'}}>We run your brands on UAE q-commerce platforms.</h1></FadeUp>
          <FadeUp delay={240}><p className="hero-sub">From onboarding to daily operations — every service you need to grow on Talabat, Noon, Amazon, and Careem.</p></FadeUp>
        </div>
      </section>

      {services.map((s, i) => (
        <section key={i} className={i % 2 === 0 ? 'bg-white' : 'bg-light'} style={{padding: '40px 0'}}>
          <div className="container">
            <div className="service-detail" style={{direction: i % 2 === 1 ? 'rtl' : 'ltr'}}>
              <FadeUp className="service-text" >
                <div style={{direction: 'ltr'}}>
                  <span className="eyebrow">{s.tag}</span>
                  <h3>{s.title}</h3>
                  <p>{s.body}</p>
                  <ul className="checks">
                    {s.bullets.map(b => <li key={b}>{b}</li>)}
                  </ul>
                </div>
              </FadeUp>
              <FadeUp delay={120}>
                <div style={{direction: 'ltr'}}>
                  <ServiceVisual type={s.type} />
                </div>
              </FadeUp>
            </div>
          </div>
        </section>
      ))}

      <section className="section bg-navy">
        <div className="container" style={{textAlign: 'center'}}>
          <FadeUp>
            <h2 style={{color: 'white', fontSize: 'clamp(28px, 4vw, 48px)', marginBottom: 16}}>Not sure which services you need?</h2>
            <p style={{color: 'rgba(255,255,255,0.7)', fontSize: 18, marginBottom: 32, maxWidth: 600, margin: '0 auto 32px'}}>Take the readiness assessment. We'll tell you exactly where to start.</p>
            <a href="#/contact" className="btn btn-primary">Get Your Readiness Score →</a>
          </FadeUp>
        </div>
      </section>
    </div>
  );
}

// CASE STUDIES
function CasesPage({navigate}) {
  const [openCase, setOpenCase] = useState(null);
  const cases = [
    {
      title: "10× growth in 12 months: how we scaled befit on UAE q-commerce",
      tag: "befit · Talabat, Noon, Amazon, Careem",
      metric: "10×",
      metricLabel: "Revenue growth in 12 months",
      preview: "Launched befit on UAE q-commerce in January 2025. Twelve months later, the brand is doing 10× the volume — built through a sequenced launch, performance marketing, ad optimization, retention promotions, and influencer-led demand generation.",
      scipab: [
        ['Situation', 'befit, a functional health-snack brand, was looking to enter UAE q-commerce in January 2025. The brand had product-market fit but no q-commerce presence, no platform relationships, and no UAE digital playbook.'],
        ['Complication', 'A cold launch on UAE q-commerce typically stalls — listings sit at the bottom of search, ad spend leaks without ROAS attribution, and there\'s no demand signal to support dark-store allocation requests. Most brands plateau within 60 days.'],
        ['Implication', 'Without a sequenced go-to-market, befit risked being one more brand on the shelf with flat velocity — invisible to algorithms that reward early traction, and burning ad budget chasing impressions instead of repeat customers.'],
        ['Position', 'We treated launch as a 12-month operating system, not a one-time event. Five plays running in parallel: strategic product sequencing, platform-native marketing, daily ad optimization, loyalty-driven promotions, and influencer demand generation feeding back into platform search.'],
        ['Action', 'Phased SKU rollout aligned to platform category gaps · Listing content built against our Listing Quality Score framework · Ad campaigns restructured weekly with ROAS attribution per SKU and platform · Promo calendar mapped to retention windows (re-purchase day 14/28/45) and platform flash-deal slots · Influencer campaigns targeted to Dubai/Abu Dhabi health and fitness creators, with discount codes routed back to platform listings to compound search ranking.'],
        ['Benefit', '10× revenue growth from launch to month 12. Live across all four major UAE q-commerce platforms. Sustained month-on-month growth, repeat-purchase rate above category average, and a top-three position in search for the brand\'s primary keywords.'],
      ],
    },
    {
      title: "OOS reduced from 14% to 3% in 60 days",
      tag: "Health Food Brand · Talabat Mart",
      metric: "14% → 3%",
      metricLabel: "Out-of-stock rate",
      preview: "A health food brand across 8 dark-store nodes was losing sales to preventable stockouts. We rebuilt their MSL planning and stock allocation model node by node.",
      scipab: [
        ['Situation', 'A health food brand distributed by a UAE-based FMCG company was live on Talabat Mart across 8 dark-store nodes.'],
        ['Complication', 'Out-of-stock rate was running at 14% — meaning 1 in 7 customer searches returned no product. The distributor had no node-level visibility and was checking stock weekly.'],
        ['Implication', 'At ~120 units/day demand, 14% OOS translated to ~17 lost sales/day, roughly AED 8,500/week in missed revenue — and platform search ranking was decaying because the algorithm deprioritises out-of-stock SKUs.'],
        ['Position', 'Node-level stock tracking, MSL (Minimum Stock Level) rebuild based on 90-day velocity per dark store, and a daily check rhythm replacing the weekly one.'],
        ['Action', 'Daily stock audits, automated reorder alerts when any node dropped below 3-day supply, and direct coordination with the platform\'s supply chain team for replenishment exceptions.'],
        ['Benefit', 'OOS dropped from 14% to 3% in 60 days. Recovered revenue ~AED 30,000+/month, search ranking restored within two weeks of stabilising availability.'],
      ],
    },
    {
      title: "24 SKUs live on Noon Minutes in 30 days",
      tag: "Sports Nutrition · UAE market entry",
      metric: "24 SKUs",
      metricLabel: "Live in 30 days",
      preview: "An international sports nutrition brand wanted to enter UAE through q-commerce. Zero presence to 24 SKUs live on Noon Minutes within one month — running vendor onboarding, listing build, and dark-store negotiation in parallel.",
      scipab: [
        ['Situation', 'International sports nutrition brand with strong UK presence, a newly appointed UAE distributor, and zero local e-commerce footprint.'],
        ['Complication', 'The distributor had no Noon Minutes vendor account, no listing assets sized for the platform, and no dark-store relationship. Standard onboarding timelines would push the launch into Q2.'],
        ['Implication', 'Every week of delay was missed velocity in a category where early-mover ranking compounds. The brand needed to be searchable before competitors filled the same shelf.'],
        ['Position', 'A 30-day parallel sprint: vendor registration, listing creation, content optimization, and dark-store allocation negotiated simultaneously rather than sequentially.'],
        ['Action', 'Vendor onboarding completed in week 1 · 24 listings built against Noon Minutes content rules in weeks 2-3 · dark-store allocation negotiated and stock fed in by week 4.'],
        ['Benefit', '24 SKUs live and purchasable across Dubai dark stores within 30 days of engagement, with platform-optimized content from day one.'],
      ],
    },
    {
      title: "Listing overhaul: 55% MoM growth on Noon Minutes",
      tag: "Ambient Snacks · Noon Minutes & Amazon.ae",
      metric: "55%",
      metricLabel: "MoM growth, sustained one quarter",
      preview: "Live on platforms but flat. Listings were copy-pasted from offline catalogues and ad spend wasn't tracked. We rebuilt the digital shelf — content, attribution, and dark-store coverage.",
      scipab: [
        ['Situation', 'An ambient snacks brand distributed across Noon Minutes and Amazon.ae, with active ad spend but flat monthly sales for two consecutive quarters.'],
        ['Complication', 'Listings were copy-pasted from the offline catalogue with no platform-specific keyword work. Ad spend was running with no ROAS attribution. Dark-store coverage was capped at 12 nodes when 28 were serviceable.'],
        ['Implication', 'The brand was paying for impressions it couldn\'t convert and missing customers in 16 dark stores it could have been live in — a structural ceiling, not a performance one.'],
        ['Position', 'Three-track fix: full listing rebuild against our Listing Quality Score framework, ad restructure with clear ROAS attribution, and a dark-store expansion request supported by our existing velocity data on adjacent SKUs.'],
        ['Action', 'Rewrote all listings · restructured ad campaigns by SKU and intent stage · expanded dark-store allocation from 12 → 28 nodes through platform negotiation.'],
        ['Benefit', '55% month-on-month growth sustained over the following quarter, with positive ROAS on every active campaign for the first time.'],
      ],
    },
  ];

  return (
    <div data-screen-label="Cases">
      <section className="hero hero-half bg-navy" style={{position: 'relative'}}>
        <div className="hero-grid"></div>
        <div className="hero-glow hero-glow-1"></div>
        <div className="container hero-content">
          <FadeUp><span className="eyebrow">CASE STUDIES</span></FadeUp>
          <FadeUp delay={120}><h1 style={{fontSize: 'clamp(36px, 5vw, 64px)'}}>Real operations.<br/>Real numbers.</h1></FadeUp>
          <FadeUp delay={240}><p className="hero-sub">Anonymized results from brands we manage across UAE q-commerce platforms. The method is real — the results speak for themselves.</p></FadeUp>
        </div>
      </section>

      <section className="section bg-white">
        <div className="container">
          <div className="grid-2">
            {cases.map((c, i) => (
              <FadeUp key={i} delay={i * 80}>
                <div className="card case-card" onClick={() => setOpenCase(i)}>
                  <span className="case-tag">{c.tag}</span>
                  <div className="case-metric">{c.metric}</div>
                  <div style={{fontSize: 13, color: 'var(--muted-text)', fontFamily: 'var(--mono)', textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: 16}}>{c.metricLabel}</div>
                  <h3>{c.title}</h3>
                  <p>{c.preview}</p>
                  <span className="learn-more">Read the full case →</span>
                </div>
              </FadeUp>
            ))}
          </div>
        </div>
      </section>

      {openCase !== null && (
        <div onClick={() => setOpenCase(null)} className="case-modal-overlay" style={{
          position: 'fixed', inset: 0, background: 'rgba(15,15,35,0.85)', backdropFilter: 'blur(8px)',
          zIndex: 200, display: 'flex', alignItems: 'flex-start', justifyContent: 'center',
          overflow: 'auto', padding: '80px 24px',
        }}>
          <div onClick={e => e.stopPropagation()} className="case-modal" style={{
            background: 'white', borderRadius: 20, maxWidth: 760, width: '100%', padding: 56, position: 'relative',
          }}>
            <button onClick={() => setOpenCase(null)} className="case-modal-close" style={{
              position: 'absolute', top: 20, right: 20, width: 36, height: 36, borderRadius: 8,
              background: 'var(--light-gray)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 18, color: 'var(--dark-text)',
            }}>×</button>
            <span className="case-tag">{cases[openCase].tag}</span>
            <h2 className="case-modal-h2" style={{fontSize: 32, marginTop: 16, marginBottom: 12, lineHeight: 1.2}}>{cases[openCase].title}</h2>
            <div className="case-modal-metric case-metric" style={{fontSize: 56}}>{cases[openCase].metric}</div>
            <div className="scipab">
              {cases[openCase].scipab.map(([label, text]) => (
                <div key={label} className="scipab-row">
                  <div className="scipab-label">{label}</div>
                  <div className="scipab-text">{text}</div>
                </div>
              ))}
            </div>
          </div>
        </div>
      )}

      <section className="section bg-navy">
        <div className="container" style={{textAlign: 'center'}}>
          <FadeUp>
            <h2 style={{color: 'white', fontSize: 'clamp(28px, 4vw, 48px)', marginBottom: 32}}>Want results like these for your brands?</h2>
            <a href="#/contact" className="btn btn-primary">Get Your Readiness Score →</a>
          </FadeUp>
        </div>
      </section>
    </div>
  );
}

window.ServicesPage = ServicesPage;
window.CasesPage = CasesPage;
