// Animación conceptual: qué le hace la inflación al margen de un plato
const MONTHS = ['Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dic', 'Ene', 'Feb'];
const BASE_COST = 5597, BASE_PRICE = 22000;
const INFL = [0, .035, .072, .098, .141, .186, .215, .262, .298, .331, .378, .412]; // acumulada

const InflationAnim = () => {
  const [t, setT] = React.useState(0);
  const [playing, setPlaying] = React.useState(true);
  const ref = React.useRef(null);

  // Solo corre cuando la sección está a la vista
  React.useEffect(() => {
    if (!ref.current) return;
    const io = new IntersectionObserver(([e]) => setPlaying(e.isIntersecting), { threshold: 0.25 });
    io.observe(ref.current);
    return () => io.disconnect();
  }, []);

  React.useEffect(() => {
    if (!playing) return;
    const id = setInterval(() => setT(v => (v + 0.045) % 12), 90);
    return () => clearInterval(id);
  }, [playing]);

  const i = Math.min(11, Math.floor(t));
  const f = t - i;
  const infl = INFL[i] + (INFL[Math.min(11, i + 1)] - INFL[i]) * f;
  const costo = BASE_COST * (1 + infl);

  // Sin control: el precio de carta nunca se toca
  const fcSin = (costo / BASE_PRICE) * 100;

  // Con Gajo: cuando la alerta salta (>30%), se reajusta el precio
  const priceAt = (upTo) => {
    let p = BASE_PRICE, n = 0;
    for (let k = 0; k <= upTo; k++) {
      if ((BASE_COST * (1 + INFL[k]) / p) * 100 > 29.5) {
        p = Math.ceil((BASE_COST * (1 + INFL[k])) / 0.25 / 500) * 500;
        n++;
      }
    }
    return { price: p, fired: n };
  };
  const { price: priceCon, fired } = priceAt(i);
  const fcCon = (costo / priceCon) * 100;
  const justFired = ((BASE_COST * (1 + INFL[i]) / priceCon) * 100) > 29.5;

  // Cifra de cierre: fija al mes 12, no al frame actual
  const costo12 = BASE_COST * (1 + INFL[11]);
  const gap12 = priceAt(11).price - BASE_PRICE;

  return (
    <section ref={ref} id="por-que" style={{ background: 'var(--primary)', color: '#fff' }}>
      <div className="container">
        <div style={{ maxWidth: 760, marginBottom: 48 }}>
          <div className="eyebrow" style={{ color: 'rgba(255,255,255,.55)', marginBottom: 16 }}>Por qué importa</div>
          <h2 className="display" style={{ fontSize: 'clamp(34px, 4.4vw, 54px)', margin: '0 0 20px' }}>
            No sube el plato. <em style={{ color: 'var(--accent-soft)' }}>Sube el costo.</em>
          </h2>
          <p className="body-lg" style={{ color: 'rgba(255,255,255,.78)' }}>
            Un mismo plato, doce meses, sin cambiar ni un gramo de la receta. A la izquierda nadie mira la incidencia.
            A la derecha, el sistema avisa cuando se pasa de 30% y el precio se reajusta a tiempo.
          </p>
        </div>

        <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 20, flexWrap: 'wrap' }}>
          <div style={{
            fontFamily: 'var(--mono)', fontSize: 12, padding: '5px 11px',
            background: 'rgba(255,255,255,.10)', borderRadius: 6, letterSpacing: '.04em',
          }}>{MONTHS[i]} · inflación de insumos acumulada {(infl * 100).toFixed(1)}%</div>
          <div style={{ flex: 1, minWidth: 120, height: 3, background: 'rgba(255,255,255,.14)', borderRadius: 2, overflow: 'hidden' }}>
            <div style={{ width: (t / 12 * 100) + '%', height: '100%', background: 'var(--accent-soft)' }}/>
          </div>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 18 }} className="infl-grid">
          <Lane title="Sin control" sub="Precio de carta congelado" price={BASE_PRICE} costo={costo} fc={fcSin} dim/>
          <Lane title={`Con ${BRAND.name}`} sub={fired ? `${fired} reajuste${fired > 1 ? 's' : ''} a tiempo` : 'Vigilando la incidencia'}
                price={priceCon} costo={costo} fc={fcCon} alert={justFired}/>
        </div>

        <div style={{
          marginTop: 24, paddingTop: 20, borderTop: '1px solid rgba(255,255,255,.12)',
          display: 'flex', gap: 32, flexWrap: 'wrap', alignItems: 'flex-end',
        }}>
          <div>
            <div className="eyebrow" style={{ color: 'rgba(255,255,255,.5)', marginBottom: 6 }}>Diferencia de contribución al mes 12</div>
            <div className="display" style={{ fontSize: 40, color: 'var(--accent-soft)', lineHeight: 1 }}>
              {ars(gap12)} <span style={{ fontSize: 18, color: 'rgba(255,255,255,.6)' }}>por plato vendido</span>
            </div>
          </div>
          <div className="small" style={{ color: 'rgba(255,255,255,.5)', fontSize: 12, maxWidth: 320 }}>
            Ejemplo ilustrativo con un plato de entrada. Costo base {ars(BASE_COST)}, margen objetivo 25%.
            Al mes 12 el costo llega a {ars(costo12)}.
          </div>
        </div>
      </div>
      <style>{`@media (max-width:820px){.infl-grid{grid-template-columns:1fr !important}}@media (max-width:560px){.infl-lane{padding:18px !important}.infl-fc{font-size:42px !important}}`}</style>
    </section>
  );
};

const Lane = ({ title, sub, price, costo, fc, dim, alert }) => {
  const s = semaforo(fc);
  const costPct = Math.min(100, (costo / price) * 100);
  return (
    <div className="infl-lane" style={{
      background: 'rgba(255,255,255,.055)',
      border: '1px solid ' + (alert ? 'var(--accent-soft)' : 'rgba(255,255,255,.11)'),
      borderRadius: 'var(--radius-lg)', padding: 22,
      transition: 'border-color 300ms ease',
    }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 18, gap: 10 }}>
        <div>
          <div style={{ fontFamily: 'var(--serif)', fontSize: 24, lineHeight: 1.1 }}>{title}</div>
          <div style={{ fontSize: 12, color: 'rgba(255,255,255,.58)', marginTop: 3 }}>{sub}</div>
        </div>
        {alert && (
          <div style={{
            display: 'flex', alignItems: 'center', gap: 6, padding: '4px 9px',
            background: 'var(--accent)', borderRadius: 999, fontSize: 10.5,
            fontFamily: 'var(--mono)', whiteSpace: 'nowrap', animation: 'fadeInUp 260ms ease',
          }}>
            <Icon.Bell size={11}/>Alerta
          </div>
        )}
      </div>

      <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, marginBottom: 12 }}>
        <div className="ticker infl-fc" style={{
          fontFamily: 'var(--serif)', fontSize: 52, lineHeight: 1,
          color: dim ? (fc > 35 ? '#EE8A7C' : fc > 30 ? '#F0C173' : '#8FD0AA') : '#8FD0AA',
        }}>{fc.toFixed(1)}%</div>
        <div style={{ fontSize: 12, color: 'rgba(255,255,255,.55)', fontFamily: 'var(--mono)' }}>
          incidencia<br/>
          <span style={{ color: fc > 35 ? '#EE8A7C' : fc > 30 ? '#F0C173' : '#8FD0AA' }}>{s.label}</span>
        </div>
      </div>

      {/* Barra: costo vs contribución sobre el precio de carta */}
      <div style={{ height: 30, borderRadius: 6, overflow: 'hidden', display: 'flex', background: 'rgba(255,255,255,.09)', marginBottom: 8 }}>
        <div style={{
          width: costPct + '%', background: fc > 35 ? '#B8483A' : fc > 30 ? '#C08A32' : 'var(--accent)',
          transition: 'width 140ms linear, background 400ms ease',
        }}/>
        <div style={{ flex: 1, background: 'rgba(143,208,170,.30)' }}/>
      </div>
      <div style={{ display: 'flex', justifyContent: 'space-between', fontFamily: 'var(--mono)', fontSize: 10.5, color: 'rgba(255,255,255,.62)' }}>
        <span>costo {ars(costo)}</span>
        <span>contrib. {ars(price - costo)}</span>
      </div>

      <div style={{
        marginTop: 16, paddingTop: 14, borderTop: '1px solid rgba(255,255,255,.10)',
        display: 'flex', justifyContent: 'space-between', fontSize: 12,
      }}>
        <span style={{ color: 'rgba(255,255,255,.58)' }}>Precio en carta</span>
        <span style={{ fontFamily: 'var(--mono)', fontWeight: 600 }}>{ars(price)}</span>
      </div>
    </div>
  );
};

window.InflationAnim = InflationAnim;
