/* Gaung.ai — Office Scene Animation
   An animated cross-section of a Gaung office at night: 3 workstations lit by monitor glow,
   a lead flowing across the scene from a phone to WhatsApp bubbles to the dashboard,
   subtle window reflections, ambient particle 'signal' pings, plants, coffee.
   All SVG + React, no figurative people (simple iconographic heads/torsos only).
*/

function OfficeScene() {
  const [tick, setTick] = useState(0);
  const rafRef = useRef(null);

  useEffect(() => {
    let start = performance.now();
    const loop = (now) => {
      setTick((now - start) / 1000);
      rafRef.current = requestAnimationFrame(loop);
    };
    rafRef.current = requestAnimationFrame(loop);
    return () => cancelAnimationFrame(rafRef.current);
  }, []);

  const t = tick;

  // Helpers
  const typedText = (msg, speed = 14, delay = 0, loop = 8) => {
    const localT = (t - delay) % loop;
    if (localT < 0) return '';
    const chars = Math.max(0, Math.min(msg.length, Math.floor(localT * speed)));
    return msg.slice(0, chars);
  };
  const blinkingCaret = () => (Math.floor(t * 2) % 2) ? '▍' : ' ';

  // Lead-flow dot position (travels across screens over 6s)
  const flowT = (t % 6) / 6; // 0..1
  const easeInOut = x => x < 0.5 ? 2*x*x : 1 - Math.pow(-2*x + 2, 2)/2;
  const fT = easeInOut(flowT);
  // path from station 1 (x=210,y=285) -> station 2 (x=500,y=285) -> station 3 (x=790,y=285)
  const flowX = 210 + fT * 580;
  const flowY = 285 + Math.sin(flowT * Math.PI * 2) * 18;

  // Subtle breathing on screens
  const breath = (offset=0) => 0.85 + 0.15 * Math.sin(t * 1.2 + offset);

  return (
    <div style={{position:'relative',borderRadius:16,overflow:'hidden',border:'1px solid var(--line)',background:'linear-gradient(180deg, oklch(96% 0.01 60) 0%, oklch(92% 0.015 60) 100%)'}}>
      <svg viewBox="0 0 1000 500" width="100%" style={{display:'block'}} preserveAspectRatio="xMidYMid slice">
        <defs>
          <linearGradient id="skyGrad" x1="0" x2="0" y1="0" y2="1">
            <stop offset="0" stopColor="#ffe4d0"/>
            <stop offset="0.5" stopColor="#ffd0e4"/>
            <stop offset="1" stopColor="#fff4ea"/>
          </linearGradient>
          <linearGradient id="screenGlow" x1="0" x2="0" y1="0" y2="1">
            <stop offset="0" stopColor="#1a1a1f"/>
            <stop offset="1" stopColor="#2a1030"/>
          </linearGradient>
          <linearGradient id="floorGrad" x1="0" x2="0" y1="0" y2="1">
            <stop offset="0" stopColor="oklch(88% 0.01 60)"/>
            <stop offset="1" stopColor="oklch(82% 0.01 60)"/>
          </linearGradient>
          <linearGradient id="brand" x1="0" x2="1">
            <stop offset="0" stopColor="#ea008c"/>
            <stop offset="1" stopColor="#ff8a10"/>
          </linearGradient>
          <radialGradient id="monitorLight" cx="0.5" cy="0.3" r="0.7">
            <stop offset="0" stopColor="#ff8a10" stopOpacity="0.35"/>
            <stop offset="1" stopColor="#ff8a10" stopOpacity="0"/>
          </radialGradient>
          <radialGradient id="monitorLight2" cx="0.5" cy="0.3" r="0.7">
            <stop offset="0" stopColor="#ea008c" stopOpacity="0.3"/>
            <stop offset="1" stopColor="#ea008c" stopOpacity="0"/>
          </radialGradient>
        </defs>

        {/* Window wall */}
        <rect x="0" y="0" width="1000" height="340" fill="url(#skyGrad)"/>

        {/* Distant city silhouette */}
        <g opacity="0.35">
          {[30, 110, 180, 260, 340, 420, 520, 620, 700, 790, 870, 960].map((x, i) => {
            const h = 40 + ((i * 37) % 80);
            return <rect key={i} x={x} y={340 - h} width={40 + ((i*13)%20)} height={h} fill="oklch(65% 0.02 60)"/>;
          })}
        </g>

        {/* Window frames */}
        <g stroke="oklch(60% 0.01 60)" strokeWidth="2" fill="none">
          <line x1="0" y1="50" x2="1000" y2="50"/>
          <line x1="0" y1="340" x2="1000" y2="340"/>
          {[200, 400, 600, 800].map((x,i)=><line key={i} x1={x} y1="50" x2={x} y2="340"/>)}
        </g>

        {/* Sun / orb — slow drift */}
        <circle cx={780 + Math.sin(t*0.15)*8} cy={160 + Math.cos(t*0.2)*4} r="44" fill="#ff8a10" opacity="0.35"/>
        <circle cx={780 + Math.sin(t*0.15)*8} cy={160 + Math.cos(t*0.2)*4} r="26" fill="#ff8a10" opacity="0.6"/>

        {/* Floor */}
        <rect x="0" y="340" width="1000" height="160" fill="url(#floorGrad)"/>
        <line x1="0" y1="340" x2="1000" y2="340" stroke="oklch(70% 0.01 60)" strokeWidth="1"/>

        {/* Ambient ground-light pools from monitors */}
        {[210, 500, 790].map((cx, i) => (
          <ellipse key={i} cx={cx} cy="400" rx="130" ry="30" fill={i === 1 ? 'url(#monitorLight2)' : 'url(#monitorLight)'} opacity={breath(i*1.1)}/>
        ))}

        {/* --- Station 1: Lead Gen operator --- */}
        <Workstation
          x={210} y={340}
          screenTitle="Lead Gen Engine"
          screenAccent="#ff8a10"
          headTilt={Math.sin(t*0.6)*3}
          armPulse={t}
          screenBlink={breath(0)}
        >
          <ScreenContent kind="leadgen" t={t}/>
        </Workstation>

        {/* --- Station 2: Conversation Engine --- */}
        <Workstation
          x={500} y={340}
          screenTitle="Conversation Engine"
          screenAccent="#ea008c"
          headTilt={Math.sin(t*0.7 + 2)*3}
          armPulse={t + 1}
          screenBlink={breath(1.5)}
        >
          <ScreenContent kind="chat" t={t} typedText={typedText} blinkingCaret={blinkingCaret}/>
        </Workstation>

        {/* --- Station 3: Analytics --- */}
        <Workstation
          x={790} y={340}
          screenTitle="Analytics"
          screenAccent="#ff8a10"
          headTilt={Math.sin(t*0.5 + 4)*3}
          armPulse={t + 2}
          screenBlink={breath(3)}
        >
          <ScreenContent kind="analytics" t={t}/>
        </Workstation>

        {/* Data lead flow: particle traveling through the system */}
        <g>
          {[0, 0.15, 0.3].map((offset, i) => {
            const lt = (t + offset*6) % 6;
            const ltN = easeInOut(lt / 6);
            const lx = 210 + ltN * 580;
            const ly = 285 + Math.sin(ltN * Math.PI * 2.2 + offset*4) * 22;
            const opacity = 1 - Math.abs(ltN - 0.5) * 1.2;
            return (
              <g key={i} opacity={Math.max(0, opacity)}>
                <circle cx={lx} cy={ly} r="4" fill="url(#brand)"/>
                <circle cx={lx} cy={ly} r="10" fill="url(#brand)" opacity="0.25"/>
              </g>
            );
          })}
        </g>

        {/* Floating signal pings above monitors */}
        {[{cx:210, d:0}, {cx:500, d:1.7}, {cx:790, d:3.4}].map((p, i) => {
          const localT = (t + p.d) % 5;
          const r = localT * 10;
          const op = Math.max(0, 1 - localT/2.5);
          return (
            <circle key={i} cx={p.cx} cy="212" r={r} fill="none" stroke={i%2 ? '#ea008c' : '#ff8a10'} strokeWidth="1.2" opacity={op*0.4}/>
          );
        })}

        {/* Plants in corners */}
        <Plant x={60} y={400}/>
        <Plant x={940} y={400} flip/>

        {/* Coffee cups */}
        <CoffeeCup x={140} y={345} steamT={t}/>
        <CoffeeCup x={850} y={345} steamT={t + 2}/>

        {/* Floor reflection of logo/brand */}
        <text x="500" y="480" textAnchor="middle" fontFamily="Inter, sans-serif" fontSize="11" fill="oklch(55% 0.01 60)" letterSpacing="4">
          GAUNG.AI · 03:14 AM · SYSTEM ONLINE
        </text>

        {/* Clock on wall */}
        <g transform="translate(40, 120)">
          <circle cx="0" cy="0" r="22" fill="#fff" stroke="oklch(60% 0.01 60)" strokeWidth="1.5"/>
          <line x1="0" y1="0" x2={Math.cos(t*0.4 - Math.PI/2)*14} y2={Math.sin(t*0.4 - Math.PI/2)*14} stroke="#1a1a1f" strokeWidth="1.5"/>
          <line x1="0" y1="0" x2={Math.cos(t*0.05 - Math.PI/2)*9} y2={Math.sin(t*0.05 - Math.PI/2)*9} stroke="#1a1a1f" strokeWidth="2"/>
          <circle cx="0" cy="0" r="2" fill="#ea008c"/>
        </g>

      </svg>

      {/* Caption overlay */}
      <div style={{position:'absolute',bottom:20,left:24,right:24,display:'flex',justifyContent:'space-between',alignItems:'flex-end',pointerEvents:'none'}}>
        <div>
          <div style={{fontFamily:'var(--serif)',fontSize:22,fontStyle:'italic',color:'var(--ink)',lineHeight:1.1}}>
            Orkestrasi pukul tiga pagi.
          </div>
          <div style={{fontSize:13,color:'var(--ink-2)',marginTop:4,maxWidth:400}}>
            Tiga engine. Satu pipeline. Leads yang mengalir bahkan saat tim Anda sedang tidur.
          </div>
        </div>
        <div style={{display:'flex',gap:6,alignItems:'center',padding:'6px 12px',background:'oklch(16% 0.012 70 / 0.08)',backdropFilter:'blur(10px)',borderRadius:99,fontSize:11,color:'var(--ink)',fontWeight:500,letterSpacing:'.04em'}}>
          <span style={{width:7,height:7,borderRadius:99,background:'#51cf66',animation:'pulse 1.4s infinite'}}/>
          LIVE
        </div>
      </div>
      <style>{`
        @keyframes pulse { 0%,100% { opacity: 1 } 50% { opacity: 0.4 } }
      `}</style>
    </div>
  );
}

// ---- Workstation (monitor + desk + chair + figure) ----
function Workstation({ x, y, children, screenTitle, screenAccent, headTilt, armPulse, screenBlink }) {
  return (
    <g transform={`translate(${x}, ${y})`}>
      {/* Desk */}
      <rect x="-100" y="0" width="200" height="8" fill="oklch(55% 0.02 60)"/>
      <rect x="-100" y="8" width="200" height="3" fill="oklch(38% 0.02 60)"/>
      {/* Desk legs */}
      <rect x="-95" y="11" width="4" height="50" fill="oklch(30% 0.01 60)"/>
      <rect x="91" y="11" width="4" height="50" fill="oklch(30% 0.01 60)"/>

      {/* Monitor stand */}
      <rect x="-4" y="-28" width="8" height="28" fill="oklch(45% 0.01 60)"/>
      <rect x="-20" y="-30" width="40" height="4" rx="2" fill="oklch(35% 0.01 60)"/>

      {/* Monitor */}
      <rect x="-90" y="-120" width="180" height="92" rx="6" fill="#0f0f14" opacity={screenBlink}/>
      <rect x="-85" y="-116" width="170" height="80" rx="3" fill="url(#screenGlow)"/>

      {/* Monitor chrome */}
      <rect x="-90" y="-34" width="180" height="6" fill="#1a1a1f"/>

      {/* Screen content (from child) */}
      <g clipPath={`url(#clip-${x})`}>
        <g transform="translate(-85, -116)">
          {children}
        </g>
      </g>
      <defs>
        <clipPath id={`clip-${x}`}>
          <rect x="-85" y="-116" width="170" height="80" rx="3"/>
        </clipPath>
      </defs>

      {/* Screen accent strip */}
      <rect x="-85" y="-116" width="170" height="2" fill={screenAccent}/>

      {/* Figure (simple, iconographic) */}
      <g transform={`translate(0, 40)`}>
        {/* Chair back */}
        <rect x="-30" y="-10" width="60" height="40" rx="6" fill="oklch(32% 0.015 40)"/>
        {/* Torso */}
        <path d={`M-28 5 Q-28 -15 -10 -18 Q0 -20 10 -18 Q28 -15 28 5 L28 30 L-28 30 Z`} fill={screenAccent} opacity="0.85"/>
        {/* Head */}
        <g transform={`translate(0, -28) rotate(${headTilt})`}>
          <circle cx="0" cy="0" r="12" fill="oklch(72% 0.04 50)"/>
          {/* Hair */}
          <path d="M-12 -2 Q-12 -14 0 -14 Q12 -14 12 -2 L10 0 L-10 0 Z" fill="oklch(22% 0.02 40)"/>
        </g>
        {/* Arms — slight typing motion */}
        <g>
          <rect x="-22" y="-2" width="12" height={18 + Math.sin(armPulse*3)*2} rx="4" fill={screenAccent} opacity="0.75"/>
          <rect x="10" y="-2" width="12" height={18 + Math.cos(armPulse*3)*2} rx="4" fill={screenAccent} opacity="0.75"/>
        </g>
      </g>

      {/* Station label */}
      <text x="0" y="78" textAnchor="middle" fontFamily="JetBrains Mono, monospace" fontSize="9" fill="oklch(50% 0.01 60)" letterSpacing="1">
        {screenTitle.toUpperCase()}
      </text>
    </g>
  );
}

// ---- Screen content variants ----
function ScreenContent({ kind, t, typedText, blinkingCaret }) {
  if (kind === 'leadgen') {
    // Scrolling table of leads
    const offset = (t * 18) % 20;
    const leads = ['PT Merdeka Abadi', 'CV Nusantara Raya', 'Sumber Makmur Ltd', 'Griya Arta Tbk', 'Bintang Selaras', 'Harmoni Karya', 'Duta Pharma', 'Sekawan Logistik'];
    return (
      <g>
        {/* Header bar */}
        <rect x="0" y="0" width="170" height="10" fill="#1f1020"/>
        <circle cx="4" cy="5" r="1.5" fill="#ff6b6b"/>
        <circle cx="8" cy="5" r="1.5" fill="#ffd166"/>
        <circle cx="12" cy="5" r="1.5" fill="#51cf66"/>
        <text x="85" y="7.5" textAnchor="middle" fontSize="5" fill="#ff8a10" fontFamily="JetBrains Mono, monospace">leadgen / sweep</text>

        {/* Table rows */}
        <g transform={`translate(0, ${14 - offset})`}>
          {leads.concat(leads).map((name, i) => (
            <g key={i} transform={`translate(0, ${i * 9})`}>
              <rect x="4" y="0" width="162" height="7" fill={i%2 ? '#1f1a25' : 'transparent'}/>
              <circle cx="8" cy="3.5" r="1.5" fill={i%3 === 0 ? '#ff8a10' : '#51cf66'}/>
              <text x="12" y="5" fontSize="4.5" fill="#e8e0d6" fontFamily="Inter, sans-serif">{name}</text>
              <text x="130" y="5" fontSize="4.5" fill="#8a8a9e" fontFamily="JetBrains Mono, monospace">{40 + i*3}% match</text>
            </g>
          ))}
        </g>
        {/* Footer count */}
        <rect x="0" y="74" width="170" height="6" fill="#1f1020"/>
        <text x="4" y="78.5" fontSize="4.5" fill="#ff8a10" fontFamily="JetBrains Mono, monospace">
          {2847 + Math.floor(t * 3)} leads · 40 sources · live
        </text>
      </g>
    );
  }

  if (kind === 'chat') {
    const messages = [
      { who: 'them', text: 'Selamat malam, bisa info produk?' },
      { who: 'us', text: 'Halo Pak Budi, saya Aria dari tim Anda. Bisa saya bantu?' },
      { who: 'them', text: 'Butuh 200 unit bulan depan' },
    ];
    const typed = typedText('Baik, saya buatkan proposal dalam 5 menit.', 18, 0, 9);
    return (
      <g>
        {/* Header */}
        <rect x="0" y="0" width="170" height="10" fill="#1f0a18"/>
        <circle cx="6" cy="5" r="2.5" fill="#ea008c"/>
        <text x="12" y="6.5" fontSize="5" fill="#f0e8e8" fontFamily="Inter, sans-serif" fontWeight="600">Budi S. · PT Merdeka</text>
        <text x="164" y="6.5" textAnchor="end" fontSize="4" fill="#ea008c" fontFamily="JetBrains Mono, monospace">HOT</text>

        {/* Messages */}
        {messages.map((m, i) => (
          <g key={i} transform={`translate(0, ${14 + i*14})`}>
            {m.who === 'them' ? (
              <>
                <rect x="4" y="0" width={m.text.length*1.9 + 4} height="10" rx="3" fill="#2a2030"/>
                <text x="6" y="6.5" fontSize="4.5" fill="#e8e0d6" fontFamily="Inter, sans-serif">{m.text}</text>
              </>
            ) : (
              <>
                <rect x={166 - (m.text.length*1.9 + 4)} y="0" width={m.text.length*1.9 + 4} height="10" rx="3" fill="url(#brand)"/>
                <text x={164} y="6.5" textAnchor="end" fontSize="4.5" fill="#fff" fontFamily="Inter, sans-serif">{m.text}</text>
              </>
            )}
          </g>
        ))}

        {/* Typing reply */}
        <g transform="translate(0, 56)">
          <rect x={166 - (typed.length*1.9 + 6)} y="0" width={typed.length*1.9 + 6} height="10" rx="3" fill="url(#brand)"/>
          <text x={164} y="6.5" textAnchor="end" fontSize="4.5" fill="#fff" fontFamily="Inter, sans-serif">{typed}{blinkingCaret()}</text>
        </g>

        {/* AI badge */}
        <rect x="4" y="72" width="30" height="6" rx="1.5" fill="#ea008c" opacity="0.2"/>
        <text x="19" y="76.5" textAnchor="middle" fontSize="3.5" fill="#ea008c" fontFamily="JetBrains Mono, monospace" fontWeight="600">AI · AUTO</text>
      </g>
    );
  }

  if (kind === 'analytics') {
    // Animated bar chart
    const bars = Array.from({length: 12}, (_, i) => {
      const h = 10 + Math.sin(t * 0.8 + i * 0.5) * 6 + (i*3);
      return Math.min(50, Math.max(6, h));
    });
    return (
      <g>
        {/* Header */}
        <rect x="0" y="0" width="170" height="10" fill="#1f1a10"/>
        <text x="4" y="6.5" fontSize="5" fill="#ff8a10" fontFamily="Inter, sans-serif" fontWeight="600">Pipeline · 7 hari</text>
        <text x="164" y="6.5" textAnchor="end" fontSize="4.5" fill="#51cf66" fontFamily="JetBrains Mono, monospace">↑ 12.4%</text>

        {/* KPI line */}
        <text x="4" y="22" fontSize="10" fill="#f0e8e8" fontFamily="Inter, sans-serif" fontWeight="500">Rp 4,2B</text>
        <text x="40" y="22" fontSize="4" fill="#8a8a9e" fontFamily="JetBrains Mono, monospace">pipeline value</text>

        {/* Bars */}
        <g transform="translate(4, 72)">
          {bars.map((h, i) => (
            <rect key={i} x={i*13.5} y={-h} width={10} height={h} rx="1" fill={i === 11 ? '#ea008c' : '#ff8a10'} opacity={i === 11 ? 1 : 0.8}/>
          ))}
        </g>

        {/* Trendline */}
        <path d={`M4 45 Q45 40 85 32 T166 22`} stroke="#51cf66" strokeWidth="1.2" fill="none" opacity="0.8"/>
      </g>
    );
  }

  return null;
}

function Plant({ x, y, flip }) {
  return (
    <g transform={`translate(${x}, ${y}) ${flip ? 'scale(-1, 1)' : ''}`}>
      {/* Pot */}
      <path d="M-18 0 L-14 24 L14 24 L18 0 Z" fill="oklch(40% 0.03 40)"/>
      <rect x="-19" y="-2" width="38" height="4" rx="1" fill="oklch(35% 0.03 40)"/>
      {/* Leaves */}
      <path d="M0 0 Q-18 -20 -22 -45 Q-10 -30 0 0" fill="oklch(45% 0.1 140)"/>
      <path d="M0 0 Q-5 -22 5 -48 Q8 -25 0 0" fill="oklch(50% 0.12 140)"/>
      <path d="M0 0 Q12 -18 18 -40 Q10 -22 0 0" fill="oklch(42% 0.1 140)"/>
    </g>
  );
}

function CoffeeCup({ x, y, steamT }) {
  return (
    <g transform={`translate(${x}, ${y})`}>
      {/* Cup */}
      <path d="M-8 0 L-9 16 Q-9 19 -6 19 L6 19 Q9 19 9 16 L8 0 Z" fill="#fff" stroke="oklch(55% 0.01 60)" strokeWidth="0.8"/>
      <path d="M8 4 Q13 4 13 9 Q13 14 8 14" stroke="oklch(55% 0.01 60)" strokeWidth="0.8" fill="none"/>
      <ellipse cx="0" cy="0" rx="8" ry="2" fill="#4a2818"/>
      {/* Steam */}
      {[0, 1, 2].map(i => {
        const st = (steamT + i * 0.6) % 2;
        const op = Math.max(0, 1 - st / 1.5);
        const y = -st * 20;
        const x = Math.sin((steamT + i) * 2) * 3;
        return <circle key={i} cx={x} cy={y - 4} r="2" fill="oklch(85% 0.01 60)" opacity={op*0.5}/>;
      })}
    </g>
  );
}

Object.assign(window, { OfficeScene, Workstation, ScreenContent, Plant, CoffeeCup });
