// PRODUCTS SECTION — productized use cases Rocketberry has shipped.
// Each product is "Built for" one of the clients in CLIENTS.
// Click a card → lightbox with the full case study (challenge → solution → outcomes).

const PRODUCTS = [
  {
    id: 'invoice-intelligence',
    name: 'Invoice Intelligence',
    clientId: 'northwind',
    artKey: 'Documents',
    color: '#D6248C',
    family: 'Smart Document Processing',
    tagline: 'AP automation for a 12-line stamping facility',
    blurb: 'Auto-extract, validate, route and post 8,000+ vendor invoices/month across 3 ERPs — no human touch on the happy path.',
    tags: ['Document AI', 'OCR', 'ERP'],
    stat: '98.6% accuracy',
    headline: 'From 14 min per invoice to 12 seconds.',
    challenge: 'Northwind processed 8,000 vendor invoices per month across NetSuite, Tally and a legacy system. Average handling time: 14 minutes. Posting errors cost ~$120K/year in reconciliation work.',
    solution: 'Rocketberry built a multi-tenant document agent: OCR + LLM extraction tuned on 142 invoice fields, dual-validator confidence scoring, exception queue, and direct API writebacks to all three ERPs.',
    results: [
      '98.6% extraction accuracy on production traffic',
      '−87% manual handling time per invoice',
      'Posting errors down from 4.1% to 0.3%',
      '6-week pilot to full production rollout',
    ],
  },
  {
    id: 'routemind',
    name: 'RouteMind',
    clientId: 'velosys',
    artKey: 'Workflow',
    color: '#A14BCC',
    family: 'Workflow Automation',
    tagline: 'Live route optimization across 4 hubs',
    blurb: "Re-optimizes 600 daily routes every 15 minutes against traffic, capacity and delivery windows. Dispatch went from manual to assistive.",
    tags: ['Optimization', 'Real-time', 'Logistics'],
    stat: '−24% miles',
    headline: 'Same fleet. 24% fewer miles. 19% more on-time.',
    challenge: 'Drivers averaged 8% empty miles. Customer ETA accuracy was ±42 minutes. Four regional dispatchers built daily routes by hand each morning.',
    solution: 'RouteMind re-optimizes every 15 minutes against live traffic, capacity, vehicle profile and customer windows. A separate ETA model predicts arrival within ±6 minutes; both decisions are written back into the TMS.',
    results: [
      '−24% miles driven across the active fleet',
      'ETA accuracy ±6 minutes (was ±42)',
      '+19% on-time delivery rate',
      '$2.4M fuel savings in year one',
    ],
  },
  {
    id: 'priorauth-pilot',
    name: 'PriorAuth Pilot',
    clientId: 'helio',
    artKey: 'Chatbots',
    color: '#7027A8',
    family: 'Healthcare AI',
    tagline: 'Specialty-care prior-authorization agent',
    blurb: 'Drafts, predicts and submits prior-auth packets across payer portals — nurses only see the exceptions.',
    tags: ['NLP', 'EHR', 'HIPAA'],
    stat: '−68% admin time',
    headline: 'From 4 days to 19 hours of patient wait.',
    challenge: 'Prior-auth submissions averaged 18 minutes of nurse time. 37% required rework. Patients waited 4.2 days on average for approval to begin treatment.',
    solution: 'A HIPAA-aligned document agent reads physician notes, EHR data and live payer policy. It drafts the prior-auth packet, predicts approval likelihood, and submits via payer APIs. Nurses review only flagged or escalated cases.',
    results: [
      '−68% admin time per case',
      '+41% first-pass approval rate',
      'Wait time 4.2 → 0.8 days',
      '94% nurse satisfaction score',
    ],
  },
  {
    id: 'forecast-pulse',
    name: 'Forecast Pulse',
    clientId: 'atlas',
    artKey: 'ERP',
    color: '#1F2754',
    family: 'AI-Enabled ERP',
    tagline: 'SKU-store-day demand forecasting for fresh',
    blurb: 'POS + weather + local events + competitor pricing → daily replenishment recommendations across 220 stores.',
    tags: ['Forecasting', 'Time-series', 'Retail'],
    stat: '−42% waste',
    headline: 'Fresh waste cut by 42%. Margin up $11.4M.',
    challenge: 'Atlas was bleeding 8.4% of fresh category revenue to waste. Out-of-stocks on top SKUs hit 11%. Forecast accuracy at SKU-store-day level sat at 64%.',
    solution: 'Forecast Pulse ingests POS, weather, local events and competitor pricing. Recommendations flow into the existing replenishment system with category-manager override controls. The model retrains weekly per region.',
    results: [
      '+18% sell-through on top-velocity SKUs',
      '−42% fresh-category waste',
      '−61% out-of-stocks on hero items',
      '$11.4M margin uplift in year one',
    ],
  },
  {
    id: 'underwriter-copilot',
    name: 'Underwriter Copilot',
    clientId: 'parallel',
    artKey: 'StartupOps',
    color: '#D6248C',
    family: 'Conversational AI',
    tagline: 'AI copilot for SMB credit decisions',
    blurb: 'Summarizes financials, flags risk signals, drafts the credit memo — underwriters approve or override in one screen.',
    tags: ['LLM', 'Risk', 'Finance'],
    stat: '3.2× throughput',
    headline: 'Underwriters do 3.2× the deals — without cutting corners.',
    challenge: 'Underwriters spent 90 minutes per file on data gathering and memo drafting before getting to actual decisioning. Approval cycle averaged 6 business days.',
    solution: 'A copilot panel inside the existing LOS pulls bank statements, tax returns and credit data, summarizes financial health, surfaces risk signals against policy and drafts a one-page credit memo. The underwriter remains the decider.',
    results: [
      '3.2× more files cleared per underwriter / day',
      'Cycle time 6 days → 1.4 days',
      'Default rate on AI-assisted approvals: −18% vs control',
      'Audit trail captured per recommendation',
    ],
  },
  {
    id: 'leaselens',
    name: 'LeaseLens',
    clientId: 'kinetic',
    artKey: 'Documents',
    color: '#A14BCC',
    family: 'Smart Document Processing',
    tagline: 'Lease abstraction across 8.2M sq ft',
    blurb: 'Extracts 142 lease fields from PDFs of every vintage, ties them to tenant risk and surfaces upcoming actions.',
    tags: ['Document AI', 'Legal NLP', 'Risk'],
    stat: '99.1% accuracy',
    headline: 'Lease cycle cut by more than half. Bad debt down 38%.',
    challenge: 'Lease abstraction averaged 6 hours per document. Tenant default prediction was anecdotal, leading to ~$7M in annual write-offs.',
    solution: 'LeaseLens extracts 142 fields with 99.1% accuracy, normalizes them across formats, and feeds a tenant risk model that scores default likelihood using financials, market signals and behavioural data.',
    results: [
      '−54% lease cycle time',
      '99.1% extraction accuracy across vintages',
      '−38% bad-debt write-offs',
      '14-week portfolio rollout',
    ],
  },
];

// ── Lightbox ────────────────────────────────────────
const ProductLightbox = ({ product, client, onClose }) => {
  useEffect(() => {
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    return () => {
      document.body.style.overflow = prev;
      window.removeEventListener('keydown', onKey);
    };
  }, [onClose]);

  if (!product) return null;
  const Art = SolutionArt[product.artKey] || ServiceArt[product.artKey];
  const c   = product.color;

  return (
    <div className="fixed inset-0 z-[60] flex items-center justify-center p-4 md:p-8"
         style={{ background: 'rgba(11,11,15,0.7)', backdropFilter: 'blur(8px)' }}
         onClick={onClose}>
      <article
        className="relative w-full max-w-[1100px] max-h-[90vh] surface rounded-2xl border border-token shadow-card overflow-hidden flex flex-col"
        onClick={(e) => e.stopPropagation()}
        itemScope itemType="https://schema.org/Article"
      >
        {/* Header art strip */}
        <header className="relative h-[180px] md:h-[220px] overflow-hidden border-b border-token flex-shrink-0"
                style={{ background: `linear-gradient(135deg, ${c}18 0%, transparent 100%)` }}>
          {Art ? <div className="absolute inset-0"><Art color={c}/></div> : null}

          <div className="absolute inset-0 flex items-end p-6 md:p-8">
            <div>
              <div className="font-mono text-[10px] tracking-[0.18em] uppercase text-muted mb-2 flex items-center gap-2">
                <span>{product.family}</span>
                {client && (
                  <>
                    <span className="opacity-50">·</span>
                    <span style={{color: c}}>Built for {client.name}</span>
                  </>
                )}
              </div>
              <h2 className="display text-[28px] md:text-[40px] leading-[1.05]" itemProp="name">{product.name}</h2>
              <p className="mt-1 text-[14px] md:text-[15px] text-muted max-w-2xl">{product.tagline}</p>
            </div>
          </div>

          <button onClick={onClose}
            className="absolute top-4 right-4 w-10 h-10 rounded-full surface border border-token flex items-center justify-center hover:scale-105 transition-transform"
            aria-label="Close">
            <I.Close size={18}/>
          </button>
        </header>

        {/* Body */}
        <div className="flex-1 overflow-y-auto p-6 md:p-10">
          <div className="grid lg:grid-cols-12 gap-8">
            <div className="lg:col-span-8">
              <h3 className="display text-[24px] md:text-[30px] leading-[1.1]" itemProp="headline">
                {product.headline}
              </h3>

              <div className="mt-7 space-y-7" itemProp="articleBody">
                <div>
                  <div className="font-mono text-[10px] tracking-[0.18em] uppercase text-muted mb-2">
                    <span style={{color: c}}>—</span> Challenge
                  </div>
                  <p className="text-[15px] leading-relaxed">{product.challenge}</p>
                </div>
                <div>
                  <div className="font-mono text-[10px] tracking-[0.18em] uppercase text-muted mb-2">
                    <span style={{color: c}}>—</span> Rocketberry solution
                  </div>
                  <p className="text-[15px] leading-relaxed">{product.solution}</p>
                </div>
              </div>

              <div className="mt-7 flex flex-wrap gap-2">
                {product.tags.map(t => (
                  <span key={t} className="px-2.5 py-1 rounded-md text-[11px] font-mono border border-token text-muted">
                    {t}
                  </span>
                ))}
              </div>
            </div>

            {/* Results sidebar */}
            <aside className="lg:col-span-4">
              <div className="rounded-xl border border-token p-6 sticky top-0"
                   style={{ background: `${c}08` }}>
                <div className="font-mono text-[10px] tracking-[0.18em] uppercase mb-5" style={{color: c}}>
                  Outcomes
                </div>
                <ul className="space-y-4">
                  {product.results.map((r, i) => (
                    <li key={i} className="flex items-start gap-3">
                      <span className="mt-1.5 w-1.5 h-1.5 rounded-full flex-shrink-0" style={{background: c}}/>
                      <span className="text-[14px] font-medium leading-snug">{r}</span>
                    </li>
                  ))}
                </ul>
                {client && (
                  <div className="mt-6 pt-5 border-t border-token">
                    <div className="font-mono text-[10px] tracking-[0.18em] uppercase text-muted mb-1.5">
                      Client
                    </div>
                    <div className="flex items-center gap-2.5">
                      <div className="w-9 h-9 rounded-lg flex items-center justify-center font-mono font-semibold text-[13px] border"
                           style={{background: c + '10', color: c, borderColor: c + '30'}}>
                        {client.mono}
                      </div>
                      <div>
                        <div className="text-[14px] font-medium leading-tight">{client.name}</div>
                        <div className="text-[11px] text-muted leading-tight mt-0.5">{client.sector}</div>
                      </div>
                    </div>
                  </div>
                )}
                <a href="#contact" onClick={onClose}
                  className="mt-6 btn btn-primary w-full justify-center text-[13px]">
                  Discuss a similar build <I.Arrow size={14}/>
                </a>
              </div>
            </aside>
          </div>
        </div>
      </article>
    </div>
  );
};

// ── Section ───────────────────────────────────────────
const Products = () => {
  const [open, setOpen] = useState(null);
  const clientMap = Object.fromEntries((window.CLIENTS || []).map(c => [c.id, c]));

  return (
    <Section
      id="products"
      eyebrow="Products we've shipped"
      title="Real builds. Real clients. Real outcomes."
      sub="Every Rocketberry product is a productized use case — born from a client problem, shipped end-to-end, measured against the P&L."
      className="border-t border-token"
    >
      <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-4 md:gap-5"
           itemScope itemType="https://schema.org/ItemList">
        {PRODUCTS.map((p, i) => {
          const Art = SolutionArt[p.artKey] || ServiceArt[p.artKey];
          const client = clientMap[p.clientId];
          return (
            <article
              key={p.id}
              onClick={() => setOpen(p)}
              className="reveal card group relative overflow-hidden cursor-pointer transition-all hover:-translate-y-1"
              style={{transitionDelay: `${i*40}ms`}}
              itemScope itemType="https://schema.org/Product"
              itemProp="itemListElement"
              role="button"
              tabIndex="0"
              onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); setOpen(p); } }}
            >
              <meta itemProp="position" content={i+1}/>

              {/* Art strip */}
              <div className="relative h-[160px] overflow-hidden border-b border-token"
                   style={{ background: `linear-gradient(135deg, ${p.color}10 0%, transparent 100%)` }}>
                <div className="absolute inset-0 transition-transform duration-700 group-hover:scale-105">
                  {Art ? <Art color={p.color}/> : null}
                </div>
                <div className="absolute top-3 left-3 px-2 py-1 rounded-md font-mono text-[10px] tracking-[0.14em] uppercase backdrop-blur-sm"
                     style={{background: 'var(--surface)', color: p.color, border: `1px solid ${p.color}30`}}>
                  Product · {String(i+1).padStart(2,'0')}
                </div>
                <div className="absolute top-3 right-3 px-2.5 py-1 rounded-md text-[11px] font-mono font-medium backdrop-blur-sm"
                     style={{background: p.color, color: '#fff'}}>
                  {p.stat}
                </div>
              </div>

              {/* Body */}
              <div className="p-6">
                <div className="font-mono text-[10px] tracking-[0.18em] uppercase text-muted mb-1.5">
                  {p.family}
                </div>
                <h3 className="display text-[22px] leading-[1.15]" itemProp="name">{p.name}</h3>
                <p className="mt-3 text-[13.5px] text-muted leading-relaxed">{p.blurb}</p>

                {/* Built-for footer */}
                <div className="mt-5 pt-4 border-t border-token flex items-center justify-between gap-3">
                  {client ? (
                    <div className="flex items-center gap-2 min-w-0">
                      <div className="w-7 h-7 rounded-md flex items-center justify-center font-mono font-semibold text-[10px] border flex-shrink-0"
                           style={{background: p.color + '10', color: p.color, borderColor: p.color + '30'}}>
                        {client.mono}
                      </div>
                      <div className="min-w-0">
                        <div className="text-[10px] font-mono uppercase tracking-[0.14em] text-muted leading-none">Built for</div>
                        <div className="text-[12px] font-medium leading-tight mt-0.5 truncate">{client.name}</div>
                      </div>
                    </div>
                  ) : <span/>}
                  <span className="inline-flex items-center gap-1 text-[12px] font-mono uppercase tracking-[0.14em] group-hover:translate-x-0.5 transition-transform flex-shrink-0"
                        style={{color: p.color}}>
                    Case <I.ArrowUR size={14}/>
                  </span>
                </div>
              </div>

              <div className="absolute inset-x-0 top-0 h-0.5 transition-opacity duration-300 opacity-0 group-hover:opacity-100"
                   style={{background: `linear-gradient(90deg, transparent, ${p.color}, transparent)`}}/>
            </article>
          );
        })}
      </div>

      {open && (
        <ProductLightbox
          product={open}
          client={clientMap[open.clientId]}
          onClose={() => setOpen(null)}
        />
      )}
    </Section>
  );
};

window.Products = Products;
