// ============================================================
// BVS — Solutions landing hero + "Where we work" dot-globe
// ============================================================

// ---- "built around your needs" — client needs flow into the BVS engine, a tailored system comes out ----
function NeedsEngine() {
  const SCENARIOS = [
    { tag: 'AI Receptionist', inbound: 'Hi — do you have any availability this week?', reply: 'Yes — I can fit you in Thursday at 2:00 PM. Want me to confirm?', actions: ['Lead qualified', 'Appointment booked', 'Synced to CRM', 'Reminder scheduled'] },
    { tag: 'Insurance Verification', inbound: 'Can you check what my plan covers before my visit?', reply: 'Verified — your plan covers the visit with a $25 co-pay. I’ve attached the breakdown.', actions: ['Insurer queried', 'Benefits extracted', 'Attached to record', 'Patient notified'] },
    { tag: 'AR Recovery', inbound: 'Invoice #4827 is now 60 days past due.', reply: 'Reminder sent with a payment link and a late-fee notice. Escalating if unpaid in 7 days.', actions: ['Aging detected', 'Reminder sent', 'Late fee applied', 'Follow-up queued'] },
    { tag: 'Dispatch Agent', inbound: 'New load — Chicago to Dallas, reefer, pickup 6 AM.', reply: 'Assigned to Driver #12, route optimized, ETA confirmed. Broker updated.', actions: ['Load matched', 'Driver assigned', 'Route optimized', 'Broker updated'] },
  ];
  const [si, setSi] = useState(0);
  useEffect(() => {
    if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) return;
    const t = setInterval(() => setSi((i) => (i + 1) % SCENARIOS.length), 6500);
    return () => clearInterval(t);
  }, []);
  const s = SCENARIOS[si];
  return (
    <div key={si} style={{ display: 'grid', gridTemplateColumns: '1.35fr 1fr', gap: 18, alignItems: 'stretch' }} className="ac-wrap">
      {/* live conversation */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
        <div className="mono ac-live" style={{ display: 'inline-flex', alignItems: 'center', gap: 8, fontSize: 10, fontWeight: 700, letterSpacing: '0.14em', textTransform: 'uppercase', color: GREEN }}>
          <span style={{ width: 6, height: 6, borderRadius: '50%', background: GREEN }} />{s.tag} · live
        </div>
        <div className="ac-row" style={{ alignSelf: 'flex-start', maxWidth: '90%', background: 'rgba(255,255,255,0.08)', border: '1px solid rgba(255,255,255,0.12)', borderRadius: '4px 14px 14px 14px', padding: '11px 14px', fontSize: 13.5, color: 'rgba(255,255,255,0.9)', animationDelay: '.2s' }}>
          {s.inbound}
        </div>
        <div className="ac-row" style={{ alignSelf: 'flex-end', maxWidth: '92%', background: BLUE, border: '1px solid rgba(255,255,255,0.18)', borderRadius: '14px 4px 14px 14px', padding: '11px 14px', fontSize: 13.5, color: '#fff', animationDelay: '1.1s' }}>
          {s.reply}
        </div>
        <div className="ac-row" style={{ alignSelf: 'flex-start', display: 'inline-flex', alignItems: 'center', gap: 6, background: 'rgba(255,255,255,0.08)', borderRadius: 12, padding: '10px 14px', animationDelay: '2s' }}>
          <span className="ac-typing"><span></span><span></span><span></span></span>
        </div>
      </div>
      {/* actions fired */}
      <div style={{ borderLeft: '1px solid rgba(255,255,255,0.1)', paddingLeft: 18, display: 'flex', flexDirection: 'column', gap: 10 }}>
        <div className="mono" style={{ fontSize: 10, fontWeight: 700, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'rgba(255,255,255,0.4)', marginBottom: 2 }}>Actions</div>
        {s.actions.map((t, i) => (
          <div key={t} className="ac-row" style={{ display: 'flex', alignItems: 'center', gap: 9, animationDelay: (2.6 + i * 0.6) + 's' }}>
            <span style={{ flex: 'none', width: 18, height: 18, borderRadius: '50%', background: 'rgba(74,222,91,0.16)', border: '1px solid rgba(74,222,91,0.5)', color: GREEN, display: 'grid', placeItems: 'center', fontSize: 10, fontWeight: 800 }}>✓</span>
            <span style={{ fontSize: 12.5, fontWeight: 600, color: 'rgba(255,255,255,0.82)' }}>{t}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

function SolutionsHero({ onNav }) {
  const ref = useReveal();
  const words = ['growth layer', 'operations layer', 'systems layer'];
  const [wi, setWi] = useState(0);
  useEffect(() => {
    const reduce = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    if (reduce) return;
    const t = setInterval(() => setWi((i) => (i + 1) % words.length), 2600);
    return () => clearInterval(t);
  }, []);
  return (
    <section ref={ref} className="depth" style={{ position: 'relative', overflow: 'hidden', padding: '96px 0 0' }}>
      <Particles density={1.1} />
      <div className="depth-aurora" />
      <div className="depth-orb" style={{ width: 420, height: 420, background: 'rgba(0,23,219,0.55)', top: '-120px', left: '8%' }} />
      <div className="depth-orb" style={{ width: 360, height: 360, background: 'rgba(60,120,255,0.40)', top: '40px', right: '4%', animationDelay: '3s' }} />
      <div className="wrap" style={{ position: 'relative', textAlign: 'center', maxWidth: 1000, marginLeft: 'auto', marginRight: 'auto' }}>
        <div className="reveal" style={{ display: 'flex', justifyContent: 'center', marginBottom: 30 }}>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 10, background: 'rgba(255,255,255,0.06)', border: '1px solid rgba(255,255,255,0.16)', backdropFilter: 'blur(6px)', borderRadius: 999, padding: '8px 16px' }}>
            <VMark size={15} color="#fff" />
            <span className="mono" style={{ fontSize: 11, fontWeight: 600, letterSpacing: '0.18em', textTransform: 'uppercase', color: 'rgba(255,255,255,0.92)' }}>Bleu Venture Studios</span>
          </span>
        </div>
        <h1 className="reveal h-disp" style={{ color: '#fff', fontSize: 'clamp(40px,6.4vw,92px)', lineHeight: 1.0, letterSpacing: '-0.03em', ...delay(1) }}>
          The AI-native<br />
          <span style={{ position: 'relative', display: 'inline-block', color: '#fff', minHeight: '1.05em' }}>
            {words.map((w, i) => (
              <span key={w} style={{ position: i === wi ? 'relative' : 'absolute', left: 0, right: 0, opacity: i === wi ? 1 : 0, transform: i === wi ? 'translateY(0)' : 'translateY(0.3em)', transition: 'opacity .5s var(--ease), transform .5s var(--ease)', whiteSpace: 'nowrap', textShadow: '0 2px 40px rgba(80,120,255,0.5)' }}>{w}<span style={{ color: GREEN }}>.</span></span>
            ))}
          </span>
        </h1>
        <p className="reveal" style={{ fontSize: 'clamp(15px,1.2vw,18px)', fontWeight: 500, lineHeight: 1.55, color: 'rgba(255,255,255,0.72)', maxWidth: 600, margin: '26px auto 0', ...delay(2) }}>
          We globalize you and re-engineer you for the future — building AI systems around your exact business needs.
        </p>
        <div className="reveal" style={{ display: 'flex', gap: 12, marginTop: 34, justifyContent: 'center', flexWrap: 'wrap', ...delay(3) }}>
          <Button kind="white" onClick={() => onNav('contact')} arrow>Book a Demo</Button>
          <Button kind="ghost-w" onClick={() => onNav('case-studies')}>Case Studies</Button>
        </div>
      </div>
      {/* product visual — floating glass console */}
      <div className="reveal" style={{ ...delay(3), maxWidth: 940, margin: '52px auto 0', padding: '0 8vw 96px', position: 'relative' }}>
        <div className="floaty" style={{ background: 'linear-gradient(180deg, rgba(255,255,255,0.10) 0%, rgba(255,255,255,0.035) 100%)', border: '1px solid rgba(255,255,255,0.16)', borderRadius: 24, position: 'relative', overflow: 'hidden', backdropFilter: 'blur(10px)', boxShadow: '0 60px 120px -50px rgba(0,0,0,0.7), inset 0 1px 0 rgba(255,255,255,0.18)' }}>
          {/* top sheen */}
          <div style={{ position: 'absolute', top: 0, left: 0, right: 0, height: 1, background: 'linear-gradient(90deg, transparent, rgba(255,255,255,0.5), transparent)' }} />
          {/* window chrome */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '15px 20px', borderBottom: '1px solid rgba(255,255,255,0.10)' }}>
            <div style={{ display: 'flex', gap: 7 }}>
              {['rgba(255,255,255,0.28)', 'rgba(255,255,255,0.20)', 'rgba(255,255,255,0.14)'].map((c, i) => <span key={i} style={{ width: 11, height: 11, borderRadius: '50%', background: c }} />)}
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 9 }}>
              <VMark size={14} color="#fff" />
              <span className="h-disp" style={{ color: '#fff', fontSize: 15 }}>BVS<span style={{ color: GREEN }}>.</span></span>
            </div>
            <span className="mono" style={{ marginLeft: 'auto', display: 'inline-flex', alignItems: 'center', gap: 7, fontSize: 10, fontWeight: 600, letterSpacing: '0.16em', textTransform: 'uppercase', color: 'rgba(255,255,255,0.5)' }}>
              <span style={{ width: 6, height: 6, borderRadius: '50%', background: GREEN, boxShadow: '0 0 8px ' + GREEN }} />ai agent
            </span>
          </div>
          <div style={{ padding: 'clamp(20px,3vw,38px) clamp(20px,3vw,44px)' }}>
            <div style={{ maxWidth: 580, margin: '0 auto' }}><NeedsEngine /></div>
          </div>
        </div>
      </div>
    </section>
  );
}

// ---- Cobe WebGL globe (github.com/shuding/cobe) ----
// Covered countries are filled with a grid of green markers so the whole
// country reads as highlighted (Cobe markers are points; a dense grid fills the shape).
const COUNTRY_POLYS = {
  US: [[-123,48.5],[-123,42],[-120,38],[-119,35],[-117,34],[-111,34],[-106,32],[-100,30],[-95,30],[-90,31],[-83,32],[-78,35],[-74,40],[-70,43],[-69,45],[-76,45],[-84,44],[-90,47],[-96,48.5],[-104,49],[-114,49]],
  France: [[-4,48],[-2,47],[-1,46],[-1,44],[3,43],[7,44],[7,46],[8,49],[2,51],[-2,49]],
  Italy: [[7,46],[10,46],[12,46],[14,46],[14,42],[17,41],[18,40],[16,38],[15,37],[12,42],[10,44],[8,44]],
  Serbia: [[19,46],[20,46],[22.5,45],[23,44],[22.5,43],[21,42],[20,42.5],[19.5,44]],
  Poland: [[14.5,54],[18,55],[21,55],[23.5,54],[24,51],[23,49],[19,49],[15,50.5],[14.5,52.5]],
};
// label anchors (lat,lng) per covered country
const GLOBE_LABELS = [
  { name: 'USA', lat: 39, lng: -98 },
  { name: 'France', lat: 47, lng: 2 },
  { name: 'Monaco', lat: 43.7, lng: 7.4, dy: 14 },
  { name: 'Italy', lat: 43, lng: 13 },
  { name: 'Serbia', lat: 44, lng: 21 },
  { name: 'Poland', lat: 52, lng: 19.5 },
];
function pip(lng, lat, poly) {
  let inside = false;
  for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) {
    const xi = poly[i][0], yi = poly[i][1], xj = poly[j][0], yj = poly[j][1];
    if (((yi > lat) !== (yj > lat)) && (lng < ((xj - xi) * (lat - yi)) / (yj - yi) + xi)) inside = !inside;
  }
  return inside;
}
const GLOBE_MARKERS = (() => {
  const out = [];
  const step = 0.55;
  for (const key in COUNTRY_POLYS) {
    const poly = COUNTRY_POLYS[key];
    let minLng = 999, maxLng = -999, minLat = 999, maxLat = -999;
    for (const [lng, lat] of poly) { minLng = Math.min(minLng, lng); maxLng = Math.max(maxLng, lng); minLat = Math.min(minLat, lat); maxLat = Math.max(maxLat, lat); }
    for (let lat = minLat; lat <= maxLat; lat += step) {
      for (let lng = minLng; lng <= maxLng; lng += step) {
        if (pip(lng, lat, poly)) out.push([lat, lng]);
      }
    }
  }
  out.push([43.73, 7.42]); // Monaco
  return out;
})();

// ---- globe component (projection per github.com/shuding/cobe working sample) ----
function DotGlobe({ size = 360 }) {
  const ref = useRef(null);
  const overlayRef = useRef(null);
  useEffect(() => {
    const canvas = ref.current;
    if (!canvas) return;
    const labelEls = overlayRef.current ? Array.from(overlayRef.current.children) : [];
    let globe = null, raf = 0, phi = -1.047, disposed = false;
    const THETA = 0.32, s = size;
    const reduce = window.matchMedia('(prefers-reduced-motion: reduce)').matches;

    const updateLabels = () => {
      const cosTheta = Math.cos(THETA), sinTheta = Math.sin(THETA);
      const cosPhi = Math.cos(phi), sinPhi = Math.sin(phi);
      const R = 0.8 + 0.05;
      for (let i = 0; i < GLOBE_LABELS.length; i++) {
        const el = labelEls[i]; if (!el) continue;
        const L = GLOBE_LABELS[i];
        const latR = L.lat * Math.PI / 180, lonR = L.lng * Math.PI / 180;
        const cosLat = Math.cos(latR);
        const x = cosLat * Math.cos(lonR) * R;
        const y = Math.sin(latR) * R;
        const z = -cosLat * Math.sin(lonR) * R;
        const rx = cosPhi * x + sinPhi * z;
        const ry = sinPhi * sinTheta * x + cosTheta * y - cosPhi * sinTheta * z;
        const rz = -sinPhi * cosTheta * x + sinTheta * y + cosPhi * cosTheta * z;
        if (rz < 0.18) { el.style.opacity = '0'; continue; }
        const px = ((rx + 1) / 2) * s;
        const py = ((-ry + 1) / 2) * s;
        el.style.opacity = Math.min(1, (rz - 0.18) * 4).toFixed(2);
        el.style.transform = `translate(-50%,-50%) translate(${px}px, ${py + (L.dy || 0)}px)`;
      }
    };

    const start = (createGlobe) => {
      if (disposed || !createGlobe) return;
      const dpr = Math.min(2, window.devicePixelRatio || 1);
      const px = size * dpr;
      globe = createGlobe(canvas, {
        devicePixelRatio: dpr,
        width: px,
        height: px,
        phi,
        theta: THETA,
        dark: 1,
        diffuse: 1.2,
        mapSamples: 22000,
        mapBrightness: 3.4,
        baseColor: [0.20, 0.22, 0.28],
        markerColor: [74 / 255, 222 / 255, 91 / 255],
        glowColor: [0.10, 0.14, 0.42],
        markers: GLOBE_MARKERS.map((location) => ({ location, size: 0.035 })),
        onRender: (state) => {
          state.phi = phi;
          state.theta = THETA;
          if (!reduce) phi -= 0.0025;
          state.width = px;
          state.height = px;
          updateLabels();
        },
      });
    };

    if (window.__createGlobe) start(window.__createGlobe);
    else {
      const onReady = () => start(window.__createGlobe);
      window.addEventListener('cobe-ready', onReady, { once: true });
      let tries = 0;
      const poll = setInterval(() => {
        if (window.__createGlobe) { clearInterval(poll); start(window.__createGlobe); }
        else if (++tries > 60) clearInterval(poll);
      }, 100);
      return () => { disposed = true; window.removeEventListener('cobe-ready', onReady); clearInterval(poll); cancelAnimationFrame(raf); if (globe) globe.destroy(); };
    }
    return () => { disposed = true; cancelAnimationFrame(raf); if (globe) globe.destroy(); };
  }, [size]);
  return (
    <div style={{ position: 'relative', width: size, height: size, maxWidth: '100%' }}>
      <canvas ref={ref} width={size} height={size}
        style={{ width: size, height: size, maxWidth: '100%', aspectRatio: '1 / 1', display: 'block', contain: 'layout paint size' }}
        aria-hidden="true" />
      <div ref={overlayRef} style={{ position: 'absolute', inset: 0, pointerEvents: 'none' }}>
        {GLOBE_LABELS.map((l) => (
          <span key={l.name} style={{ position: 'absolute', top: 0, left: 0, opacity: 0, transition: 'opacity .18s linear', whiteSpace: 'nowrap', fontFamily: 'var(--bvs-sans)', fontSize: 10, fontWeight: 600, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'rgba(255,255,255,0.85)', textShadow: '0 1px 6px rgba(0,0,0,0.95)' }}>
            {l.name}
          </span>
        ))}
      </div>
    </div>
  );
}

// ---- where we work ----
const LOCATIONS = ['USA', 'France', 'Monaco', 'Italy', 'Serbia', 'Poland'];

function WhereWeWork() {
  const ref = useReveal();
  return (
    <section id="where-we-work" ref={ref} className="depth" style={{ padding: '64px 0 56px', scrollMarginTop: 72, position: 'relative', overflow: 'hidden' }}>
      <Particles density={1} />
      <div className="depth-aurora" />
      <div className="wrap" style={{ position: 'relative' }}>
        <div className="reveal mono" style={{ display: 'flex', alignItems: 'center', gap: 10, fontSize: 12, fontWeight: 700, letterSpacing: '0.18em', textTransform: 'uppercase', color: 'rgba(255,255,255,0.6)' }}>
          <span style={{ width: 9, height: 9, borderRadius: '50%', background: GREEN, boxShadow: '0 0 8px ' + GREEN }} />6 countries · 2 continents
        </div>
        <div className="reveal" style={{ display: 'flex', justifyContent: 'center', margin: '8px 0' }}>
          <CountryGlobe size={620} />
        </div>
        <div className="reveal" style={{ ...delay(1) }}>
          <div className="mono" style={{ display: 'flex', alignItems: 'center', gap: 9, fontSize: 12, fontWeight: 700, letterSpacing: '0.18em', textTransform: 'uppercase', color: GREEN, marginBottom: 10 }}>
            <span style={{ width: 8, height: 8, borderRadius: '50%', background: GREEN, boxShadow: '0 0 8px ' + GREEN }} />active markets
          </div>
          <div className="mono" style={{ fontSize: 'clamp(13px,1.3vw,16px)', fontWeight: 600, letterSpacing: '0.16em', textTransform: 'uppercase', color: 'rgba(255,255,255,0.78)', display: 'flex', flexWrap: 'wrap', gap: '4px 0' }}>
            {LOCATIONS.map((c, i) => (
              <span key={c}>{c}{i < LOCATIONS.length - 1 && <span style={{ color: 'rgba(255,255,255,0.3)', margin: '0 12px' }}>·</span>}</span>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { SolutionsHero, WhereWeWork });
