// mockups.jsx — Mockups animados de cada producto

// ───── Helpers
function MiniBar({ h, delay = 0 }) {
  return (
    <div style={{
      height: h + '%',
      background: 'linear-gradient(180deg, var(--accent) 0%, var(--accent-soft) 100%)',
      width: '100%',
      borderRadius: '3px 3px 0 0',
      transformOrigin: 'bottom',
      animation: `barRise 1100ms cubic-bezier(0.2, 0.8, 0.2, 1) ${delay}ms backwards`,
    }} />
  );
}

function TypingDots() {
  return (
    <div style={{ display: 'flex', gap: 3, alignItems: 'center', padding: '6px 10px', background: 'rgba(255,255,255,0.06)', borderRadius: '10px 10px 10px 2px', border: '1px solid var(--line)', alignSelf: 'flex-start' }}>
      {[0, 1, 2].map(i => (
        <div key={i} style={{ width: 5, height: 5, borderRadius: 999, background: 'var(--ink-dim)', animation: `typingBounce 1s ease-in-out ${i * 160}ms infinite` }} />
      ))}
    </div>
  );
}

// ───── BilleterAI: secuencia de chat animada
const BILLETER_SEQ = [
  { wait: 500 },
  { msg: { dir: 'r', text: 'Factura B a Juan Pérez — $48.500 IVA incluido' }, wait: 1000 },
  { typing: true, wait: 950 },
  { msg: { dir: 'l', text: '✓ Lista. FB-0042' }, wait: 700 },
  { msg: { dir: 'l', invoice: true }, wait: 1400 },
  { msg: { dir: 'r', text: '¿Cuánto debe Rodríguez?' }, wait: 900 },
  { typing: true, wait: 950 },
  { msg: { dir: 'l', text: 'Debe $12.300. Vence en 3 días.' }, wait: 1000 },
  { msg: { dir: 'r', text: 'Avisale por WhatsApp' }, wait: 850 },
  { typing: true, wait: 800 },
  { msg: { dir: 'l', text: '✓ Recordatorio enviado.' }, wait: 3000 },
  { reset: true },
];

function MockBilleter() {
  const [msgs, setMsgs] = React.useState([]);
  const [typing, setTyping] = React.useState(false);
  const [idx, setIdx] = React.useState(0);

  React.useEffect(() => {
    const step = BILLETER_SEQ[idx];
    if (!step) return;

    if (step.reset) {
      setMsgs([]);
      setTyping(false);
      setIdx(0);
      return;
    }

    if (step.typing) {
      setTyping(true);
    } else if (step.msg) {
      setTyping(false);
      setMsgs(prev => [...prev, { ...step.msg, id: idx }].slice(-5));
    }

    const t = setTimeout(() => setIdx(i => i + 1), step.wait);
    return () => clearTimeout(t);
  }, [idx]);

  const slide = (dir) => ({ animation: `${dir === 'r' ? 'msgSlideR' : 'msgSlideL'} 260ms cubic-bezier(0.2,0.8,0.2,1) both` });

  return (
    <div className="phone" style={{ margin: '0 auto' }}>
      <div className="phone-screen" style={{ background: 'linear-gradient(180deg, #0f0f1a 0%, #07070f 100%)', overflow: 'hidden' }}>
        {/* Header */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, paddingBottom: 8, borderBottom: '1px solid var(--line)', flexShrink: 0 }}>
          <div style={{ width: 22, height: 22, borderRadius: 999, background: 'var(--accent)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 11, color: '#fff', fontWeight: 700 }}>B</div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 9, fontWeight: 600 }}>BilleterAI</div>
            <div style={{ fontSize: 7, color: 'var(--ink-dim)' }}>en línea · vía WhatsApp</div>
          </div>
          <div style={{ width: 4, height: 4, borderRadius: 999, background: 'var(--accent)', boxShadow: '0 0 6px var(--accent-glow)' }} />
        </div>

        {/* Chat */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 7, paddingTop: 8, flex: 1, justifyContent: 'flex-end' }}>
          {msgs.map((m) => m.invoice ? (
            <div key={m.id} style={{ ...slide('l'), alignSelf: 'flex-start', width: '90%', border: '1px solid var(--line-strong)', borderRadius: 8, padding: 7, background: 'rgba(0,0,0,0.3)' }}>
              <div style={{ fontSize: 7, color: 'var(--ink-dim)', letterSpacing: '0.08em', textTransform: 'uppercase' }}>Factura B</div>
              <div style={{ fontSize: 10, fontWeight: 600, marginTop: 2 }}>$48.500</div>
              <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 4, fontSize: 7, color: 'var(--ink-muted)' }}>
                <span>Juan Pérez</span><span>FB-0042</span>
              </div>
              <div style={{ marginTop: 6, height: 16, borderRadius: 3, background: 'repeating-linear-gradient(90deg, transparent 0 2px, var(--ink-muted) 2px 3px)', opacity: 0.35 }} />
            </div>
          ) : (
            <div key={m.id} style={{
              ...slide(m.dir),
              alignSelf: m.dir === 'r' ? 'flex-end' : 'flex-start',
              maxWidth: '80%',
              background: m.dir === 'r' ? 'var(--accent)' : 'rgba(255,255,255,0.06)',
              color: m.dir === 'r' ? '#fff' : 'var(--ink)',
              fontSize: 8, padding: '6px 9px',
              borderRadius: m.dir === 'r' ? '10px 10px 2px 10px' : '10px 10px 10px 2px',
              lineHeight: 1.45,
              border: m.dir === 'l' ? '1px solid var(--line)' : 'none',
            }}>
              {m.text}
            </div>
          ))}
          {typing && <TypingDots />}
        </div>
      </div>
    </div>
  );
}

// ───── Agente Ventas: barras que se recargan
function MockVentas() {
  const [tick, setTick] = React.useState(0);
  React.useEffect(() => {
    const id = setInterval(() => setTick(t => t + 1), 4000);
    return () => clearInterval(id);
  }, []);

  return (
    <div className="mock">
      <div className="mock-chrome"><i /><i /><i /></div>
      <div className="mock-body" style={{ gridTemplateColumns: '60px 1fr', padding: '10px' }}>
        <div className="mock-side">
          <div className="item active" />
          {[60, 70, 55, 65].map((w, i) => <div key={i} className="item" style={{ width: w + '%' }} />)}
        </div>
        <div className="mock-main" style={{ gap: 8 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <div className="title" style={{ width: '40%' }} />
            <div style={{ fontSize: 8, color: 'var(--accent)', fontWeight: 600 }}>+18.4%</div>
          </div>
          <div className="row">
            {[['$ 1.2M'], ['87'], ['23']].map(([v], i) => (
              <div key={i} className="stat"><div style={{ fontSize: 9, fontWeight: 600 }}>{v}</div><div className="l" /></div>
            ))}
          </div>
          <div className="chart" style={{ display: 'flex', alignItems: 'flex-end', gap: 4, padding: 8 }}>
            {[40, 65, 55, 78, 60, 88, 72, 95, 80, 92].map((h, i) => (
              <MiniBar key={`${tick}-${i}`} h={h} delay={i * 80} />
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

// ───── Agente Central: celdas que se activan en tiempo real
function MockCentral() {
  const TOTAL = 24;
  const [activeSet, setActiveSet] = React.useState(() => new Set([0, 3, 5, 8, 11, 14, 17, 20]));
  const [flashCell, setFlashCell] = React.useState(null);
  const [events, setEvents] = React.useState([
    { id: 1, text: 'Vendedor #08 cerró venta', time: '14:22' },
    { id: 2, text: 'Vendedor #14 inició ruta', time: '14:31' },
  ]);

  React.useEffect(() => {
    const id = setInterval(() => {
      const cell = Math.floor(Math.random() * TOTAL);
      setFlashCell(cell);
      setActiveSet(prev => {
        const next = new Set(prev);
        if (next.has(cell)) next.delete(cell); else next.add(cell);
        return next;
      });
      const names = ['#03', '#07', '#11', '#18', '#22', '#05', '#16'];
      const actions = ['cerró venta', 'inició visita', 'cobró $18K', 'registró pedido'];
      const now = new Date();
      const time = `${now.getHours()}:${String(now.getMinutes()).padStart(2,'0')}`;
      setEvents(prev => [
        { id: Date.now(), text: `Vendedor ${names[Math.floor(Math.random()*names.length)]} ${actions[Math.floor(Math.random()*actions.length)]}`, time },
        ...prev.slice(0, 1),
      ]);
      setTimeout(() => setFlashCell(null), 600);
    }, 2200);
    return () => clearInterval(id);
  }, []);

  return (
    <div className="mock">
      <div className="mock-chrome"><i /><i /><i /></div>
      <div style={{ padding: 12, height: 'calc(100% - 28px)', display: 'flex', flexDirection: 'column', gap: 8 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div style={{ fontSize: 9, fontWeight: 600, letterSpacing: '0.04em' }}>EMPRESA · {TOTAL} VENDEDORES</div>
          <div style={{ fontSize: 8, color: 'var(--accent)', fontWeight: 600 }}>{activeSet.size} activos</div>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(8, 1fr)', gap: 3 }}>
          {Array.from({ length: TOTAL }, (_, i) => (
            <div key={i} style={{
              aspectRatio: '1', borderRadius: 4,
              background: flashCell === i
                ? 'white'
                : activeSet.has(i)
                  ? 'color-mix(in srgb, var(--accent) 70%, transparent)'
                  : 'var(--line)',
              border: '1px solid var(--line)',
              transition: 'background 400ms ease, box-shadow 400ms ease',
              boxShadow: flashCell === i ? '0 0 8px var(--accent-glow)' : 'none',
            }} />
          ))}
        </div>
        <div style={{ display: 'flex', gap: 10, fontSize: 7, color: 'var(--ink-dim)' }}>
          <span style={{ color: 'var(--accent)' }}>● Activo</span>
          <span>● Idle</span>
          <span>● Offline</span>
        </div>
        <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 4, overflow: 'hidden' }}>
          {events.map((e, i) => (
            <div key={e.id} style={{
              display: 'flex', justifyContent: 'space-between', alignItems: 'center',
              padding: '4px 7px', borderRadius: 5, fontSize: 7,
              background: i === 0 ? 'color-mix(in srgb, var(--accent) 10%, transparent)' : 'rgba(255,255,255,0.03)',
              border: `1px solid ${i === 0 ? 'color-mix(in srgb, var(--accent) 30%, transparent)' : 'var(--line)'}`,
              animation: i === 0 ? 'msgSlideL 300ms ease both' : 'none',
            }}>
              <span style={{ color: i === 0 ? 'var(--ink)' : 'var(--ink-dim)' }}>{e.text}</span>
              <span style={{ color: 'var(--ink-dim)', flexShrink: 0, marginLeft: 6 }}>{e.time}</span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

// ───── Agente Comercio: ventas en tiempo real con stock y POS
const PRODUCTS_DATA = [
  { n: 'Coca 1.5L',   price: 1200, color: 'var(--accent)' },
  { n: 'Pan lactal',  price: 380,  color: 'var(--accent-soft)' },
  { n: 'Yerba 500g',  price: 950,  color: '#fbbf24' },
  { n: 'Aceite 900ml',price: 650,  color: 'var(--accent)' },
];

function MockComercio() {
  const [stocks, setStocks] = React.useState([48, 12, 6, 24]);
  const [total, setTotal] = React.useState(8420);
  const [saleIdx, setSaleIdx] = React.useState(null);

  React.useEffect(() => {
    const id = setInterval(() => {
      const i = Math.floor(Math.random() * PRODUCTS_DATA.length);
      setSaleIdx(i);
      setStocks(s => s.map((v, k) => k === i ? Math.max(0, v - 1) : v));
      setTotal(t => t + PRODUCTS_DATA[i].price);
      setTimeout(() => setSaleIdx(null), 700);
    }, 2000);
    return () => clearInterval(id);
  }, []);

  return (
    <div className="mock">
      <div className="mock-chrome"><i /><i /><i /></div>
      <div style={{ padding: 12, height: 'calc(100% - 28px)', display: 'grid', gridTemplateColumns: '1fr 110px', gap: 10 }}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
          <div style={{ fontSize: 9, fontWeight: 600 }}>Productos</div>
          {PRODUCTS_DATA.map((p, i) => (
            <div key={i} style={{
              display: 'flex', justifyContent: 'space-between', alignItems: 'center',
              padding: '5px 8px', borderRadius: 5,
              border: `1px solid ${saleIdx === i ? 'color-mix(in srgb, var(--accent) 60%, transparent)' : 'var(--line)'}`,
              background: saleIdx === i ? 'color-mix(in srgb, var(--accent) 10%, transparent)' : 'transparent',
              transition: 'background 300ms, border-color 300ms',
            }}>
              <span style={{ fontSize: 8 }}>{p.n}</span>
              <span style={{ fontSize: 8, color: p.color, fontWeight: 600, transition: 'transform 200ms', transform: saleIdx === i ? 'scale(1.15)' : 'scale(1)' }}>
                {stocks[i]}u
              </span>
            </div>
          ))}
        </div>
        <div style={{ border: '1px solid var(--line-strong)', borderRadius: 8, padding: 8, display: 'flex', flexDirection: 'column', gap: 6, background: 'rgba(0,0,0,0.25)' }}>
          <div style={{ fontSize: 7, color: 'var(--ink-dim)', textTransform: 'uppercase', letterSpacing: '0.08em' }}>Total</div>
          <div style={{ fontSize: 13, fontWeight: 600, transition: 'color 200ms', color: saleIdx !== null ? 'var(--accent)' : 'var(--ink)' }}>
            $ {total.toLocaleString('es-AR')}
          </div>
          <div style={{ flex: 1 }} />
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 3 }}>
            {[1,2,3,4,5,6,7,8,9].map(n => (
              <div key={n} style={{ aspectRatio: '1', border: '1px solid var(--line)', borderRadius: 3, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 8 }}>{n}</div>
            ))}
          </div>
          <div style={{ background: 'var(--accent)', color: '#fff', padding: '5px 0', borderRadius: 4, textAlign: 'center', fontSize: 8, fontWeight: 600 }}>COBRAR</div>
        </div>
      </div>
    </div>
  );
}

// ───── Agente Resto: barras de ingredientes que se recargan
function MockResto() {
  const [tick, setTick] = React.useState(0);
  React.useEffect(() => {
    const id = setInterval(() => setTick(t => t + 1), 4500);
    return () => clearInterval(id);
  }, []);

  const ingredients = [
    { n: 'Nalga 220g',     m: 78, c: '$ 1.840' },
    { n: 'Pan rallado 40g',m: 32, c: '$ 120' },
    { n: 'Mozzarella 60g', m: 65, c: '$ 380' },
    { n: 'Salsa 80g',      m: 20, c: '$ 95' },
  ];

  return (
    <div className="mock">
      <div className="mock-chrome"><i /><i /><i /></div>
      <div style={{ padding: 14, height: 'calc(100% - 28px)', display: 'flex', flexDirection: 'column', gap: 10 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between' }}>
          <div style={{ fontSize: 10, fontWeight: 600, fontFamily: 'var(--font-serif)', fontStyle: 'italic' }}>Milanesa Napolitana</div>
          <div style={{ fontSize: 8, color: 'var(--accent)' }}>Margen 62%</div>
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
          {ingredients.map((ing, k) => (
            <div key={k} style={{ display: 'grid', gridTemplateColumns: '1fr 64px 46px', gap: 8, alignItems: 'center', fontSize: 8 }}>
              <span>{ing.n}</span>
              <div style={{ height: 5, borderRadius: 3, background: 'var(--line)', position: 'relative', overflow: 'hidden' }}>
                <div key={`${tick}-${k}`} style={{
                  position: 'absolute', inset: 0,
                  width: ing.m + '%',
                  background: 'linear-gradient(90deg, var(--accent), var(--accent-soft))',
                  animation: `barSlide 900ms cubic-bezier(0.2,0.8,0.2,1) ${k * 120}ms both`,
                }} />
              </div>
              <span style={{ color: 'var(--ink-muted)', textAlign: 'right' }}>{ing.c}</span>
            </div>
          ))}
        </div>
        <div style={{ marginTop: 'auto', display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 6, paddingTop: 8, borderTop: '1px solid var(--line)' }}>
          {[['$2.435','Costo'],['$6.400','Venta'],['4.2 min','Cocina']].map(([v, l], i) => (
            <div key={i}>
              <div style={{ fontSize: 9, fontWeight: 600, color: i === 2 ? 'var(--accent)' : 'var(--ink)' }}>{v}</div>
              <div style={{ fontSize: 7, color: 'var(--ink-dim)' }}>{l}</div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

// ───── Hero mockup
function MockHero() {
  const dataPoints = [30, 45, 38, 62, 55, 78, 72, 88, 80, 95, 92, 110, 105];
  return (
    <div className="mock" style={{ aspectRatio: '4 / 3', borderRadius: 16 }}>
      <div className="mock-chrome" style={{ padding: '11px 16px' }}>
        <i /><i /><i />
        <div style={{ marginLeft: 16, fontSize: 9, color: 'var(--ink-dim)', fontFamily: 'var(--font-mono)' }}>app.taloslabsia.com</div>
      </div>
      <div style={{ padding: 18, height: 'calc(100% - 32px)', display: 'grid', gridTemplateColumns: '110px 1fr', gap: 14 }}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          <div style={{ fontSize: 8, color: 'var(--ink-dim)', letterSpacing: '0.08em', textTransform: 'uppercase' }}>Talos</div>
          {['Dashboard','Clientes','Pedidos','Cobranzas','Stock','Reportes'].map((l, i) => (
            <div key={i} style={{ fontSize: 9, padding: '5px 8px', borderRadius: 4, background: i === 0 ? 'color-mix(in srgb, var(--accent) 20%, transparent)' : 'transparent', color: i === 0 ? 'var(--accent)' : 'var(--ink-muted)' }}>{l}</div>
          ))}
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12, minWidth: 0 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
            <div>
              <div style={{ fontSize: 10, color: 'var(--ink-dim)' }}>Ingresos · Octubre</div>
              <div style={{ fontSize: 22, fontWeight: 500, fontFamily: 'var(--font-serif)', fontStyle: 'italic', marginTop: 2 }}>$ 2.847.500</div>
            </div>
            <div style={{ fontSize: 9, color: 'var(--accent)', padding: '3px 8px', border: '1px solid var(--accent)', borderRadius: 999, background: 'color-mix(in srgb, var(--accent) 10%, transparent)' }}>↗ +24%</div>
          </div>
          <div style={{ flex: 1, position: 'relative', border: '1px solid var(--line)', borderRadius: 8, padding: 10, background: 'rgba(0,0,0,0.2)', minHeight: 80 }}>
            <svg viewBox="0 0 200 80" preserveAspectRatio="none" style={{ width: '100%', height: '100%' }}>
              <defs>
                <linearGradient id="heroLine" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="0%" stopColor="var(--accent)" stopOpacity="0.4" />
                  <stop offset="100%" stopColor="var(--accent)" stopOpacity="0" />
                </linearGradient>
              </defs>
              {(() => {
                const max = Math.max(...dataPoints);
                const pts = dataPoints.map((v, i) => `${(i / (dataPoints.length - 1)) * 200},${80 - (v / max) * 70 - 5}`).join(' ');
                return (<>
                  <polygon points={`0,80 ${pts} 200,80`} fill="url(#heroLine)" />
                  <polyline points={pts} fill="none" stroke="var(--accent)" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
                  {dataPoints.map((v, i) => <circle key={i} cx={(i/(dataPoints.length-1))*200} cy={80-(v/max)*70-5} r="1.5" fill="var(--accent)" />)}
                </>);
              })()}
            </svg>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 8 }}>
            {[['847','Pedidos'],['$ 18.4K','Ticket prom.'],['92%','Cobrado']].map(([v, l], i) => (
              <div key={i} style={{ padding: 8, border: '1px solid var(--line)', borderRadius: 6 }}>
                <div style={{ fontSize: 12, fontWeight: 500 }}>{v}</div>
                <div style={{ fontSize: 8, color: 'var(--ink-dim)', marginTop: 2 }}>{l}</div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

// ───── Keyframes globales
const __mockKeyframes = `
@keyframes barRise  { from { transform: scaleY(0); } to { transform: scaleY(1); } }
@keyframes barSlide { from { transform: scaleX(0); transform-origin: left; } to { transform: scaleX(1); transform-origin: left; } }
@keyframes fadePulse { 0%,100% { opacity:1; } 50% { opacity:0.5; } }
@keyframes msgSlideR { from { opacity:0; transform:translateX(12px) scale(0.96); } to { opacity:1; transform:none; } }
@keyframes msgSlideL { from { opacity:0; transform:translateX(-12px) scale(0.96); } to { opacity:1; transform:none; } }
@keyframes typingBounce { 0%,100% { transform:translateY(0); opacity:0.4; } 50% { transform:translateY(-4px); opacity:1; } }
`;
if (!document.getElementById('mock-anim')) {
  const s = document.createElement('style');
  s.id = 'mock-anim';
  s.textContent = __mockKeyframes;
  document.head.appendChild(s);
}

window.Mockups = { MockBilleter, MockVentas, MockCentral, MockComercio, MockResto, MockHero };
