// ============================================================
// BVS — Case Studies (Work)
// ============================================================
const AI_CASES = [
  { id: '18wheeler', n: 'I', side: 'AI', sector: 'Logistics · Trip Planning', title: 'BleuX', nda: false,
    short: 'A 120+ truck refrigerated-LTL operation stuck on a manual Google Sheets board — discovery, then a ground-up custom TMS, built alongside a Chicago logistics operator.',
    body: 'A 120+ truck LTL refrigerated-freight company was running its entire operation on a manual Google Sheets board. BVS ran full discovery, pinpointed the operational bottlenecks, then built a custom TMS from scratch — branded BLEUX — alongside a Chicago logistics operator: a live planning board with drag-to-merge load management and color-coded status, full load entry, trip consolidation that auto-sums weight across merged LTL loads, a day-view dispatch system, role-based access for dispatchers, planners and warehouse staff, and a full change-history log with admin audit trail.',
    detail: 'A 120+ truck refrigerated-LTL operation was running everything on a manual Google Sheets board. BVS ran discovery alongside a Chicago logistics operator, then built BleuX from scratch — a trip-planning platform for crossdock and dispatch teams. Inbound and outbound loads combine into fully booked trips, every driver’s calendar stays in view, and freight moves by road or rail from the same board: hand-off points named on the trip card, rail-eligible loads flagged automatically, and one status feed across both modes.',
    points: ['Load consolidation into fully booked trips', 'Live driver calendars and open hours at a glance', 'Road + rail planned together on one board', 'Rail-eligible loads flagged automatically', 'Role-based access with full change history', 'Loads imported from existing WMS, TMS or spreadsheets'],
    modules: ['Discovery & Consulting', 'Custom TMS', 'Live Load Board', 'Trip Consolidation', 'Road + Rail', 'Role-Based Audit'],
    stats: [['120+', 'truck fleet'], ['1', 'custom TMS, ground-up'], ['100%', 'audit coverage']],
    cover: 'cases/bleux-hero.jpg', coverPos: '72% 55%',
    shots: [['cases/bleux-hero.jpg', 'BleuX — every load, one trip plan'], ['cases/bleux-road-rail.jpg', 'One board for the truck leg and the rail leg'], ['cases/bleux-benefits.jpg', 'Fuller trailers, fewer idle drivers']] },
  { id: 'blevo', n: 'II', side: 'AI', sector: 'Healthcare · AI Receptionist', title: 'Blevo', nda: false,
    short: 'Our AI receptionist platform for clinics — it answers every call, books straight into live doctor schedules and hands emergencies to a human.',
    detail: 'Blevo is our AI receptionist platform for dental and medical clinics. The clinic’s AI receptionist (“Mila” in this deployment) answers calls around the clock, books patients straight into each doctor’s live schedule, quotes services and prices, answers FAQs and routes emergencies to a person. The clinic runs everything from one dashboard — opening hours, doctors and specialties, shifts and breaks, booking priority when doctors overlap, services and pricing, FAQs and emergency rules — with every call logged against its outcome.',
    points: ['AI receptionist answering calls 24/7', 'Books directly into live doctor schedules', 'Priority routing when doctors’ shifts overlap', 'Services, pricing and FAQs the AI answers from', 'Emergency hand-off rules', 'Call history, outcomes and booking-rate analytics'],
    modules: ['AI Receptionist', 'Scheduling Engine', 'Clinic Dashboard', 'Call Analytics'],
    stats: [['24/7', 'call coverage'], ['1', 'dashboard for the clinic'], ['EN · SR', 'live languages']],
    cover: 'cases/blevo-schedules.jpg', coverPos: '62% 78%',
    shots: [['cases/blevo-dashboard.jpg', 'Clinic dashboard — calls, bookings and usage'], ['cases/blevo-clinic.jpg', 'Clinic settings and AI receptionist'], ['cases/blevo-schedules.jpg', 'Doctor shifts, coverage and breaks'], ['cases/blevo-priority.jpg', 'Booking priority when doctors overlap'], ['cases/blevo-calls.jpg', 'Every call and its outcome'], ['cases/blevo-appointments.jpg', 'Appointments booked by the AI'], ['cases/blevo-services.jpg', 'Services and pricing the AI quotes'], ['cases/blevo-faqs.jpg', 'FAQs the AI answers from']] },
  { id: 'craftwood', n: 'III', side: 'AI', sector: 'Home Services', title: 'Craftwood & Skyvi', nda: false,
    short: 'A home-services company running bookings, suppliers and installs by hand — consulting and discovery, then three connected automation layers.',
    body: 'A home-services company managed client bookings, supplier coordination and installations entirely through manual channels. BVS delivered the consulting phase — running discovery and finding the solution — then architected three connected automation layers: an AI Client Conversation Agent handling WhatsApp, website chat and email with auto-qualification, scheduling and human handoff; a Supplier & Installation Workflow AI automating supplier communication, delivery tracking and installer assignment; and a CRM + Analytics Control Center with a unified database, revenue dashboard, lead-source tracking and forecasting.',
    modules: ['Discovery & Consulting', 'AI Client Agent', 'Supplier Workflow AI', 'CRM + Analytics'],
    stats: [['3', 'automation layers'], ['1', 'unified control center'], ['100%', 'channels covered']],
    img: 'clients/cr-longhair.png' },
  { id: 'dental', n: 'IV', side: 'AI', sector: 'Healthcare', title: 'Dental Clinic', nda: true,
    short: 'Consulting that pinpointed where a 15,000-patient clinic lost money — then a designed fix: insurance verification into Dentrix behind a HIPAA-compliant AI receptionist.',
    body: 'On a consulting engagement, BVS identified exactly where a 15,000-patient clinic was losing money — manual insurance verification and a broken reminder system — then designed the fix. Phase one automated insurance benefit verification by querying insurer systems, extracting benefit PDFs, attaching them to Dentrix records and notifying patients of co-pays before appointments. Phase two repaired reminders with multi-channel SMS/email and added a HIPAA-compliant AI receptionist for inbound calls, with a full audit trail across every touchpoint.',
    modules: ['Consulting & Discovery', 'Insurance Verification', 'AI Receptionist', 'HIPAA Audit Trail'],
    callout: { tag: 'HIPAA CRITICAL', text: 'Every violation risks $100K+. 15,000+ patients. Zero margin for error — all development HIPAA-compliant.' },
    stats: [['15K+', 'patients'], ['24/7', 'AI reception'], ['$100K+', 'compliance risk removed']],
    img: 'clients/cr-cap.png' },
  { id: 'accounting', n: 'V', side: 'AI', sector: 'Financial Services', title: 'Accounting Firm', nda: true,
    short: 'A firm drowning in manual WhatsApp and aging invoices — diagnosed, then an AI revenue operating system deployed across a three-phase roadmap.',
    body: 'BVS came in to consult on a firm drowning in manual WhatsApp, with no CRM and invoices aging 60–90+ days. We diagnosed the leaks and proposed an AI-powered revenue operating system, then deployed it: a WhatsApp AI triage layer with 24/7 message classification and policy-aligned routing, a GoHighLevel CRM foundation centralizing records and pipeline, AR enforcement automation with 30/60/90-day aging sequences, and a Document Intake AI with auto-classification and compliance audit trail — across a three-phase roadmap.',
    modules: ['Consulting & Diagnosis', 'WhatsApp AI Triage', 'GoHighLevel CRM', 'AR Recovery', 'Document Intake AI'],
    callout: { tag: '5X · 24/7', text: '5× faster AR recovery vs. manual, 24/7 AI communication coverage, deployed across a 3-phase roadmap.' },
    stats: [['5×', 'faster AR recovery'], ['24/7', 'AI coverage'], ['3', 'phase roadmap']],
    img: 'clients/young.png' },
];

const MEDIA_CASES = [
  { id: 'ryt', n: 'VI', side: 'MEDIA', sector: 'Blockchain · Web3', title: 'RYT Chain', nda: false,
    short: 'A pioneering Layer-1 blockchain with zero social infrastructure — we’re architecting it entirely, embedded in their team across every platform.',
    detail: 'RYT is a pioneering Layer-1 blockchain — the first to bring governments and citizens onto a secure, natively gas-free ecosystem, with applications spanning supply chain, digital identity, real estate and national digital currencies. They had zero social infrastructure, so Bleu Media Group is constructing RYT Chain’s entire digital presence from the ground up — embedded in their workflow rather than bolted on, across X/Twitter, LinkedIn, Instagram, TikTok and YouTube Shorts.',
    points: ['End-to-end short-form content strategy & production', 'Platform-native content formats for each channel', 'Audience targeting & community growth systems', 'Data-driven content calendar & posting cadence', 'Brand voice & visual identity for social', 'Ongoing performance analytics & optimization'],
    modules: ['Full Social Build', 'Short-Form Production', 'Brand Voice & Identity', 'Embedded Team'],
    stats: [['5', 'platforms built'], ['0→1', 'social from scratch'], ['L1', 'blockchain client']],
    img: 'clients/ryt.png', img2: 'clients/ryt-team.png' },
  { id: 'bigloud', n: 'VII', side: 'MEDIA', sector: 'Music · Records', title: 'Big Loud Rock Records', nda: false,
    short: 'A mass-clipping campaign across the roster — one month of pure volume on 120+ accounts, into the millions of views.',
    detail: 'We ran a mass-clipping campaign for a few of their artists — one month of pure volume across 120+ accounts. For one artist we generated well over 2.5 million views with 500+ different clips, across dozens of accounts posting their music daily. Ideation, cutting, multi-account distribution and per-account performance tracking, all run by BMG.',
    points: ['Mass clipping across 120+ accounts', '500+ unique clips for a single artist', 'Daily multi-account posting cadence', 'TikTok + YouTube Shorts distribution', 'Per-account performance tracking'],
    modules: ['Mass Clipping', 'Multi-Account Distribution', 'Short-Form Cuts', 'Performance Tracking'],
    stats: [['2.3M+', 'total views'], ['126', 'accounts'], ['75K+', 'likes']],
    img: 'clients/blrk.png', img2: 'clients/blrk-charts.png', dark: true },
  { id: 'daniel', n: 'VIII', side: 'MEDIA', sector: 'Education · Creator', title: 'English with Daniel', nda: false,
    short: 'A creator-led education channel — end-to-end production and distribution that compounded into millions of views and real creator revenue.',
    detail: 'A creator-led education channel (Angielski z Danielem). Bleu Media Group ran the full engine — strategy, editing, packaging and posting — that compounded into millions of views, a six-figure subscriber base and real creator revenue in just 90 days. In the last 90-day window the channel pulled 3.5M views, +4K subscribers and $10,700+ in estimated revenue.',
    points: ['End-to-end short & long-form production', 'Thumbnail & packaging design', 'Multi-platform distribution & scheduling', 'Channel growth & audience retention', 'Revenue & performance optimization'],
    modules: ['End-to-End Production', 'Distribution', 'Packaging & Thumbnails', 'Channel Growth'],
    stats: [['3.5M', 'views · 90 days'], ['110K+', 'subscribers'], ['$10.7K', 'revenue · 90 days']],
    img: 'clients/daniel-analytics.png' },
];

const ALL_CASES = [...AI_CASES, ...MEDIA_CASES];

// branded monogram avatar for systems cases (no stock faces)
function caseMono(title) {
  const skip = { a: 1, the: 1, '&': 1, of: 1 };
  const words = title.replace(/[^A-Za-z0-9 &]/g, '').split(/\s+/).filter((w) => w && !skip[w.toLowerCase()]);
  return words.slice(0, 2).map((w) => w[0].toUpperCase()).join('');
}
function CaseAvatar({ c, h = 180 }) {
  const tones = { dental: [BLUE, '#fff'], accounting: [INK, '#fff'], craftwood: [PAPER_DIM, BLUE], '18wheeler': [BLUE, '#fff'] };
  const [bg, fg] = tones[c.id] || [BLUE, '#fff'];
  return (
    <div className="dotgrid-d" style={{ height: h, background: bg, color: fg, position: 'relative', overflow: 'hidden', display: 'flex', alignItems: 'center', justifyContent: 'center', borderBottom: '1px solid var(--bvs-line)' }}>
      <VMark size={Math.round(h * 0.9)} color={fg} style={{ position: 'absolute', right: -h * 0.18, bottom: -h * 0.22, opacity: 0.12 }} />
      <span className="h-disp" style={{ fontSize: Math.round(h * 0.42), color: fg, letterSpacing: '-0.04em' }}>{caseMono(c.title)}<span style={{ opacity: 0.5 }}>.</span></span>
    </div>
  );
}

function CaseCard({ c, onPick, i }) {
  return (
    <div className="reveal card case-card" onClick={() => onPick(c)} style={{ ...delay(i % 3), cursor: 'pointer', overflow: 'hidden', display: 'flex', flexDirection: 'column', transition: 'transform .25s var(--ease), box-shadow .25s var(--ease)' }}>
      <div style={{ position: 'relative' }}>
        {c.cover
          ? <div style={{ height: 180, overflow: 'hidden', background: INK, borderBottom: '1px solid var(--bvs-line)' }}>
              <img src={res('assets/bvs/' + c.cover)} alt={c.title} loading="lazy" style={{ width: '100%', height: '100%', objectFit: 'cover', objectPosition: c.coverPos || '50% 0%', display: 'block' }} />
            </div>
          : c.side === 'AI'
          ? <CaseAvatar c={c} h={180} />
          : <div style={{ height: 180, overflow: 'hidden', background: PAPER_DIM, borderBottom: '1px solid var(--bvs-line)' }}>
              <img src={res('assets/bvs/' + c.img)} alt={c.title} style={{ width: '100%', height: '100%', objectFit: 'cover', objectPosition: '50% 28%', display: 'block' }} />
            </div>}
        <span className="chip" style={{ position: 'absolute', top: 12, left: 12, background: c.side === 'AI' ? INK : BLUE, color: '#fff' }}>{c.side === 'AI' ? 'AI & Systems' : 'Media · BMG'}</span>
      </div>
      <div style={{ padding: '22px 24px 24px', display: 'flex', flexDirection: 'column', flex: 1 }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
          <span className="mono" style={{ fontSize: 12, fontWeight: 700, letterSpacing: '0.1em', color: BLUE }}>{c.n}</span>
          {c.nda && <span className="mono" style={{ fontSize: 9, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', color: '#fff', background: INK, padding: '3px 7px', borderRadius: 2 }}>nda</span>}
        </div>
        <div className="h-disp" style={{ fontSize: 'clamp(20px,1.7vw,26px)', lineHeight: 1.04 }}>{c.title}</div>
        <div className="mono" style={{ fontSize: 10.5, fontWeight: 700, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'rgba(10,10,10,0.45)', marginTop: 8 }}>{c.sector}</div>
        <p style={{ fontSize: 14, lineHeight: 1.55, color: 'rgba(10,10,10,0.62)', margin: '14px 0 0', fontWeight: 500, display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden' }}>{c.short}</p>
        <div style={{ flex: 1 }} />
        <span className="ul-link mono" style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.12em', textTransform: 'uppercase', color: BLUE, marginTop: 18 }}>Read more →</span>
      </div>
    </div>
  );
}

function CaseModal({ c, onClose, onNav }) {
  useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    document.addEventListener('keydown', onKey);
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => { document.removeEventListener('keydown', onKey); document.body.style.overflow = prev; };
  }, []);
  return ReactDOM.createPortal((
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, zIndex: 9999, background: 'rgba(10,10,10,0.55)', backdropFilter: 'blur(4px)', display: 'flex', justifyContent: 'center', alignItems: 'flex-start', padding: '5vh 4vw', overflowY: 'auto' }}>
      <div onClick={(e) => e.stopPropagation()} className="case-modal" style={{ background: PAPER, borderRadius: 12, maxWidth: 1040, width: '100%', overflow: 'hidden', boxShadow: '0 60px 120px -40px rgba(0,0,0,0.5)', animation: 'pageIn .34s var(--ease) both' }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '18px 26px', borderBottom: '1px solid var(--bvs-line)', background: '#fff' }}>
          <div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
            <span className="chip" style={{ background: c.side === 'AI' ? BLUE : INK, color: '#fff' }}>{c.side === 'AI' ? 'AI & Systems' : 'Media · BMG'}</span>
            {c.nda && <span className="mono" style={{ fontSize: 10, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', color: '#fff', background: INK, padding: '3px 8px', borderRadius: 2 }}>nda signed</span>}
          </div>
          <button onClick={onClose} aria-label="Close" className="mono" style={{ border: 0, background: 'transparent', cursor: 'pointer', fontSize: 13, fontWeight: 700, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'rgba(10,10,10,0.55)' }}>Close ✕</button>
        </div>
        <div className="case-detail" style={{ display: 'grid', gridTemplateColumns: '1fr 1.1fr', gap: 40, padding: 'clamp(28px,3vw,44px)', alignItems: c.detail ? 'start' : 'center' }}>
          <div style={c.shots ? { position: 'sticky', top: 24 } : undefined}>
            <Eyebrow slash={false} style={{ color: 'rgba(10,10,10,0.45)' }}>case {c.n} · {c.sector}</Eyebrow>
            <h2 className="h-disp" style={{ fontSize: 'clamp(28px,3.2vw,44px)', marginTop: 10 }}>{c.title}<span style={{ color: BLUE }}>.</span></h2>
            <p style={{ fontSize: 'clamp(15px,1.2vw,17px)', lineHeight: 1.55, color: 'rgba(10,10,10,0.66)', marginTop: 16, fontWeight: 500 }}>{c.detail || c.short}</p>
            {c.points && (
              <div style={{ marginTop: 18 }}>
                <div className="microtag" style={{ marginBottom: 12 }}>what we do for them</div>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 9 }}>
                  {c.points.map((p) => (
                    <span key={p} style={{ display: 'flex', gap: 10, alignItems: 'flex-start', fontSize: 14, fontWeight: 500, color: 'rgba(10,10,10,0.66)', lineHeight: 1.45 }}>
                      <span style={{ color: GREEN_D, fontWeight: 800, marginTop: 1 }}>✓</span>{p}
                    </span>
                  ))}
                </div>
              </div>
            )}
            <div className="det-stats" style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 18, marginTop: 24 }}>
              {c.stats.map(([n, l], i) => (
                <div key={i}><div className="h-disp" style={{ fontSize: 'clamp(22px,2.2vw,32px)', color: BLUE }}>{n}</div><div style={{ fontSize: 11.5, color: 'rgba(10,10,10,0.55)', marginTop: 6, fontWeight: 500 }}>{l}</div></div>
              ))}
            </div>
            <div style={{ marginTop: 26 }}><Button kind="blue" onClick={() => { onClose(); onNav('contact'); }} arrow>Start a project like this</Button></div>
          </div>
          {c.shots ? (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
              {c.shots.map(([src, cap]) => (
                <figure key={src} style={{ margin: 0 }}>
                  <img src={res('assets/bvs/' + src)} alt={cap} loading="lazy" style={{ width: '100%', display: 'block', borderRadius: 10, border: '1px solid var(--bvs-line)', background: '#fff' }} />
                  <figcaption className="mono" style={{ fontSize: 11, fontWeight: 600, letterSpacing: '0.06em', color: 'rgba(10,10,10,0.5)', marginTop: 8 }}>{cap}</figcaption>
                </figure>
              ))}
            </div>
          ) : (
          <div>
            <div style={{ borderRadius: 10, overflow: 'hidden', border: '1px solid var(--bvs-line)', background: c.dark ? '#0a0a0a' : '#fff', position: c.detail ? 'sticky' : 'static', top: 24 }}>
              {c.side === 'AI'
                ? <CaseAvatar c={c} h={300} />
                : <img src={res('assets/bvs/' + c.img)} alt={c.title} style={{ width: '100%', display: 'block', objectFit: 'cover' }} />}
            </div>
            {c.img2 && c.side !== 'AI' && (
              <div style={{ borderRadius: 10, overflow: 'hidden', border: '1px solid var(--bvs-line)', background: c.dark ? '#0a0a0a' : '#fff', marginTop: 14 }}>
                <img src={res('assets/bvs/' + c.img2)} alt={c.title} style={{ width: '100%', display: 'block', objectFit: c.dark ? 'contain' : 'cover', padding: c.dark ? 8 : 0 }} />
              </div>
            )}
          </div>
          )}
        </div>
      </div>
    </div>
  ), document.body);
}

// Inline Case Studies section (scroll-anchored). side: 'AI' | 'MEDIA'
function CaseStudiesSection({ side, onNav, bg = PAPER }) {
  const ref = useReveal();
  const [active, setActive] = useState(null);
  const shown = ALL_CASES.filter((c) => c.side === side);
  useEffect(() => {
    const onOpen = (e) => {
      const key = String(e.detail).toLowerCase();
      const c = ALL_CASES.find((x) => x.id === e.detail || x.title.toLowerCase() === key);
      if (c) setActive(c);
    };
    window.addEventListener('open-case', onOpen);
    return () => window.removeEventListener('open-case', onOpen);
  }, []);
  return (
    <section id="case-studies" ref={ref} style={{ background: bg, padding: '74px 0', scrollMarginTop: 80 }}>
      <div className="wrap">
        <Eyebrow className="reveal">case studies</Eyebrow>
        <h2 className="reveal h-disp" style={{ fontSize: 'clamp(25px,2.6vw,38px)', marginTop: 12, maxWidth: 820, ...delay(1) }}>
          {side === 'AI' ? <>Systems shipped. Results delivered.</> : <>Reach built. Brands globalized.</>}
        </h2>
        <p className="reveal" style={{ fontSize: 16.5, lineHeight: 1.5, color: 'rgba(10,10,10,0.6)', maxWidth: 720, marginTop: 14, fontWeight: 500, ...delay(2) }}>
          {side === 'AI'
            ? 'We lead with consulting — find the leak, design the fix, then build it. Our own platforms, BleuX and Blevo, plus real engagements across healthcare, finance and home services.'
            : 'End-to-end production and distribution that compounds — across music, Web3 and creator education.'}
        </p>
        <div className="work-grid" style={{ display: 'grid', gridTemplateColumns: `repeat(${shown.length === 4 ? 4 : 3},1fr)`, gap: 18, marginTop: 40 }}>
          {shown.map((c, i) => <CaseCard key={c.id} c={c} onPick={setActive} i={i} />)}
        </div>
      </div>
      {active && <CaseModal c={active} onClose={() => setActive(null)} onNav={onNav} />}
    </section>
  );
}

Object.assign(window, { CaseStudiesSection, AI_CASES, MEDIA_CASES, ALL_CASES });
