// Case studies database — keyed by industry
const CaseStudies = {
  Manufacturing: [
    {
      id: 'mfg-1',
      client: 'Tier-1 Automotive Supplier',
      title: 'Vision-AI defect detection on the stamping line',
      challenge: 'A 12-press stamping facility was losing 4–6 hours per shift to manual visual QA. Defect escape rate to assembly was 1.8%, costing $4.2M annually in downstream rework.',
      solution: 'Deployed AIDD vision pipeline: 11 edge cameras feeding a custom YOLOv8-based defect classifier, integrated into the existing PLC stack. Human-in-loop review surfaces only 0.3% of frames.',
      results: ['98.6% defect detection accuracy', '−87% manual QA time', '$3.6M annual rework savings', '6-week production deployment'],
      tags: ['Computer Vision', 'Edge AI', 'Real-time'],
    },
    {
      id: 'mfg-2',
      client: 'Industrial Pump Manufacturer',
      title: 'Predictive maintenance across 340 CNC machines',
      challenge: 'Unplanned downtime averaged 14 hours/month per machine. Maintenance was calendar-based, missing 60% of actual failure precursors.',
      solution: 'Vibration + thermal sensor ingestion into AIDD anomaly model. Predicts failures 72h in advance and auto-schedules maintenance windows during planned changeovers.',
      results: ['+32% OEE improvement', '−61% unplanned downtime', '$1.9M saved year one', 'ROI in 4.2 months'],
      tags: ['Predictive ML', 'IoT', 'OEE'],
    },
  ],
  Healthcare: [
    {
      id: 'hc-1',
      client: 'Regional Hospital Network (12 facilities)',
      title: 'Prior-authorization automation for specialty care',
      challenge: 'Prior-auth submissions averaged 18 minutes of nurse time. 37% required rework. Patient delays averaged 4.2 days.',
      solution: 'AIDD document agent reads physician notes, EHR data, and payer policies. Drafts the prior-auth packet, predicts approval likelihood, and auto-submits via payer APIs.',
      results: ['−68% admin time per case', '+41% first-pass approval', '4.2 → 0.8 day patient wait', '94% nurse satisfaction'],
      tags: ['NLP', 'EHR Integration', 'HIPAA'],
    },
    {
      id: 'hc-2',
      client: 'Specialty Diagnostics Lab',
      title: 'Clinical document summarization at intake',
      challenge: 'Pathologists spent 22 minutes per case reviewing referral history. 15% of orders were placed without complete clinical context.',
      solution: 'AIDD summarizer extracts indication, prior results, and risk factors from referral packets. Surfaces a 1-screen pathologist briefing.',
      results: ['−74% chart review time', '99.2% indication accuracy', '+28% throughput', '3-week deployment'],
      tags: ['LLM', 'Summarization', 'Clinical'],
    },
  ],
  Retail: [
    {
      id: 'rt-1',
      client: 'Multi-banner Grocery Chain (220 stores)',
      title: 'Demand forecasting for fresh categories',
      challenge: 'Fresh waste was 8.4% of category revenue. Out-of-stocks on top SKUs averaged 11%. Forecast accuracy at the SKU-store-day level was 64%.',
      solution: 'AIDD forecasting model ingests POS, weather, local events, and competitor pricing. Recommendations flow into the existing replenishment system with override controls.',
      results: ['+18% sell-through', '−42% fresh waste', '−61% out-of-stocks on top SKUs', '$11.4M margin uplift Y1'],
      tags: ['Forecasting', 'Replenishment', 'Time-series'],
    },
  ],
  Logistics: [
    {
      id: 'lg-1',
      client: 'Mid-market 3PL',
      title: 'Dynamic route optimization with live traffic + ETA AI',
      challenge: 'Drivers averaged 8% empty miles. Customer ETA accuracy was ±42 minutes. Dispatch was manual across 4 regional hubs.',
      solution: 'AIDD routing engine re-optimizes every 15 minutes against live traffic, capacity, and customer windows. ETA model predicts arrival within ±6 minutes.',
      results: ['−24% miles driven', 'ETA accuracy ±6 min (was ±42)', '+19% on-time delivery', '$2.4M fuel savings Y1'],
      tags: ['Optimization', 'Routing', 'Real-time'],
    },
  ],
  Hospitality: [
    {
      id: 'hs-1',
      client: 'Boutique Hotel Group (38 properties)',
      title: 'AI revenue manager + concierge agent',
      challenge: 'Pricing decisions were weekly, missing event-driven demand spikes. Front-desk handled 1,400 routine inquiries per property per month.',
      solution: 'AIDD pricing model recommends daily rate moves; AI concierge handles 78% of guest inquiries via SMS, email, and in-app chat.',
      results: ['+11% RevPAR', '−63% routine inquiry load', '+0.4 NPS', '8-property pilot in 5 weeks'],
      tags: ['Pricing', 'Conversational AI', 'CX'],
    },
  ],
  eCommerce: [
    {
      id: 'ec-1',
      client: 'DTC Apparel Brand ($180M GMV)',
      title: 'Personalized merchandising + AI returns triage',
      challenge: 'Homepage CTR plateaued at 3.1%. Returns rate was 28% with manual restocking decisions costing $4.10/unit.',
      solution: 'AIDD personalization engine reorders PLP per visitor. Returns AI predicts resale grade and routes to outlet, donate, or restock automatically.',
      results: ['+27% AOV on personalized sessions', '+44% homepage CTR', '−$1.80/unit returns cost', '3.2× ROAS on retargeting'],
      tags: ['Personalization', 'Vision', 'Returns'],
    },
  ],
  RealEstate: [
    {
      id: 're-1',
      client: 'Commercial Property Owner (8.2M sq ft)',
      title: 'Lease abstraction + tenant scoring',
      challenge: 'Lease abstraction averaged 6 hours per document. Tenant default prediction was anecdotal, leading to $7M in annual write-offs.',
      solution: 'AIDD doc-AI extracts 142 lease fields with 99.1% accuracy. Tenant model scores default risk using financials, market signals, and behavioral data.',
      results: ['−54% lease cycle time', '99.1% extraction accuracy', '−38% bad-debt write-offs', '14-week rollout'],
      tags: ['Document AI', 'Risk Scoring', 'Legal NLP'],
    },
  ],
  Education: [
    {
      id: 'ed-1',
      client: 'Online Higher-Ed Provider (44k students)',
      title: 'Adaptive learning + enrollment automation',
      challenge: 'Course completion was 51%. Enrollment ops handled 22k tickets/year manually, with 4.6 day median resolution.',
      solution: 'AIDD adaptive pacing adjusts content per learner. AI enrollment agent resolves 71% of inquiries end-to-end across email, chat, and SMS.',
      results: ['+22% completion rate', '−71% enrollment ticket load', '4.6 → 0.6 day resolution', '+19% Y2 retention'],
      tags: ['Adaptive ML', 'Conversational AI', 'EdTech'],
    },
  ],
  Automotive: [
    {
      id: 'au-1',
      client: 'Multi-state Auto Dealer Group (62 stores)',
      title: 'Dealer CRM AI + claims automation',
      challenge: 'Lead response averaged 4.2 hours. Warranty claim processing took 6.8 days on average with 22% denial rate.',
      solution: 'AIDD lead agent qualifies and responds in under 90 seconds. Claims AI assembles, validates, and submits warranty packets to OEM portals.',
      results: ['−41% claim cycle time', 'Sub-90s lead response', '+34% test-drive conversion', '−14pp denial rate'],
      tags: ['CRM AI', 'Claims', 'OEM Integration'],
    },
  ],
};

// Lightbox component
const CaseStudyLightbox = ({ industry, color, onClose }) => {
  const studies = CaseStudies[industry?.artKey] || [];
  const [active, setActive] = useState(0);

  // Lock body scroll
  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 (!industry) return null;
  const Art = IndustryArt[industry.artKey];
  const cs = studies[active];

  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 */}
        <header className="relative h-[180px] md:h-[220px] overflow-hidden border-b border-token flex-shrink-0"
                style={{ background: `linear-gradient(135deg, ${color}18 0%, transparent 100%)` }}>
          <div className="absolute inset-0"><Art color={color}/></div>
          <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">
                Case studies · {industry.title}
              </div>
              <h2 className="display text-[28px] md:text-[40px] leading-[1.05]" itemProp="about">
                {studies.length} customer {studies.length === 1 ? 'story' : 'stories'} from {industry.title}
              </h2>
            </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 case studies">
            <I.Close size={18}/>
          </button>
        </header>

        {/* Tabs */}
        {studies.length > 1 && (
          <div className="flex border-b border-token overflow-x-auto no-scrollbar flex-shrink-0">
            {studies.map((s, i) => (
              <button key={s.id} onClick={() => setActive(i)}
                className="px-5 py-3 text-[13px] whitespace-nowrap transition-colors border-b-2"
                style={{
                  color: i === active ? color : 'var(--muted)',
                  borderColor: i === active ? color : 'transparent',
                  fontWeight: i === active ? 600 : 400,
                }}>
                {s.client}
              </button>
            ))}
          </div>
        )}

        {/* Body */}
        <div className="flex-1 overflow-y-auto p-6 md:p-10">
          {cs && (
            <div className="grid lg:grid-cols-12 gap-8">
              <div className="lg:col-span-8">
                <div className="font-mono text-[10px] tracking-[0.18em] uppercase text-muted mb-3">
                  Client · <span itemProp="publisher">{cs.client}</span>
                </div>
                <h3 className="display text-[26px] md:text-[34px] leading-[1.1]" itemProp="headline">{cs.title}</h3>

                <div className="mt-7 space-y-7" itemProp="articleBody">
                  <Block label="Challenge" color={color} text={cs.challenge}/>
                  <Block label="AIDD Solution" color={color} text={cs.solution}/>
                </div>

                <div className="mt-7 flex flex-wrap gap-2">
                  {cs.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 panel */}
              <aside className="lg:col-span-4">
                <div className="rounded-xl border border-token p-6 sticky top-0"
                     style={{ background: `${color}08` }}>
                  <div className="font-mono text-[10px] tracking-[0.18em] uppercase mb-5" style={{color}}>
                    Outcomes
                  </div>
                  <ul className="space-y-4">
                    {cs.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: color}}/>
                        <span className="text-[14px] font-medium leading-snug">{r}</span>
                      </li>
                    ))}
                  </ul>
                  <a href="#contact" onClick={onClose}
                    className="mt-7 btn btn-primary w-full justify-center text-[13px]">
                    Discuss your case <I.Arrow size={14}/>
                  </a>
                </div>
              </aside>
            </div>
          )}
        </div>
      </article>
    </div>
  );
};

const Block = ({ label, color, text }) => (
  <div>
    <div className="font-mono text-[10px] tracking-[0.18em] uppercase text-muted mb-2"
         style={{ color: 'var(--muted)' }}>
      <span style={{color}}>—</span> {label}
    </div>
    <p className="text-[15px] leading-relaxed text-[var(--text)]">{text}</p>
  </div>
);

window.CaseStudies = CaseStudies;
window.CaseStudyLightbox = CaseStudyLightbox;
