// Animations: ads attracting customers + growth chart
function AdsAttractScene({ compact = false }) {
  const stageRef = React.useRef(null);
  const [customers, setCustomers] = React.useState([]);
  const [revenue, setRevenue] = React.useState(0);
  const idRef = React.useRef(0);
  const { t } = window.useI18n();

  React.useEffect(() => {
    if (!stageRef.current) return;
    const interval = setInterval(() => {
      const stage = stageRef.current;
      if (!stage) return;
      const rect = stage.getBoundingClientRect();
      const w = rect.width, h = rect.height;
      const adIndex = Math.floor(Math.random() * 3);
      const adX = w * (compact ? 0.10 : 0.12);
      const adY = h * (0.18 + adIndex * 0.30);
      const storeX = w * (compact ? 0.78 : 0.82);
      const storeY = h * 0.5;
      const id = idRef.current++;
      const value = Math.floor(40 + Math.random() * 120);
      setCustomers(prev => [...prev, { id, fromX: adX, fromY: adY, toX: storeX, toY: storeY, value }]);
      setTimeout(() => {
        setCustomers(prev => prev.filter(c => c.id !== id));
        setRevenue(r => r + value);
      }, 2400);
    }, 700);
    return () => clearInterval(interval);
  }, [compact]);

  const ads = [
    { cls: 'a1', name: 'lunaria.co', tag: 'Sponsored', cta: 'Shop now', price: '−25%' },
    { cls: 'a2', name: 'Casa·Verde', tag: 'Sponsored', cta: 'Get yours', price: 'New' },
    { cls: 'a3', name: 'Aire Studio', tag: 'Sponsored', cta: 'Shop', price: 'Free shipping' }
  ];

  return (
    <div className="ads-anim-stage" ref={stageRef}>
      <svg style={{position:'absolute', inset:0, width:'100%', height:'100%', pointerEvents:'none', opacity:0.25}} aria-hidden="true">
        <defs>
          <linearGradient id="line-grad" x1="0" x2="1">
            <stop offset="0%" stopColor="#3B6EF5" stopOpacity="0"/>
            <stop offset="50%" stopColor="#ffffff" stopOpacity="0.6"/>
            <stop offset="100%" stopColor="#ffffff" stopOpacity="0"/>
          </linearGradient>
        </defs>
      </svg>

      {ads.map((ad) => (
        <div key={ad.cls} className={`ad-card ${ad.cls}`}>
          <div className="ad-fb-bar">
            <div className="ad-fb-avatar"></div>
            <div>
              <div className="ad-fb-name">{ad.name}</div>
              <div className="ad-fb-meta">{ad.tag} · 2h</div>
            </div>
          </div>
          <div className="ad-creative"></div>
          <div className="ad-cta">
            <span>{ad.cta}</span>
            <strong>{ad.price}</strong>
          </div>
        </div>
      ))}

      {customers.map(c => (
        <div key={c.id} className="customer" style={{
          '--from-x': `${c.fromX}px`, '--from-y': `${c.fromY}px`,
          '--to-x':   `${c.toX}px`,   '--to-y':   `${c.toY}px`,
          left: 0, top: 0,
          animation: 'flyToStore 2.3s cubic-bezier(0.5,0,0.4,1) forwards'
        }}/>
      ))}

      <div className="ads-anim-store">
        <div className="store-counter" aria-live="polite">{revenue.toLocaleString('en-US')}</div>
        <div className="store-header">
          <div className="store-dot"></div>
          <div className="store-label">Live · Store</div>
        </div>
        <div className="store-product">
          <svg width="56" height="56" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1" strokeLinecap="round" strokeLinejoin="round">
            <path d="M6 2L3 6v14a2 2 0 002 2h14a2 2 0 002-2V6l-3-4z"/>
            <line x1="3" y1="6" x2="21" y2="6"/>
            <path d="M16 10a4 4 0 01-8 0"/>
          </svg>
        </div>
        <div className="store-meta"><i>Your</i> store</div>
        <div className="store-price">+{customers.length} customers · live</div>
      </div>
    </div>
  );
}

function GrowthChart() {
  const ref = React.useRef(null);
  const [progress, setProgress] = React.useState(0);
  const [inView, setInView] = React.useState(false);
  const { t } = window.useI18n();

  React.useEffect(() => {
    if (!ref.current) return;
    const obs = new IntersectionObserver(([e]) => {
      if (e.isIntersecting) { setInView(true); obs.disconnect(); }
    }, { threshold: 0.3 });
    obs.observe(ref.current);
    return () => obs.disconnect();
  }, []);

  React.useEffect(() => {
    if (!inView) return;
    let raf, start;
    const tick = (ts) => {
      if (!start) start = ts;
      const p = Math.min((ts - start) / 2400, 1);
      const eased = 1 - Math.pow(1 - p, 3);
      setProgress(eased);
      if (p < 1) raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [inView]);

  const months = ['M1','M2','M3','M4','M5','M6'];
  const before = [100, 105, 102, 108, 110, 106];
  const after  = [100, 145, 198, 248, 305, 412];
  const W = 800, H = 320, PADX = 40, PADY = 40;
  const xStep = (W - PADX*2) / (months.length - 1);
  const maxV = 420;

  const ptsAfter = after.map((v, i) => [PADX + i * xStep, H - PADY - (v / maxV) * (H - PADY*2)]);
  const ptsBefore = before.map((v, i) => [PADX + i * xStep, H - PADY - (v / maxV) * (H - PADY*2)]);

  const pathOf = (pts) => pts.map((p, i) => `${i === 0 ? 'M' : 'L'} ${p[0]} ${p[1]}`).join(' ');
  const fillOf = (pts) => `${pathOf(pts)} L ${pts[pts.length-1][0]} ${H-PADY} L ${pts[0][0]} ${H-PADY} Z`;

  const totalLen = 1400;
  const dashOffset = totalLen * (1 - progress);

  const idx = Math.floor(progress * (after.length - 1));
  const currentVal = Math.round(after[idx] * progress + after[Math.max(0, idx-1)] * (1 - progress));
  const lastPt = ptsAfter[Math.max(0, Math.min(ptsAfter.length - 1, idx))];

  return (
    <div ref={ref} className="growth-chart-wrap">
      <div className="growth-chart-header">
        <div>
          <div className="gch-title">{t('growth.chart.title')}</div>
          <div className="gch-big"><i>{currentVal}</i></div>
        </div>
        <div className="gch-pill">↗ +{Math.round(after[after.length-1] - 100)}%</div>
      </div>

      <svg viewBox={`0 0 ${W} ${H}`} className="growth-chart-svg" preserveAspectRatio="none">
        <defs>
          <linearGradient id="gc-fill" x1="0" x2="0" y1="0" y2="1">
            <stop offset="0%" stopColor="#ffffff" stopOpacity="0.3"/>
            <stop offset="100%" stopColor="#ffffff" stopOpacity="0"/>
          </linearGradient>
          <linearGradient id="gc-line" x1="0" x2="1">
            <stop offset="0%" stopColor="#3B6EF5"/>
            <stop offset="100%" stopColor="#ffffff"/>
          </linearGradient>
        </defs>

        {[0.25, 0.5, 0.75].map((p, i) => (
          <line key={i} x1={PADX} x2={W-PADX}
            y1={H-PADY - p*(H-PADY*2)} y2={H-PADY - p*(H-PADY*2)}
            stroke="rgba(245,239,224,0.05)" strokeDasharray="2 4"/>
        ))}
        {months.map((m, i) => (
          <text key={m} x={PADX + i*xStep} y={H - 12}
            fontFamily="JetBrains Mono" fontSize="10" fill="#615e59"
            textAnchor="middle">{m}</text>
        ))}

        <path d={pathOf(ptsBefore)} fill="none" stroke="#3b3935"
          strokeWidth="1.5" strokeDasharray="4 4"/>

        <path d={fillOf(ptsAfter)} fill="url(#gc-fill)" opacity={progress}/>

        <path d={pathOf(ptsAfter)} fill="none" stroke="url(#gc-line)"
          strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"
          strokeDasharray={totalLen} strokeDashoffset={dashOffset}/>

        {progress > 0.95 && (
          <g>
            <circle cx={ptsAfter[ptsAfter.length-1][0]} cy={ptsAfter[ptsAfter.length-1][1]} r="10" fill="#ffffff" opacity="0.25"/>
            <circle cx={ptsAfter[ptsAfter.length-1][0]} cy={ptsAfter[ptsAfter.length-1][1]} r="5" fill="#ffffff"/>
          </g>
        )}

        {progress > 0.05 && progress < 0.95 && (
          <circle cx={lastPt[0]} cy={lastPt[1]} r="5" fill="#ffffff"/>
        )}
      </svg>
    </div>
  );
}

window.AdsAttractScene = AdsAttractScene;
window.GrowthChart = GrowthChart;
