/* global React, Reveal, Icon */
const { useState: useFam, useEffect: useFamEffect } = React;

// resolve an asset to the inlined bundle resource if present, else the relative path
const RES = (id, path) => (typeof window !== 'undefined' && window.__resources && window.__resources[id]) || path;

// ════════════════════════════════════════════════════════════
//  PRODUTOS — the Convive product family + "inside" views
//  Convive Control → galeria de telas reais
//  Convive Eat     → telas ilustrativas
// ════════════════════════════════════════════════════════════
const FAMILY = [
  {
    name: 'Control',
    flagship: true,
    icon: 'layers',
    status: 'Disponível',
    tagline: 'Controle total da operação, para empresas de qualquer porte.',
    desc: 'O motor completo: comercial, projetos e financeiro conversando num lugar só, com o fluxo de designação que passa o trabalho adiante sozinho.',
    modules: ['CRM', 'Projetos', 'Financeiro', 'Designação'],
    shots: [
      { src: RES('ctrlDashboard', 'assets/control/dashboard.png'), label: 'Dashboard', sub: 'Faturamento, metas e projeção do ano em tempo real.' },
      { src: RES('ctrlAbc', 'assets/control/curva-abc.png'), label: 'Curva ABC', sub: 'Produtos classificados pela contribuição no faturamento.' },
      { src: RES('ctrlMon', 'assets/control/monitoramento.png'), label: 'Monitoramento', sub: 'Tempo e desempenho de cada equipe em campo.' },
      { src: RES('ctrlRanking', 'assets/control/ranking.png'), label: 'Equipe & RH', sub: 'Ranking e perfil de cada colaborador.' },
      { src: RES('ctrlAcesso', 'assets/control/acesso.png'), label: 'Acesso seguro', sub: 'Login por usuário, com controle de permissão.' },
    ],
  },
  {
    name: 'Eat',
    flagship: false,
    icon: 'utensils',
    status: 'Disponível',
    tagline: 'Gestão inteligente para restaurantes e bares.',
    desc: 'Do estoque ao caixa, no ritmo da casa cheia — comandas, equipe e a margem real de cada prato, num painel leve.',
    modules: ['Caixa', 'Comandas', 'Estoque', 'Ficha técnica'],
    shots: [
      { src: RES('eatDashboard', 'assets/eat/dashboard3.png'), label: 'Dashboard', sub: 'Faturamento, ticket médio, CMV e margem em tempo real.' },
      { src: RES('eatPedidos', 'assets/eat/pedidos4.png'), label: 'Painel de pedidos', sub: 'Delivery, balcão e mesa fluindo por etapa.' },
      { src: RES('eatCozinha', 'assets/eat/cozinha3.png'), label: 'Cozinha', sub: 'Produtividade e pódio da equipe.' },
      { src: RES('eatFicha', 'assets/eat/ficha3.png'), label: 'Ficha técnica', sub: 'Custo, margem e ingredientes de cada prato.' },
      { src: RES('eatCmv', 'assets/eat/cmv3.png'), label: 'Saúde do CMV', sub: 'Onde o custo corrói a sua margem.' },
    ],
  },
];

function Produtos() {
  const [open, setOpen] = useFam(null);
  return (
    <section id="produtos" className="section section-paper">
      <div className="wrap">
        <div style={{ textAlign: 'center', maxWidth: 680, margin: '0 auto' }}>
          <Reveal as="div" className="eyebrow">Os produtos</Reveal>
          <Reveal as="h2" delay={60} className="sec-title" style={{ marginInline: 'auto' }}>
            Dois produtos, <em className="it" style={{ color: 'var(--terra)' }}>uma filosofia</em>.
          </Reveal>
          <Reveal as="p" delay={120} className="sec-lead" style={{ marginInline: 'auto' }}>
            A mesma engenharia que convive com a sua rotina, em duas frentes: a operação completa e a cozinha cheia.
          </Reveal>
        </div>

        <div className="familia-grid" style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 20, marginTop: 48 }}>
          {FAMILY.map((p, i) => (
            <Reveal key={p.name} delay={i * 90} style={{ height: '100%' }}>
              <FamilyCard p={p} onOpen={() => setOpen(p)} />
            </Reveal>
          ))}
        </div>
      </div>

      {open && <ProductModal p={open} onClose={() => setOpen(null)} />}

      <style>{`@media (max-width: 760px){ .familia-grid{ grid-template-columns: 1fr !important; } }`}</style>
    </section>
  );
}

function FamilyCard({ p, onOpen }) {
  const [hover, setHover] = useFam(false);
  return (
    <div
      onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
      style={{ height: '100%', display: 'flex', flexDirection: 'column', background: 'var(--white)', border: `1px solid ${hover ? 'var(--peach)' : 'var(--line)'}`, borderRadius: 24, padding: 'clamp(26px, 3vw, 40px)', transition: 'transform .25s cubic-bezier(.2,.7,.2,1), box-shadow .25s, border-color .25s', transform: hover ? 'translateY(-5px)' : 'none', boxShadow: hover ? 'var(--shadow-md)' : 'var(--shadow-sm)' }}
    >
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 22 }}>
        <span style={{ width: 52, height: 52, borderRadius: 14, display: 'grid', placeItems: 'center', background: 'var(--terra)', color: 'var(--paper)' }}>
          <Icon name={p.icon} size={26} />
        </span>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 7, fontFamily: 'var(--mono)', fontSize: 11, fontWeight: 600, letterSpacing: '.12em', textTransform: 'uppercase', color: 'var(--done)' }}>
          <span style={{ width: 7, height: 7, borderRadius: '50%', background: 'var(--done)' }} /> {p.status}
        </span>
      </div>

      <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, flexWrap: 'wrap' }}>
        <span className="serif-display" style={{ fontSize: 'clamp(30px, 3.6vw, 42px)', color: 'var(--ink)', fontStyle: 'normal' }}>{p.name}</span>
        {p.flagship && (
          <span style={{ fontSize: 10.5, fontWeight: 700, letterSpacing: '.1em', textTransform: 'uppercase', color: 'var(--terra-deep)', background: 'var(--peach-soft)', borderRadius: 999, padding: '4px 9px', alignSelf: 'center' }}>Principal</span>
        )}
      </div>

      <p className="serif-display" style={{ fontSize: 'clamp(19px, 2vw, 23px)', color: 'var(--ink)', lineHeight: 1.3, marginTop: 16 }}>{p.tagline}</p>
      <p style={{ fontSize: 15, color: 'var(--ink-soft)', lineHeight: 1.55, marginTop: 12 }}>{p.desc}</p>

      <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginTop: 20 }}>
        {p.modules.map(m => (
          <span key={m} style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--ink-soft)', background: 'var(--cream)', border: '1px solid var(--line-soft)', borderRadius: 999, padding: '6px 13px' }}>{m}</span>
        ))}
      </div>

      <div style={{ marginTop: 'auto', paddingTop: 28, display: 'flex', gap: 10, flexWrap: 'wrap' }}>
        <button onClick={onOpen} className={p.flagship ? 'btn btn-primary' : 'btn btn-ink'}>
          Ver o {p.name} por dentro <Icon name="arrow" size={18} />
        </button>
        <a href="#conviver" className="btn btn-ghost">Falar com a gente</a>
      </div>
    </div>
  );
}

// ── Inside modal (gallery for shots, else faux screens) ──────
function ProductModal({ p, onClose }) {
  const hasShots = !!(p.shots && p.shots.length);
  const [idx, setIdx] = useFam(0);
  const [tab, setTab] = useFam(p.screens ? p.screens[0] : null);
  const n = hasShots ? p.shots.length : 0;
  const [lidOpen, setLidOpen] = useFam(false);

  useFamEffect(() => {
    const onKey = (e) => {
      if (e.key === 'Escape') onClose();
      if (hasShots && e.key === 'ArrowRight') setIdx(i => (i + 1) % n);
      if (hasShots && e.key === 'ArrowLeft') setIdx(i => (i + n - 1) % n);
    };
    document.addEventListener('keydown', onKey);
    document.body.style.overflow = 'hidden';
    const t = setTimeout(() => setLidOpen(true), 180); // abre a tampa ao surgir
    return () => { document.removeEventListener('keydown', onKey); document.body.style.overflow = ''; clearTimeout(t); };
  }, [n]);

  const shot = hasShots ? p.shots[idx] : null;

  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, zIndex: 1000, background: 'rgba(26,18,12,0.6)', backdropFilter: 'blur(6px)', WebkitBackdropFilter: 'blur(6px)', display: 'grid', placeItems: 'center', padding: 'clamp(12px, 3vw, 40px)', animation: 'pmFade .25s ease' }}>
      <div onClick={e => e.stopPropagation()} style={{ width: '100%', maxWidth: hasShots ? 1080 : 880, maxHeight: '92vh', overflowY: 'auto', background: 'var(--paper)', borderRadius: 'var(--radius-lg)', boxShadow: 'var(--shadow-lg)', animation: 'pmRise .3s cubic-bezier(.2,.7,.2,1)' }} className="pm-scroll">
        {/* header */}
        <div style={{ position: 'sticky', top: 0, zIndex: 2, background: 'var(--paper)', borderBottom: '1px solid var(--line)', padding: 'clamp(16px,2.2vw,24px) clamp(20px,3vw,32px)', display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16 }}>
          <div>
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 9 }}>
              <span className="serif-display" style={{ fontSize: 24, color: 'var(--ink)' }}>{p.name}</span>
            </div>
            <div style={{ fontSize: 13.5, color: 'var(--ink-soft)', marginTop: 2 }}>{p.tagline}</div>
          </div>
          <button onClick={onClose} aria-label="Fechar" style={{ flexShrink: 0, border: '1px solid var(--line)', background: 'var(--white)', width: 40, height: 40, borderRadius: '50%', display: 'grid', placeItems: 'center', color: 'var(--ink-soft)' }}>
            <Icon name="x" size={18} />
          </button>
        </div>

        {hasShots ? (
          <div style={{ padding: 'clamp(18px,2.4vw,26px) clamp(20px,3vw,32px) clamp(24px,3vw,32px)' }}>
            {/* notebook: a tampa abre ao surgir */}
            <div style={{ perspective: 1800, maxWidth: 880, margin: '0 auto' }}>
              <div style={{ transformOrigin: '50% 100%', transition: 'transform .75s cubic-bezier(.4,.05,.2,1)', transform: lidOpen ? 'rotateX(0deg)' : 'rotateX(-88deg)' }}>
                <div style={{ position: 'relative', background: '#1b1815', borderRadius: 'clamp(12px,1.4vw,16px) clamp(12px,1.4vw,16px) 6px 6px', padding: 'clamp(8px,1vw,11px)', boxShadow: '0 40px 80px -34px rgba(0,0,0,.5)', border: '1px solid #2c2825' }}>
                  <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 'clamp(4px,.5vw,6px)' }}>
                    <span style={{ width: 5, height: 5, borderRadius: '50%', background: '#39342f' }} />
                  </div>
                  <div style={{ position: 'relative', borderRadius: 6, overflow: 'hidden', background: '#000' }}>
                    <img key={shot.src} src={shot.src} alt={shot.label} style={{ display: 'block', width: '100%', height: 'auto', animation: 'shotFade .3s ease' }} />
                    {/* prev / next */}
                    <button onClick={() => setIdx(i => (i + n - 1) % n)} aria-label="Anterior" style={navBtn('left')}><Icon name="arrow-left" size={20} stroke={2.2} /></button>
                    <button onClick={() => setIdx(i => (i + 1) % n)} aria-label="Próximo" style={navBtn('right')}><Icon name="arrow" size={20} stroke={2.2} /></button>
                    {/* counter */}
                    <div style={{ position: 'absolute', top: 12, right: 12, background: 'rgba(26,18,12,0.7)', color: 'var(--paper)', fontFamily: 'var(--mono)', fontSize: 12, fontWeight: 600, borderRadius: 999, padding: '4px 11px' }}>{idx + 1} / {n}</div>
                  </div>
                </div>
              </div>
              {/* base / deck */}
              <div style={{ position: 'relative', height: 16, marginTop: -1 }}>
                <div style={{ width: '108%', marginLeft: '-4%', height: '100%', background: 'linear-gradient(180deg,#dad3c9 0%,#b6ad9f 100%)', borderRadius: '0 0 14px 14px', boxShadow: '0 18px 30px -16px rgba(0,0,0,.45)' }}>
                  <div style={{ width: 'clamp(70px,9vw,108px)', height: 7, background: '#9c9388', borderRadius: '0 0 9px 9px', margin: '0 auto' }} />
                </div>
              </div>
            </div>

            {/* caption */}
            <div style={{ marginTop: 20, textAlign: 'center' }}>
              <div className="serif-display" style={{ fontSize: 21 }}>{shot.label}</div>
              <div style={{ fontSize: 14, color: 'var(--ink-soft)', marginTop: 2 }}>{shot.sub}</div>
            </div>

            {/* thumbnails */}
            <div style={{ display: 'flex', gap: 10, justifyContent: 'center', flexWrap: 'wrap', marginTop: 18 }}>
              {p.shots.map((s, i) => (
                <button key={s.src} onClick={() => setIdx(i)} aria-label={s.label}
                  style={{ width: 92, height: 58, borderRadius: 9, overflow: 'hidden', border: `2px solid ${i === idx ? 'var(--terra)' : 'var(--line)'}`, padding: 0, background: 'var(--white)', opacity: i === idx ? 1 : 0.6, transition: 'opacity .15s, border-color .15s' }}>
                  <img src={s.src} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover', objectPosition: 'top left' }} />
                </button>
              ))}
            </div>

            <div style={{ display: 'flex', justifyContent: 'center', marginTop: 24 }}>
              <a href="#conviver" onClick={onClose} className="btn btn-primary btn-lg">Quero o {p.name} na minha operação <Icon name="arrow" size={19} /></a>
            </div>
          </div>
        ) : (
          <React.Fragment>
            <div style={{ display: 'flex', gap: 6, padding: '16px clamp(20px,3vw,32px) 0', flexWrap: 'wrap' }}>
              {p.screens.map(s => (
                <button key={s} onClick={() => setTab(s)}
                  style={{ border: 0, borderRadius: 999, padding: '9px 16px', fontSize: 14, fontWeight: 600, transition: 'all .18s', background: tab === s ? 'var(--terra)' : 'var(--cream)', color: tab === s ? 'var(--paper)' : 'var(--ink-soft)' }}>
                  {s}
                </button>
              ))}
            </div>
            <div style={{ padding: 'clamp(18px,2.4vw,26px) clamp(20px,3vw,32px) clamp(24px,3vw,34px)' }}>
              <div style={{ background: 'var(--white)', border: '1px solid var(--line)', borderRadius: 'var(--radius)', padding: 'clamp(16px,2.4vw,24px)', minHeight: 320 }}>
                <Screen product={p.name} tab={tab} />
              </div>
              <div style={{ display: 'flex', justifyContent: 'center', marginTop: 22 }}>
                <a href="#conviver" onClick={onClose} className="btn btn-primary btn-lg">Quero o {p.name} na minha operação <Icon name="arrow" size={19} /></a>
              </div>
            </div>
          </React.Fragment>
        )}
      </div>
      <style>{`
        @keyframes pmFade { from { opacity: 0; } to { opacity: 1; } }
        @keyframes pmRise { from { opacity: 0; transform: translateY(16px) scale(.98); } to { opacity: 1; transform: none; } }
        @keyframes shotFade { from { opacity: 0; } to { opacity: 1; } }
        .pm-scroll{ scrollbar-width: thin; }
      `}</style>
    </div>
  );
}

function navBtn(side) {
  return {
    position: 'absolute', top: '50%', transform: 'translateY(-50%)', [side]: 12,
    width: 44, height: 44, borderRadius: '50%', border: 0,
    background: 'rgba(250,244,234,0.92)', color: 'var(--ink)',
    display: 'grid', placeItems: 'center', boxShadow: 'var(--shadow-md)', cursor: 'pointer',
  };
}

// ── Eat faux screens ─────────────────────────────────────────
function ScreenHead({ title, sub, right }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, marginBottom: 16, flexWrap: 'wrap' }}>
      <div>
        <div className="serif-display" style={{ fontSize: 22 }}>{title}</div>
        <div style={{ fontSize: 13, color: 'var(--ink-faint)' }}>{sub}</div>
      </div>
      {right && <div style={{ fontFamily: 'var(--mono)', fontSize: 13, color: 'var(--terra-deep)', fontWeight: 600 }}>{right}</div>}
    </div>
  );
}

function StatRow({ items }) {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: `repeat(${items.length}, 1fr)`, gap: 12, marginBottom: 16 }}>
      {items.map(([l, v, c]) => (
        <div key={l} style={{ background: 'var(--cream)', border: '1px solid var(--line-soft)', borderRadius: 14, padding: '14px 15px' }}>
          <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--ink-faint)', textTransform: 'uppercase', letterSpacing: '.05em' }}>{l}</div>
          <div className="serif-display" style={{ fontSize: 28, marginTop: 5, color: c || 'var(--ink)' }}>{v}</div>
        </div>
      ))}
    </div>
  );
}

function Screen({ product, tab }) {
  if (product === 'Eat' && tab === 'Caixa') {
    const bars = [40, 55, 38, 70, 62, 88, 95, 72];
    return (<div>
      <ScreenHead title="Caixa de hoje" sub="Quinta · movimento da casa" right="R$ 8.420 no dia" />
      <StatRow items={[['Vendas', 'R$ 8.420'], ['Ticket médio', 'R$ 96'], ['A receber', 'R$ 1.180', 'var(--terra-deep)']]} />
      <div style={{ background: 'var(--cream)', border: '1px solid var(--line-soft)', borderRadius: 12, padding: '16px 16px 10px' }}>
        <div style={{ fontSize: 13, fontWeight: 600, marginBottom: 12 }}>Vendas por hora</div>
        <div style={{ display: 'flex', alignItems: 'flex-end', gap: 8, height: 90 }}>
          {bars.map((h, i) => <div key={i} style={{ flex: 1, height: `${h}%`, background: i === 6 ? 'var(--terra)' : 'var(--peach)', borderRadius: '6px 6px 0 0' }} />)}
        </div>
        <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 10.5, color: 'var(--ink-faint)', marginTop: 6, fontFamily: 'var(--mono)' }}>
          <span>18h</span><span>20h</span><span>22h</span><span>00h</span>
        </div>
      </div>
    </div>);
  }
  if (product === 'Eat' && tab === 'Comandas') {
    const mesas = [['01', 'Aberta', 'R$ 142', 'var(--terra)'], ['02', 'Fechando', 'R$ 308', 'var(--waiting)'], ['03', 'Livre', '—', 'var(--ink-faint)'], ['04', 'Aberta', 'R$ 96', 'var(--terra)'], ['05', 'Aberta', 'R$ 214', 'var(--terra)'], ['06', 'Livre', '—', 'var(--ink-faint)'], ['07', 'Fechando', 'R$ 175', 'var(--waiting)'], ['08', 'Aberta', 'R$ 60', 'var(--terra)']];
    return (<div>
      <ScreenHead title="Comandas e mesas" sub="Salão em tempo real" right="6 mesas ativas" />
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 12 }}>
        {mesas.map(([nu, st, v, c]) => (
          <div key={nu} style={{ background: 'var(--cream)', border: '1px solid var(--line-soft)', borderRadius: 12, padding: '14px 12px', textAlign: 'center' }}>
            <div className="serif-display" style={{ fontSize: 26 }}>{nu}</div>
            <div style={{ fontSize: 11.5, fontWeight: 700, color: c, textTransform: 'uppercase', letterSpacing: '.04em', marginTop: 2 }}>{st}</div>
            <div style={{ fontFamily: 'var(--mono)', fontSize: 13, marginTop: 6 }}>{v}</div>
          </div>
        ))}
      </div>
    </div>);
  }
  if (product === 'Eat' && tab === 'Estoque') {
    const items = [['Chopp Pilsen', 78, 'ok'], ['Hambúrguer 180g', 22, 'baixo'], ['Batata congelada', 64, 'ok'], ['Gin', 12, 'ruptura'], ['Queijo prato', 41, 'ok']];
    const tint = s => s === 'ruptura' ? 'var(--terra)' : s === 'baixo' ? 'var(--waiting)' : 'var(--done)';
    return (<div>
      <ScreenHead title="Estoque" sub="Nível atual e alertas" right="2 itens em atenção" />
      <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
        {items.map(([nm, lvl, s]) => (
          <div key={nm} style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
            <div style={{ width: 150, fontSize: 14, fontWeight: 500, flexShrink: 0 }}>{nm}</div>
            <div style={{ flex: 1, height: 12, background: 'var(--cream)', borderRadius: 999, overflow: 'hidden', border: '1px solid var(--line-soft)' }}>
              <div style={{ width: `${lvl}%`, height: '100%', background: tint(s), borderRadius: 999 }} />
            </div>
            <div style={{ width: 76, textAlign: 'right', fontSize: 11.5, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '.04em', color: tint(s) }}>{s}</div>
          </div>
        ))}
      </div>
    </div>);
  }
  return null;
}

Object.assign(window, { Produtos });
