// El sistema en uso: la cadena real desde la factura hasta la carta
const STEPS = [
  { k: 'factura', nav: 'Facturas', path: 'compras / facturas', label: 'Cargás la factura', desc: 'Le sacás una foto con el celular o subís la imagen o el PDF desde la PC. El sistema la compara contra la orden de compra y marca las diferencias: no entregado, cantidad menor, precio distinto o item agregado.' },
  { k: 'insumo', nav: 'Insumos', path: 'compras / insumos', label: 'Los insumos se actualizan', desc: 'Cada insumo toma el precio nuevo y guarda el histórico. Si el aumento es atípico queda señalado, y sabés qué proveedor te lo movió.' },
  { k: 'receta', nav: 'Recetas', path: 'cocina / recetas', label: 'Las recetas se recalculan', desc: 'Todas las fichas que usan ese insumo se recostean solas — incluidas las elaboraciones intermedias. No tocás una planilla.' },
  { k: 'carta', nav: 'Carta', path: 'cocina / carta', label: 'La carta te avisa', desc: 'Los platos que se pasaron del margen objetivo cambian de semáforo. Ves qué reajustar antes del cierre de mes, no después.' },
];

const SystemAnim = () => {
  const [step, setStep] = React.useState(0);
  const [playing, setPlaying] = React.useState(false);
  const ref = React.useRef(null);

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

  React.useEffect(() => {
    if (!playing) return;
    const id = setInterval(() => setStep(s => (s + 1) % STEPS.length), 4200);
    return () => clearInterval(id);
  }, [playing, step]);

  const cur = STEPS[step];

  return (
    <section ref={ref} id="sistema" style={{ background: 'var(--bg-soft)', borderTop: '1px solid var(--line)', borderBottom: '1px solid var(--line)' }}>
      <div className="container">
        <SectionHead eyebrow="El sistema en acción"
          title={<>Una factura entra. <em>Toda la carta se entera.</em></>}
          blurb={`Esta es la cadena que hace ${BRAND.name} cada vez que cargás una compra. Cuatro pasos, sin intervención manual.`}/>

        <div className="sys-grid" style={{ display: 'grid', gridTemplateColumns: '300px 1fr', gap: 32, alignItems: 'start' }}>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            {STEPS.map((s, i) => {
              const on = i === step;
              return (
                <button key={s.k} onClick={() => setStep(i)} className="sys-step" style={{
                  textAlign: 'left', border: '1px solid ' + (on ? 'var(--primary)' : 'var(--line)'),
                  background: on ? 'var(--bg-card)' : 'transparent', cursor: 'pointer',
                  borderRadius: 'var(--radius-md)', padding: '14px 16px', fontFamily: 'var(--sans)',
                  transition: 'all 180ms ease', position: 'relative', overflow: 'hidden',
                }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 9, marginBottom: on ? 7 : 0 }}>
                    <span style={{
                      width: 20, height: 20, borderRadius: '50%', flexShrink: 0,
                      background: on ? 'var(--accent)' : 'var(--line-strong)', color: '#fff',
                      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                      fontFamily: 'var(--mono)', fontSize: 10, fontWeight: 500,
                    }}>{i + 1}</span>
                    <span style={{ fontSize: 14.5, fontWeight: 500, color: on ? 'var(--ink)' : 'var(--ink-muted)' }}>{s.label}</span>
                  </div>
                  {on && (
                    <>
                      <p className="body" style={{ fontSize: 13, margin: '0 0 0 29px', lineHeight: 1.5 }}>{s.desc}</p>
                      <div style={{ position: 'absolute', left: 0, bottom: 0, height: 2, background: 'var(--accent)', animation: 'grow 4.2s linear' }}/>
                    </>
                  )}
                </button>
              );
            })}
          </div>

          <AppWindow design={620} path={BRAND.domain + ' / ' + cur.path}>
            <div style={{ display: 'flex', minHeight: 430 }}>
              <AppSidebar active={cur.nav} compact/>
              <div style={{ flex: 1, padding: 18, background: 'var(--bg)', minWidth: 0 }}>
                {step === 0 && <FacturasScreen/>}
                {step === 1 && <InsumosScreen/>}
                {step === 2 && <RecetasScreen/>}
                {step === 3 && <CartaScreen/>}
              </div>
            </div>
          </AppWindow>
        </div>
      </div>
      <style>{`
        @keyframes grow { from { width: 0 } to { width: 100% } }
        @media (max-width: 940px){ .sys-grid { grid-template-columns: 1fr !important } }
        @media (max-width: 560px){ .sys-step { padding: 12px 13px !important } }
      `}</style>
    </section>
  );
};

const th = { fontFamily: 'var(--mono)', fontSize: 8.5, letterSpacing: '.08em', textTransform: 'uppercase', color: 'var(--ink-muted)' };
const Panel = ({ children, cols }) => (
  <div style={{ background: 'var(--bg-card)', border: '1px solid var(--line)', borderRadius: 8, overflow: 'hidden' }}>
    {children}
  </div>
);
const Row = ({ cols, children, tint, head }) => (
  <div style={{
    display: 'grid', gridTemplateColumns: cols, gap: 8, padding: '7px 11px', alignItems: 'center',
    borderTop: head ? 'none' : '1px solid var(--line)',
    background: head ? 'var(--bg-soft)' : tint || 'transparent', fontSize: 11,
    transition: 'background 600ms ease',
  }}>{children}</div>
);

const FacturasScreen = () => (
  <>
    <PageHead title="Facturas" sub="Registro de compras a proveedores" size={23} right={
      <div style={{ display: 'flex', gap: 6 }}>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, padding: '5px 9px', border: '1px solid var(--line-strong)', borderRadius: 6, fontSize: 10.5, background: 'var(--bg-card)' }}>
          <span style={{ color: 'var(--good)', display: 'inline-flex' }}><Icon.Excel size={11}/></span>Excel
        </span>
        <span style={{ padding: '5px 9px', background: 'var(--accent)', color: '#fff', borderRadius: 6, fontSize: 10.5, display: 'inline-flex', alignItems: 'center', gap: 4 }}>
          <Icon.Plus size={10}/>Nueva Factura
        </span>
      </div>
    }/>
    <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap', marginBottom: 12, fontSize: 9.5, color: 'var(--ink-muted)' }}>
      {[['#C0392B', 'No entregado'], ['#D5825C', 'Cant. menor'], ['#E2A03F', 'Precio dif.'], ['#2F7D52', 'Agregado']].map(([c, l]) => (
        <span key={l} style={{ display: 'inline-flex', alignItems: 'center', gap: 5 }}>
          <span style={{ width: 7, height: 7, borderRadius: '50%', background: c }}/>{l}
        </span>
      ))}
      <span style={{ marginLeft: 'auto', fontFamily: 'var(--mono)', color: 'var(--ink)' }}>Total: $165.830.592,40</span>
    </div>
    <Panel>
      <Row cols="1.3fr 74px 1fr 88px" head><span style={th}>Número</span><span style={th}>Fecha</span><span style={th}>Proveedor</span><span style={{ ...th, textAlign: 'right' }}>Total</span></Row>
      {[
        { n: '0006-00055364', oc: 'OC A01-0448', d: '15/08/2026', p: 'Delico', t: '$369.469,05', dots: ['#D5825C', '#E2A03F'], nuevo: true },
        { n: '0015-00543934', oc: 'OC A01-0446', d: '15/08/2026', p: 'Blancaluna', t: '$153.354,00', dots: [] },
        { n: '0007-00687122', oc: 'OC A01-0451', d: '15/08/2026', p: 'Marilu Damiano', t: '$948.662,80', dots: ['#D5825C', '#E2A03F'] },
        { n: '00007-00010481', oc: 'OC A01-0435', d: '13/08/2026', p: 'Dacapo', t: '$69.688,00', dots: [] },
        { n: '00011-00113468', oc: 'OC A01-0437', d: '13/08/2026', p: 'Fresh', t: '$22.089,34', dots: ['#E2A03F'] },
        { n: '00002-00084650', oc: 'OC A01-0442', d: '13/08/2026', p: 'Alamenia', t: '$211.854,00', dots: ['#D5825C'] },
      ].map(r => (
        <Row key={r.n} cols="1.3fr 74px 1fr 88px" tint={r.nuevo ? 'var(--accent-tint)' : null}>
          <span style={{ display: 'flex', alignItems: 'center', gap: 6, minWidth: 0 }}>
            <span style={{ display: 'flex', flexDirection: 'column', gap: 2, width: 7, flexShrink: 0 }}>
              {r.dots.map((d, k) => <span key={k} style={{ width: 7, height: 7, borderRadius: '50%', background: d }}/>)}
            </span>
            <span style={{ minWidth: 0 }}>
              <span style={{ display: 'block', fontSize: 11, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{r.n}</span>
              <span style={{ fontSize: 9, color: 'var(--ink-muted)', fontFamily: 'var(--mono)' }}>{r.oc}</span>
            </span>
            {r.nuevo && <span style={{ fontSize: 8.5, fontFamily: 'var(--mono)', color: 'var(--accent)', flexShrink: 0 }}>nueva</span>}
          </span>
          <span style={{ fontFamily: 'var(--mono)', fontSize: 10 }}>{r.d}</span>
          <span style={{ whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{r.p}</span>
          <span style={{ fontFamily: 'var(--mono)', fontSize: 10.5, textAlign: 'right', fontWeight: 600 }}>{r.t}</span>
        </Row>
      ))}
    </Panel>
  </>
);

const InsumosScreen = () => (
  <>
    <PageHead title="Insumos" sub="Precios y variación por proveedor" size={23}/>
    <Panel>
      <Row cols="1.2fr .9fr 70px 62px 54px" head>
        <span style={th}>Insumo</span><span style={th}>Proveedor</span>
        <span style={{ ...th, textAlign: 'right' }}>Precio</span>
        <span style={{ ...th, textAlign: 'right' }}>Var.</span>
        <span style={{ ...th, textAlign: 'right' }}>Rubro</span>
      </Row>
      {[
        { n: 'Morron rojo', u: 'kg', p: 'Verdura Francisco', v: 5128, d: '+8.4%', tone: 'bad', r: 'Verduras', nuevo: true },
        { n: 'Linguini', u: 'kg', p: 'Delico', v: 6050, d: '0.0%', tone: 'flat', r: 'Almacén' },
        { n: 'Salsa de soja', u: 'lt', p: 'Alamenia', v: 9148, d: '+1.2%', tone: 'bad', r: 'Almacén' },
        { n: 'Cebollon', u: 'kg', p: 'Verdura Francisco', v: 2458, d: '−3.1%', tone: 'good', r: 'Verduras' },
        { n: 'Morron verde', u: 'kg', p: 'Verdura Francisco', v: 4571, d: '+2.0%', tone: 'bad', r: 'Verduras' },
        { n: 'Langostino cola N°2', u: 'kg', p: 'Blancaluna', v: 28400, d: '+5.4%', tone: 'bad', r: 'Pescados' },
      ].map(r => (
        <Row key={r.n} cols="1.2fr .9fr 70px 62px 54px" tint={r.nuevo ? 'var(--accent-tint)' : null}>
          <span style={{ display: 'flex', alignItems: 'center', gap: 6, minWidth: 0 }}>
            <span style={{ color: 'var(--good)', flexShrink: 0, display: 'inline-flex' }}><Icon.Box size={11}/></span>
            <span style={{ whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{r.n}</span>
            <span style={{ fontSize: 9, color: 'var(--ink-muted)', flexShrink: 0 }}>/{r.u}</span>
          </span>
          <span style={{ fontSize: 10.5, color: 'var(--ink-soft)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{r.p}</span>
          <span style={{ fontFamily: 'var(--mono)', fontSize: 10.5, textAlign: 'right', fontWeight: r.nuevo ? 600 : 400 }}>{ars(r.v)}</span>
          <span style={{
            fontFamily: 'var(--mono)', fontSize: 10.5, textAlign: 'right',
            color: r.tone === 'bad' ? 'var(--bad)' : r.tone === 'good' ? 'var(--good)' : 'var(--ink-muted)',
          }}>{r.d}</span>
          <span style={{ fontSize: 9.5, textAlign: 'right', color: 'var(--ink-muted)' }}>{r.r}</span>
        </Row>
      ))}
    </Panel>
    <div style={{
      marginTop: 12, padding: '10px 12px', background: 'var(--warn-tint)',
      border: '1px solid #EBD6A6', borderRadius: 8, fontSize: 11, color: '#8A6420',
      display: 'flex', alignItems: 'center', gap: 8,
    }}>
      <Icon.Alert size={13}/>Aumento atípico detectado en <strong>Morron rojo</strong> · 3 recetas afectadas
    </div>
  </>
);

const RecetasScreen = () => (
  <>
    <PageHead title="Recetas" sub="Fichas técnicas recosteadas" size={23} right={
      <span style={{ fontFamily: 'var(--mono)', fontSize: 10, color: 'var(--ink-muted)' }}>63 platos</span>
    }/>
    <Panel>
      <Row cols="1.5fr 1fr 74px 62px" head>
        <span style={th}>Plato</span><span style={th}>Insumos</span>
        <span style={{ ...th, textAlign: 'right' }}>Costo x porción</span>
        <span style={{ ...th, textAlign: 'right' }}>Var.</span>
      </Row>
      {[
        { n: 'Brochette de langostinos', i: 'Morron rojo · Linguini · Salsa de soja', c: 2429, d: '+0.7%', hit: true },
        { n: 'Petit Camambert', i: 'Morron rojo · Rucula · Camambert', c: 5841, d: '+1.0%', hit: true },
        { n: 'Muzzarelitas apanadas', i: 'Muzzarella · Pan rallado · Huevo', c: 1913, d: '0.0%' },
        { n: 'Molleja al Verdeo', i: 'Papa · Molleja', c: 7282, d: '0.0%' },
        { n: 'Rabas al Romana', i: 'Tubo de calamar · Harina 0000', c: 6234, d: '0.0%' },
        { n: 'Revuelto gramajo', i: 'Huevo · Arvejas · Papa · Jamon', c: 2559, d: '0.0%' },
      ].map(r => (
        <Row key={r.n} cols="1.5fr 1fr 74px 62px" tint={r.hit ? 'var(--accent-tint)' : null}>
          <span style={{ display: 'flex', alignItems: 'center', gap: 6, minWidth: 0 }}>
            <span style={{ color: 'var(--accent)', flexShrink: 0, display: 'inline-flex' }}><Icon.Chef size={11}/></span>
            <span style={{ whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{r.n}</span>
          </span>
          <span style={{ fontSize: 9.5, color: 'var(--ink-muted)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{r.i}</span>
          <span style={{ fontFamily: 'var(--mono)', fontSize: 10.5, textAlign: 'right', color: 'var(--good)', fontWeight: 600 }}>{ars(r.c)}</span>
          <span style={{ fontFamily: 'var(--mono)', fontSize: 10.5, textAlign: 'right', color: r.hit ? 'var(--bad)' : 'var(--ink-muted)' }}>{r.d}</span>
        </Row>
      ))}
    </Panel>
    <div style={{
      marginTop: 12, padding: '10px 12px', background: 'var(--primary-tint)',
      border: '1px solid #C6DACC', borderRadius: 8, fontSize: 11, color: 'var(--primary)',
      display: 'flex', alignItems: 'center', gap: 8,
    }}>
      <Icon.Spark size={13}/>2 fichas recosteadas automáticamente · incluye elaboraciones anidadas
    </div>
  </>
);

const CartaScreen = () => (
  <>
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 8, marginBottom: 14 }}>
      {[['OK', 24, 'good'], ['Atención', 9, 'warn'], ['Fuera', 13, 'bad']].map(([l, v, t]) => (
        <div key={l} style={{
          padding: '9px 12px', borderRadius: 8,
          background: `var(--${t}-tint)`, border: '1px solid ' + (t === 'good' ? '#BFDECB' : t === 'warn' ? '#EBD6A6' : '#EFC3BC'),
        }}>
          <div style={{ fontSize: 10, color: `var(--${t})`, display: 'flex', alignItems: 'center', gap: 5 }}>
            {t === 'good' ? <Icon.Check size={11}/> : <Icon.Alert size={11}/>}{l}
          </div>
          <div style={{ fontFamily: 'var(--mono)', fontSize: 20, fontWeight: 600, color: `var(--${t})`, lineHeight: 1.2 }}>{v}</div>
        </div>
      ))}
    </div>
    <div style={{ display: 'flex', gap: 14, marginBottom: 10, fontSize: 11, borderBottom: '1px solid var(--line)', paddingBottom: 7 }}>
      {[['En Carta (46)', true], ['Fuera de Carta (24)', false], ['Ejecutivos (16)', false], ['Especiales (3)', false]].map(([l, on]) => (
        <span key={l} style={{
          color: on ? 'var(--good)' : 'var(--ink-muted)', fontWeight: on ? 500 : 400,
          borderBottom: on ? '2px solid var(--good)' : 'none', paddingBottom: 6, marginBottom: -8,
        }}>{l}</span>
      ))}
    </div>
    <Panel>
      <Row cols="1.5fr 30px 58px 58px 40px 58px" head>
        <span style={th}>Plato</span><span style={th}>Carta</span>
        <span style={{ ...th, textAlign: 'right' }}>Costo</span>
        <span style={{ ...th, textAlign: 'right' }}>P.Carta</span>
        <span style={{ ...th, textAlign: 'right' }}>M.Obj</span>
        <span style={{ ...th, textAlign: 'right' }}>FC</span>
      </Row>
      {[
        { n: 'Burratina con Salmorejo', c: 5542, p: 22000, m: '25%', fc: 25.2, hit: true },
        { n: 'Chorizo Criollo', c: 1138, p: 8000, m: '25%', fc: 14.2 },
        { n: 'Empanada de Carne', c: 787, p: 4500, m: '25%', fc: 17.5 },
        { n: 'Ensalada rusa con langostinos', c: 2036, p: 17000, m: '15%', fc: 12.0 },
        { n: 'Gambas al ajillo', c: 4646, p: 23000, m: '20%', fc: 20.2, hit: true },
        { n: 'Rabas al Romana', c: 6231, p: 25000, m: '25%', fc: 24.9 },
        { n: 'Tortilla Española', c: 3070, p: 16000, m: '15%', fc: 19.2 },
      ].map(r => (
        <Row key={r.n} cols="1.5fr 30px 58px 58px 40px 58px" tint={r.hit ? 'var(--accent-tint)' : null}>
          <span style={{ display: 'flex', alignItems: 'center', gap: 6, minWidth: 0 }}>
            <span style={{ color: 'var(--accent)', flexShrink: 0, display: 'inline-flex' }}><Icon.Chef size={11}/></span>
            <span style={{ whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{r.n}</span>
          </span>
          <Toggle on/>
          <span style={{ fontFamily: 'var(--mono)', fontSize: 10.5, textAlign: 'right', color: 'var(--ink-soft)' }}>{ars(r.c)}</span>
          <span style={{ fontFamily: 'var(--mono)', fontSize: 10.5, textAlign: 'right', fontWeight: 600 }}>{ars(r.p)}</span>
          <span style={{ fontFamily: 'var(--mono)', fontSize: 10, textAlign: 'right', color: 'var(--ink-muted)' }}>{r.m}</span>
          <span style={{ textAlign: 'right' }}><FcPill pct={r.fc}/></span>
        </Row>
      ))}
    </Panel>
  </>
);

window.SystemAnim = SystemAnim;
