
// Hero.jsx — 3D spatial scene with mouse parallax physics

function WorkerSVG({ flip, style }) {
  return (
    <svg width="38" height="60" viewBox="0 0 38 60" fill="none" style={style}>
      {/* Hard hat */}
      <ellipse cx="19" cy="10" rx="12" ry="5" fill="#f59e0b"/>
      <rect x="10" y="10" width="18" height="3" rx="1" fill="#f59e0b"/>
      {/* Head */}
      <circle cx="19" cy="17" r="6" fill="#fcd9a0"/>
      {/* Vest body */}
      <rect x="12" y="23" width="14" height="16" rx="3" fill="#e11d48"/>
      <rect x="16" y="23" width="6" height="16" fill="#ff6b35" opacity="0.6"/>
      {/* Arms */}
      <rect x={flip ? "22" : "6"} y="24" width="5" height="12" rx="2" fill="#e11d48" style={{transform: flip ? 'none' : 'none'}}/>
      <rect x={flip ? "10" : "27"} y="24" width="5" height="12" rx="2" fill="#e11d48"/>
      {/* Pants */}
      <rect x="12" y="38" width="6" height="14" rx="2" fill="#1e293b"/>
      <rect x="20" y="38" width="6" height="14" rx="2" fill="#1e293b"/>
      {/* Boots */}
      <rect x="11" y="50" width="8" height="5" rx="2" fill="#374151"/>
      <rect x="19" y="50" width="8" height="5" rx="2" fill="#374151"/>
      {/* Safety stripe */}
      <rect x="12" y="31" width="14" height="2" rx="1" fill="#fbbf24" opacity="0.9"/>
    </svg>
  );
}

// Mini panel card components
function MiniCard({ label, value, color, style: sx }) {
  return (
    <div style={{
      background: 'rgba(21,25,37,0.95)',
      border: `1px solid ${color}40`,
      borderRadius: 10,
      padding: '10px 14px',
      backdropFilter: 'blur(12px)',
      boxShadow: `0 8px 32px rgba(0,0,0,0.5), 0 0 0 1px ${color}20`,
      minWidth: 140,
      ...sx,
    }}>
      <div style={{ fontSize: 10, color: '#64748b', fontWeight: 700, textTransform: 'uppercase', letterSpacing: 1, marginBottom: 4 }}>{label}</div>
      <div style={{ fontSize: 18, fontWeight: 800, color: '#e2e8f0' }}>{value}</div>
      <div style={{ width: 24, height: 3, borderRadius: 2, background: color, marginTop: 6 }}/>
    </div>
  );
}

function AlertCard({ style: sx, label, title, sub }) {
  return (
    <div style={{
      background: 'rgba(21,25,37,0.95)',
      border: '1px solid #e11d4840',
      borderRadius: 10,
      padding: '10px 14px',
      backdropFilter: 'blur(12px)',
      boxShadow: '0 8px 32px rgba(0,0,0,0.5)',
      minWidth: 170,
      ...sx,
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 6 }}>
        <div style={{ width: 6, height: 6, borderRadius: '50%', background: '#e11d48', animation: 'pulse 1.5s infinite' }}/>
        <span style={{ fontSize: 10, color: '#e11d48', fontWeight: 700, textTransform: 'uppercase', letterSpacing: 1 }}>{label}</span>
      </div>
      <div style={{ fontSize: 13, color: '#e2e8f0', fontWeight: 600 }}>{title}</div>
      <div style={{ fontSize: 11, color: '#64748b', marginTop: 3 }}>{sub}</div>
    </div>
  );
}

function TelegramCard({ style: sx, from, msg, reply }) {
  return (
    <div style={{
      background: 'rgba(21,25,37,0.95)',
      border: '1px solid #3b82f640',
      borderRadius: 12,
      padding: '12px 14px',
      backdropFilter: 'blur(12px)',
      boxShadow: '0 8px 32px rgba(0,0,0,0.5)',
      minWidth: 200,
      ...sx,
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
        <div style={{ width: 28, height: 28, borderRadius: '50%', background: '#2AABEE22', display: 'flex', alignItems: 'center', justifyContent: 'center', border: '1px solid #2AABEE40' }}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="#2AABEE"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm4.64 6.8c-.15 1.58-.8 5.42-1.13 7.19-.14.75-.42 1-.68 1.03-.58.05-1.02-.38-1.58-.75-.88-.58-1.38-.94-2.23-1.5-.99-.65-.35-1.01.22-1.59.15-.15 2.71-2.48 2.76-2.69a.2.2 0 00-.05-.18c-.06-.05-.14-.03-.21-.02-.09.02-1.49.95-4.22 2.79-.4.27-.76.41-1.08.4-.36-.01-1.04-.2-1.55-.37-.62-.2-1.12-.31-1.08-.65.02-.18.27-.36.74-.55 2.92-1.27 4.86-2.11 5.83-2.51 2.78-1.16 3.35-1.36 3.73-1.36.08 0 .27.02.39.12.1.08.13.19.14.27-.01.06.01.24 0 .24z"/></svg>
        </div>
        <span style={{ fontSize: 11, color: '#94a3b8', fontWeight: 600 }}>BLD Construction Software</span>
      </div>
      <div style={{ fontSize: 12, color: '#e2e8f0', lineHeight: 1.5 }}>{msg}<br/><span style={{ color: '#10b981' }}>{reply}</span></div>
    </div>
  );
}

function ProgressCard({ style: sx, label, sA, sB, sC }) {
  return (
    <div style={{
      background: 'rgba(21,25,37,0.95)',
      border: '1px solid #10b98140',
      borderRadius: 10,
      padding: '12px 14px',
      backdropFilter: 'blur(12px)',
      boxShadow: '0 8px 32px rgba(0,0,0,0.5)',
      minWidth: 180,
      ...sx,
    }}>
      <div style={{ fontSize: 10, color: '#64748b', fontWeight: 700, textTransform: 'uppercase', letterSpacing: 1, marginBottom: 8 }}>{label}</div>
      {[[sA||'A', 78, '#10b981'], [sB||'B', 52, '#3b82f6'], [sC||'C', 31, '#f59e0b']].map(([lbl, pct, col]) => (
        <div key={lbl} style={{ marginBottom: 6 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 3 }}>
            <span style={{ fontSize: 11, color: '#94a3b8' }}>{lbl}</span>
            <span style={{ fontSize: 11, color: col, fontWeight: 700 }}>{pct}%</span>
          </div>
          <div style={{ height: 3, borderRadius: 2, background: '#1e293b' }}>
            <div style={{ height: '100%', width: `${pct}%`, borderRadius: 2, background: col }}/>
          </div>
        </div>
      ))}
    </div>
  );
}

const HERO_LABELS = {
  en: { sites: 'Active sites', events: 'Events today', progress: 'Site progress', secA: 'Section A', secB: 'Section B', secC: 'Section C', liveLabel: 'LIVE', alertLabel: 'Critical deviation', alertTitle: 'Cement delivery delay', alertSub: 'Section A · 6 days', tgFrom: 'Site Manager', tgMsg: '📦 Rebar delivered: 20t', tgReply: '✓ Recorded in panel', statSites: '3', statEvents: '12', statLabel1: 'Active pilots', statLabel2: 'First month', statLabel3: 'Setup time' },
  uk: { sites: 'Активних об\'єктів', events: 'Подій сьогодні', progress: 'Прогрес об\'єкта', secA: 'Секція А', secB: 'Секція Б', secC: 'Секція В', liveLabel: 'LIVE', alertLabel: 'Критичне відхилення', alertTitle: 'Затримка поставки цементу', alertSub: 'Секція А · 6 днів', tgFrom: 'Нач. об\'єкта', tgMsg: '📦 Арматура доставлена: 20т', tgReply: '✓ Зафіксовано в панелі', statSites: '3', statEvents: '12', statLabel1: 'Активних пілоти', statLabel2: 'Перший місяць', statLabel3: 'Час налаштування' },
  ru: { sites: 'Активных объектов', events: 'Событий сегодня', progress: 'Прогресс объекта', secA: 'Секция А', secB: 'Секция Б', secC: 'Секция В', liveLabel: 'LIVE', alertLabel: 'Критическое отклонение', alertTitle: 'Задержка поставки цемента', alertSub: 'Секция А · 6 дней', tgFrom: 'Нач. объекта', tgMsg: '📦 Арматура доставлена: 20т', tgReply: '✓ Зафиксировано в панели', statSites: '3', statEvents: '12', statLabel1: 'Активных пилота', statLabel2: 'Первый месяц', statLabel3: 'Время настройки' },
};

function Hero({ t, lang, onCTA }) {
  const hl = HERO_LABELS[lang] || HERO_LABELS.en;
  const sceneRef = React.useRef(null);
  const mouseRef = React.useRef({ x: 0, y: 0 });
  const currentRef = React.useRef({ x: 0, y: 0 });
  const rafRef = React.useRef(null);

  // Card physics state
  const cardsRef = React.useRef([
    { x: -280, y: -80,  z: 60,  rx: 8,  ry: -15, baseX: -280, baseY: -80,  vx: 0, vy: 0, factor: 0.04 },
    { x:  200, y: -120, z: 40,  rx: -5, ry: 12,  baseX:  200, baseY: -120, vx: 0, vy: 0, factor: 0.03 },
    { x: -240, y:  80,  z: 30,  rx: 10, ry: -8,  baseX: -240, baseY:  80,  vx: 0, vy: 0, factor: 0.05 },
    { x:  220, y:  60,  z: 50,  rx: -8, ry: 10,  baseX:  220, baseY:  60,  vx: 0, vy: 0, factor: 0.035 },
    { x:   0,  y:  150, z: 20,  rx: 5,  ry: 0,   baseX:   0,  baseY:  150, vx: 0, vy: 0, factor: 0.025 },
  ]);

  const [cardPositions, setCardPositions] = React.useState(cardsRef.current.map(c => ({ ...c })));
  const [floatT, setFloatT] = React.useState(0);

  React.useEffect(() => {
    let t0 = performance.now();
    const animate = (ts) => {
      const elapsed = (ts - t0) / 1000;
      setFloatT(elapsed);

      // Smooth mouse follow
      const dx = mouseRef.current.x - currentRef.current.x;
      const dy = mouseRef.current.y - currentRef.current.y;
      currentRef.current.x += dx * 0.06;
      currentRef.current.y += dy * 0.06;

      const mx = currentRef.current.x;
      const my = currentRef.current.y;

      const cards = cardsRef.current;
      cards.forEach((c, i) => {
        // Float offset
        const floatY = Math.sin(elapsed * 0.6 + i * 1.2) * 8;
        const floatX = Math.cos(elapsed * 0.4 + i * 0.9) * 4;
        // Mouse parallax target
        const tx = c.baseX + mx * c.factor * 60 + floatX;
        const ty = c.baseY + my * c.factor * 40 + floatY;
        // Spring physics
        const springK = 0.08;
        const damping = 0.85;
        c.vx = (c.vx + (tx - c.x) * springK) * damping;
        c.vy = (c.vy + (ty - c.y) * springK) * damping;
        c.x += c.vx;
        c.y += c.vy;
        c.rx = -my * 8 + Math.sin(elapsed * 0.5 + i) * 3;
        c.ry = mx * 12 + Math.cos(elapsed * 0.4 + i) * 4;
      });

      setCardPositions(cards.map(c => ({ ...c })));
      rafRef.current = requestAnimationFrame(animate);
    };
    rafRef.current = requestAnimationFrame(animate);
    return () => cancelAnimationFrame(rafRef.current);
  }, []);

  const handleMouseMove = React.useCallback((e) => {
    const rect = sceneRef.current?.getBoundingClientRect();
    if (!rect) return;
    mouseRef.current.x = ((e.clientX - rect.left) / rect.width - 0.5) * 2;
    mouseRef.current.y = ((e.clientY - rect.top) / rect.height - 0.5) * 2;
  }, []);

  const h1Lines = t.hero.h1.split('\n');

  return (
    <section
      ref={sceneRef}
      className="hero-section"
      onMouseMove={handleMouseMove}
      onMouseLeave={() => { mouseRef.current = { x: 0, y: 0 }; }}
      style={{
        minHeight: '100vh',
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        justifyContent: 'center',
        position: 'relative',
        overflow: 'hidden',
        background: '#0f111a',
        paddingTop: 80,
      }}
    >
      {/* Background grid */}
      <div style={{
        position: 'absolute', inset: 0, zIndex: 0,
        backgroundImage: `linear-gradient(rgba(30,41,59,0.3) 1px, transparent 1px), linear-gradient(90deg, rgba(30,41,59,0.3) 1px, transparent 1px)`,
        backgroundSize: '60px 60px',
        maskImage: 'radial-gradient(ellipse 80% 60% at 50% 50%, black 40%, transparent 100%)',
      }}/>
      {/* Glow */}
      <div style={{ position: 'absolute', top: '30%', left: '50%', transform: 'translate(-50%,-50%)', width: 600, height: 400, borderRadius: '50%', background: 'radial-gradient(ellipse, rgba(59,130,246,0.12) 0%, transparent 70%)', pointerEvents: 'none', zIndex: 0 }}/>

      {/* 3D scene layer */}
      <div className="hero-3d-scene" style={{ position: 'absolute', inset: 0, perspective: '1000px', zIndex: 1, pointerEvents: 'none' }}>
        <div style={{ position: 'absolute', top: '50%', left: '50%', transformStyle: 'preserve-3d' }}>
          {/* Card 0 — Alert */}
          <div style={{ position: 'absolute', transform: `translate3d(${cardPositions[0].x}px, ${cardPositions[0].y}px, ${cardPositions[0].z}px) rotateX(${cardPositions[0].rx}deg) rotateY(${cardPositions[0].ry}deg)`, transition: 'none' }}>
            <AlertCard label={hl.alertLabel} title={hl.alertTitle} sub={hl.alertSub} />
          </div>
          {/* Card 1 — Stats */}
          <div style={{ position: 'absolute', transform: `translate3d(${cardPositions[1].x}px, ${cardPositions[1].y}px, ${cardPositions[1].z}px) rotateX(${cardPositions[1].rx}deg) rotateY(${cardPositions[1].ry}deg)` }}>
            <MiniCard label={hl.sites} value={hl.statSites} color="#3b82f6" />
          </div>
          {/* Card 2 — Telegram */}
          <div style={{ position: 'absolute', transform: `translate3d(${cardPositions[2].x}px, ${cardPositions[2].y}px, ${cardPositions[2].z}px) rotateX(${cardPositions[2].rx}deg) rotateY(${cardPositions[2].ry}deg)` }}>
            <TelegramCard from={hl.tgFrom} msg={hl.tgMsg} reply={hl.tgReply} />
          </div>
          {/* Card 3 — Progress */}
          <div style={{ position: 'absolute', transform: `translate3d(${cardPositions[3].x}px, ${cardPositions[3].y}px, ${cardPositions[3].z}px) rotateX(${cardPositions[3].rx}deg) rotateY(${cardPositions[3].ry}deg)` }}>
            <ProgressCard label={hl.progress} sA={hl.secA} sB={hl.secB} sC={hl.secC} />
          </div>
          {/* Card 4 — Events count */}
          <div style={{ position: 'absolute', transform: `translate3d(${cardPositions[4].x}px, ${cardPositions[4].y}px, ${cardPositions[4].z}px) rotateX(${cardPositions[4].rx}deg) rotateY(${cardPositions[4].ry}deg)` }}>
            <MiniCard label={hl.events} value={hl.statEvents} color="#10b981" />
          </div>
        </div>
      </div>

      {/* Hero text */}
      <div className="hero-text" style={{ position: 'relative', zIndex: 2, textAlign: 'center', maxWidth: 760, padding: '0 24px' }}>
        {/* Backdrop for readability */}
        <div style={{ position: 'absolute', inset: '-40px -60px', background: 'radial-gradient(ellipse 80% 100% at 50% 50%, rgba(15,17,26,0.85) 40%, transparent 100%)', pointerEvents: 'none', zIndex: -1 }}/>
        <div style={{
          display: 'inline-flex', alignItems: 'center', gap: 8,
          background: 'rgba(225,29,72,0.12)', border: '1px solid rgba(225,29,72,0.3)',
          borderRadius: 20, padding: '6px 16px', marginBottom: 32,
        }}>
          <div style={{ width: 6, height: 6, borderRadius: '50%', background: '#e11d48', animation: 'pulse 1.5s infinite' }}/>
          <span style={{ fontSize: 11, fontWeight: 700, color: '#e11d48', letterSpacing: 2, textTransform: 'uppercase' }}>{t.hero.badge}</span>
        </div>

        <h1 className="hero-h1" style={{ fontSize: 'clamp(48px, 8vw, 96px)', fontWeight: 900, color: '#e2e8f0', lineHeight: 1.0, marginBottom: 12, letterSpacing: '-2px', fontFamily: "'Outfit', sans-serif" }}>
          {h1Lines.map((line, i) => <div key={i}>{line}</div>)}
        </h1>
        <h2 className="hero-h2" style={{ fontSize: 'clamp(20px, 3vw, 32px)', fontWeight: 400, color: '#3b82f6', marginBottom: 24, fontFamily: "'Outfit', sans-serif" }}>
          {t.hero.h2}
        </h2>
        <p className="hero-sub" style={{ fontSize: 18, color: '#94a3b8', maxWidth: 560, margin: '0 auto 40px', lineHeight: 1.6 }}>
          {t.hero.sub}
        </p>

        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 12 }}>
          <button className="hero-cta" onClick={onCTA} style={{
            background: 'linear-gradient(135deg, #3b82f6, #2563eb)',
            color: '#fff', border: 'none', borderRadius: 12,
            padding: '18px 40px', fontSize: 17, fontWeight: 700, cursor: 'pointer',
            boxShadow: '0 8px 32px rgba(59,130,246,0.4)',
            transition: 'transform 0.15s, box-shadow 0.15s',
            fontFamily: "'DM Sans', sans-serif",
          }}
            onMouseEnter={e => { e.target.style.transform='translateY(-2px)'; e.target.style.boxShadow='0 12px 40px rgba(59,130,246,0.5)'; }}
            onMouseLeave={e => { e.target.style.transform='translateY(0)'; e.target.style.boxShadow='0 8px 32px rgba(59,130,246,0.4)'; }}
          >
            {t.hero.cta}
          </button>
          <span style={{ fontSize: 13, color: '#475569' }}>{t.hero.sub2}</span>
        </div>

        {/* Live indicator */}
        <div className="hero-stats" style={{ marginTop: 48, display: 'flex', justifyContent: 'center', gap: 32, flexWrap: 'wrap' }}>
          {[[hl.statSites, hl.statLabel1], ['$0', hl.statLabel2], ['24h', hl.statLabel3]].map(([val, lbl]) => (
            <div key={lbl} style={{ textAlign: 'center' }}>
              <div style={{ fontSize: 28, fontWeight: 900, color: '#e2e8f0', fontFamily: "'Outfit', sans-serif" }}>{val}</div>
              <div style={{ fontSize: 12, color: '#475569', marginTop: 2 }}>{lbl}</div>
            </div>
          ))}
        </div>
      </div>

      {/* Construction workers walking */}
      <div className="hero-workers" style={{ position: 'absolute', bottom: 24, left: 0, right: 0, zIndex: 3, pointerEvents: 'none', overflow: 'hidden', height: 70 }}>
        <div style={{ animation: 'walkRight 20s linear infinite', position: 'absolute', bottom: 4, left: '-60px' }}>
          <WorkerSVG />
        </div>
        <div style={{ animation: 'walkLeft 25s linear infinite', position: 'absolute', bottom: 4, right: '-60px' }}>
          <WorkerSVG flip />
        </div>
      </div>

      {/* Scroll hint */}
      <div className="hero-scroll-hint" style={{ position: 'absolute', bottom: 80, left: '50%', transform: 'translateX(-50%)', zIndex: 4, animation: 'bounce 2s infinite' }}>
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#334155" strokeWidth="2"><polyline points="6 9 12 15 18 9"/></svg>
      </div>
    </section>
  );
}

Object.assign(window, { Hero });
