/* PORCEVILLE — Feed (estilo Instagram) + Stories */

const porceIconBtn = { position: 'relative', width: 40, height: 40, borderRadius: '50%', border: 'none', background: 'transparent', color: 'var(--navy)', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer' };

function PorceTopBar({ app }) {
  return (
    <div style={{ position: 'sticky', top: 0, zIndex: 30, paddingTop: 54, background: 'linear-gradient(180deg, var(--porc-bg) 72%, rgba(244,243,240,0))' }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '4px 18px 10px' }}>
        <button onClick={() => app.goHome()} title="Início" style={{ border: 'none', background: 'none', cursor: 'pointer', padding: 0 }}><PorceWordmark size={20} /></button>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
          <button onClick={() => app.go('orcamento')} style={porceIconBtn} aria-label="orçamento">
            <PIcon name="doc" size={23} />
            {app.quoteCount > 0 && <span className="dot-badge">{app.quoteCount}</span>}
          </button>
        </div>
      </div>
    </div>
  );
}

function PorceStoryRow({ app }) {
  return (
    <div style={{ display: 'flex', gap: 15, padding: '4px 18px 16px', overflowX: 'auto' }}>
      {PORCE_DATA.stories.map((s, i) => (!s || !Array.isArray(s.slides) || !s.slides[0]) ? null : (
        <button key={s.id} onClick={() => app.openStory(i)}
          style={{ border: 'none', background: 'none', cursor: 'pointer', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 7, flex: 'none', width: 66 }}>
          <div style={{
            width: 66, height: 66, borderRadius: '50%', padding: 3,
            background: app.seenStories.includes(s.id) ? 'var(--line)' : 'conic-gradient(from 210deg, #C9A86A, #1D3557, #C9A86A)',
          }}>
            <div style={{ width: '100%', height: '100%', borderRadius: '50%', border: '2.5px solid var(--porc-bg)', overflow: 'hidden' }}>
              <PPhoto kind={(PORCE_DATA.getProduct(s.slides[0].productId)||{}).kind} illo={PORCE_ILLO.illoFor(PORCE_DATA.getProduct(s.slides[0].productId))} img={s.slides[0].img || (PORCE_DATA.getProduct(s.slides[0].productId)||{}).img} slot={`pstory-${s.id}`} placeholder="" style={{ width: '100%', height: '100%' }} />
            </div>
          </div>
          <span style={{ fontSize: 11.5, fontWeight: 700, color: 'var(--ink-soft)', maxWidth: 66, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{s.label}</span>
        </button>
      ))}
    </div>
  );
}

/* compre por categoria — mini-cards foto+pílula (mesma referência da home desktop), sem quebrar o feed */
function PorceCatRow({ app }) {
  const temFotoReal = p => p.img && !String(p.img).includes('falta-foto');
  const cards = PORCE_DATA.categories
    .map(c => { const p = PORCE_DATA.products.find(x => x.cat === c.id && temFotoReal(x)); return p ? { cat: c, img: p.img } : null; })
    .filter(Boolean).slice(0, 6);
  if (cards.length < 2) return null;
  return (
    <div style={{ display: 'flex', gap: 12, padding: '2px 18px 16px', overflowX: 'auto' }}>
      {cards.map(({ cat: c, img }) => (
        <button key={c.id} type="button" onClick={() => app.openProducts(c.id)}
          style={{ position: 'relative', flex: 'none', width: 128, aspectRatio: '1 / 1.05', border: 'none', padding: 0, cursor: 'pointer', borderRadius: 14, overflow: 'hidden', background: '#fff', boxShadow: '0 8px 20px rgba(13,43,90,.10)' }}>
          <img src={img} alt={c.label} style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover' }} />
          <span style={{ position: 'absolute', left: '50%', bottom: 8, transform: 'translateX(-50%)', background: 'rgba(255,255,255,.94)', color: 'var(--navy)', fontWeight: 800, fontSize: 9.5, letterSpacing: '.08em', textTransform: 'uppercase', padding: '5px 10px', borderRadius: 99, whiteSpace: 'nowrap', maxWidth: 116, overflow: 'hidden', textOverflow: 'ellipsis' }}>{c.label}</span>
        </button>
      ))}
    </div>
  );
}

function PorcePost({ post, app }) {
  const [liked, setLiked] = React.useState(false);
  const [saved, setSaved] = React.useState(false);
  const [slide, setSlide] = React.useState(0);
  const carousel = post.type === 'carousel' ? post.items.map(id => PORCE_DATA.getProduct(id)).filter(Boolean) : null;
  const product = carousel ? carousel[slide] : PORCE_DATA.getProduct(post.productId);
  if (!product) return null;   // produto removido/desativado na unificação → não derruba o feed inteiro

  return (
    <article className="fade-in" style={{ marginBottom: 6 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 16px' }}>
        <PorceAvatar size={36} />
        <div style={{ flex: 1, lineHeight: 1.2 }}>
          <div style={{ fontWeight: 800, fontSize: 14, color: 'var(--navy)' }}>porceville</div>
          <div style={{ fontSize: 12, color: 'var(--ink-mute)' }}>Personalizados · {post.time}</div>
        </div>
        <button style={{ ...porceIconBtn, width: 30 }}><span style={{ fontSize: 22, letterSpacing: 1, color: 'var(--ink-soft)' }}>···</span></button>
      </div>

      <div style={{ position: 'relative', width: '100%', aspectRatio: '4 / 5', overflow: 'hidden', cursor: 'pointer' }}
        onClick={() => app.openDetail(product.id)}>
        <PPhoto kind={product.kind} illo={PORCE_ILLO.illoFor(product)} img={product.img} slot={`pfeed-${post.id}-${carousel ? slide : 0}`} placeholder="Arraste a foto do produto" style={{ width: '100%', height: '100%' }}>
          <div style={{ position: 'absolute', left: 0, right: 0, bottom: 0, padding: '26px 16px 14px', background: 'linear-gradient(180deg, transparent, rgba(20,38,63,.55))', pointerEvents: 'none' }}>
            <div className="display" style={{ color: '#fff', fontSize: 22 }}>{displayName(product.name)}</div>
            <div style={{ color: 'rgba(255,255,255,.85)', fontSize: 12.5, fontWeight: 700 }}>{product.detail}</div>
          </div>
        </PPhoto>
        {carousel && (
          <>
            <div style={{ position: 'absolute', top: 12, right: 12, background: 'rgba(20,38,63,.55)', color: '#fff', fontSize: 12, fontWeight: 700, padding: '3px 9px', borderRadius: 99 }}>{slide + 1}/{carousel.length}</div>
            {slide > 0 && <button onClick={(e) => { e.stopPropagation(); setSlide(slide - 1); }} style={porceCarNav('left')}><PIcon name="chevron" size={18} style={{ transform: 'rotate(180deg)' }} /></button>}
            {slide < carousel.length - 1 && <button onClick={(e) => { e.stopPropagation(); setSlide(slide + 1); }} style={porceCarNav('right')}><PIcon name="chevron" size={18} /></button>}
          </>
        )}
      </div>

      <div style={{ display: 'flex', alignItems: 'center', gap: 16, padding: '11px 16px 6px' }}>
        <button style={porceActBtn} onClick={() => setLiked(!liked)}>
          <PIcon name="heart" size={25} fill={liked ? 'var(--gold)' : 'none'} stroke={liked ? 'var(--gold-700)' : 'var(--navy)'} />
        </button>
        <button style={porceActBtn}><PIcon name="comment" size={24} /></button>
        <button style={porceActBtn}><PIcon name="share" size={23} /></button>
        <div style={{ flex: 1 }} />
        <button style={porceActBtn} onClick={() => setSaved(!saved)}>
          <PIcon name="bookmark" size={24} fill={saved ? 'var(--navy)' : 'none'} />
        </button>
      </div>

      <div style={{ padding: '0 16px' }}>
        <div style={{ fontWeight: 800, fontSize: 13.5, color: 'var(--navy)' }}>{(post.likes + (liked ? 1 : 0)).toLocaleString('pt-BR')} curtidas</div>
        <div style={{ fontSize: 14, marginTop: 4, lineHeight: 1.5 }}>
          <span style={{ fontWeight: 800, color: 'var(--navy)' }}>porceville </span>
          <span>{post.caption} </span>
          <span style={{ color: 'var(--gold-700)', fontWeight: 700 }}>{post.tags.join(' ')}</span>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 12 }}>
          <div style={{ flex: 1 }}>
            <div className="quote-tag">{priceTag(product)}</div>
            <div style={{ fontSize: 11.5, color: 'var(--ink-mute)', fontWeight: 600 }}>{product.subl ? 'Sublimação sem mínimo' : `Serigrafia · mín. ${PORCE_DATA.MIN_SERI} un`}</div>
          </div>
          <button className="btn btn-navy btn-sm" onClick={() => app.openDetail(product.id)}>Adicionar ao orçamento</button>
        </div>
      </div>

      <div className="hr" style={{ margin: '16px 16px 0' }} />
    </article>
  );
}
const porceActBtn = { border: 'none', background: 'none', padding: 0, cursor: 'pointer', color: 'var(--navy)', display: 'flex', alignItems: 'center' };
const porceCarNav = (side) => ({ position: 'absolute', [side]: 10, top: '50%', transform: 'translateY(-50%)', width: 34, height: 34, borderRadius: '50%', border: 'none', background: 'rgba(20,38,63,.45)', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer' });

// Banner promocional intercalado (cupom, frete, categorias) — sem produto, imune a órfão
function PorceFeedArt({ art, app }) {
  const a = (art && art.art) || {};
  const gold = a.accent === 'gold';
  const onCta = () => {
    const act = a.cta_action || 'catalogo';
    if (act.indexOf('categoria:') === 0) app.openProducts(act.slice(10));
    else if (act === 'whatsapp') window.open('https://wa.me/' + PORCE_DATA.WHATS, '_blank');
    else if (/^https?:/.test(act)) window.open(act, '_blank');
    else app.openProducts('todos');
  };
  // arte com imagem real (banner JPG) — imagem inteira clicável
  if (a.image) {
    return (
      <article className="fade-in" style={{ margin: '4px 16px 16px', borderRadius: 18, overflow: 'hidden', cursor: 'pointer', boxShadow: 'var(--sh-card)' }} onClick={onCta}>
        <img src={a.image} alt={a.title || 'Porceville'} style={{ width: '100%', display: 'block' }} />
      </article>
    );
  }
  // arte renderizada (HTML: gradiente + título + CTA)
  return (
    <article className="fade-in" style={{ margin: '4px 16px 16px', borderRadius: 18, overflow: 'hidden', position: 'relative', minHeight: 150, display: 'flex', flexDirection: 'column', justifyContent: 'center', padding: '22px 20px', background: gold ? 'linear-gradient(135deg,#FFE680,#FFCE00)' : 'linear-gradient(135deg,#22436e,#0D2B5A)' }}>
      <div style={{ fontSize: 10.5, letterSpacing: '.16em', textTransform: 'uppercase', fontWeight: 800, color: gold ? 'var(--navy)' : 'var(--gold)' }}>Porceville</div>
      <div className="display" style={{ fontSize: 24, lineHeight: 1.1, margin: '6px 0', color: gold ? 'var(--navy)' : '#fff' }}>{a.title}</div>
      {a.subtitle && <div style={{ fontSize: 13, lineHeight: 1.4, marginBottom: 14, color: gold ? 'rgba(13,43,90,.82)' : 'rgba(255,255,255,.85)' }}>{a.subtitle}</div>}
      <button onClick={onCta} className="btn btn-sm" style={{ alignSelf: 'flex-start', border: 'none', fontWeight: 800, background: gold ? 'var(--navy)' : 'var(--gold)', color: gold ? '#fff' : 'var(--navy)' }}>{a.cta_text || 'Ver catálogo'}</button>
    </article>
  );
}

function PorceFeedScreen({ app }) {
  return (
    <div className="scroll" style={{ paddingBottom: 28 }}>
      <PorceTopBar app={app} />
      <div style={{ padding: '0 18px 16px' }}>
        <div className="eyebrow">Porcelanas &amp; vidros personalizados</div>
        <div className="h1" style={{ marginTop: 8, fontSize: 22 }}>Sua marca em cada detalhe.</div>
      </div>
      <PorceStoryRow app={app} />
      <div className="hr" style={{ margin: '0 0 4px' }} />
      {(() => {
        const posts = PORCE_DATA.feed.filter(f => f.type !== 'arte');
        const artes = PORCE_DATA.feed.filter(f => f.type === 'arte');
        // 1 arte a cada 2 produtos (teto); se há artes demais p/ poucos posts, espaça menos
        // pra distribuir uniformemente em vez de empilhar no fim.
        const spacing = artes.length ? Math.max(1, Math.min(2, Math.floor(posts.length / artes.length))) : 99;
        const out = []; let ai = 0;
        posts.forEach((p, i) => {
          out.push(<PorcePost key={p.id} post={p} app={app} />);
          if ((i + 1) % spacing === 0 && ai < artes.length) { out.push(<PorceFeedArt key={artes[ai].id} art={artes[ai]} app={app} />); ai++; }
        });
        while (ai < artes.length) { out.push(<PorceFeedArt key={artes[ai].id} art={artes[ai]} app={app} />); ai++; }
        return out;
      })()}
      <div style={{ textAlign: 'center', color: 'var(--ink-mute)', fontSize: 13, fontWeight: 600, padding: '24px 0 8px' }}>
        Transformando ideias em peças que permanecem. ✨
      </div>
    </div>
  );
}

function PorceStoryViewer({ app }) {
  const story = PORCE_DATA.stories[app.storyIndex];
  const [slide, setSlide] = React.useState(0);
  const DURATION = 5000;
  React.useEffect(() => { setSlide(0); }, [app.storyIndex]);
  React.useEffect(() => {
    const t = setTimeout(() => next(), DURATION);
    return () => clearTimeout(t);
  }, [slide, app.storyIndex]);
  React.useEffect(() => { app.markStorySeen(story.id); }, [app.storyIndex]);

  const next = () => {
    if (slide < story.slides.length - 1) setSlide(slide + 1);
    else if (app.storyIndex < PORCE_DATA.stories.length - 1) app.setStoryIndex(app.storyIndex + 1);
    else app.closeStory();
  };
  const prev = () => {
    if (slide > 0) setSlide(slide - 1);
    else if (app.storyIndex > 0) app.setStoryIndex(app.storyIndex - 1);
  };

  const data = story.slides[slide];
  const product = PORCE_DATA.getProduct(data.productId) || {};
  const cover = data.img || product.img;

  return (
    <div style={{ position: 'absolute', inset: 0, zIndex: 120, background: 'var(--navy-deep)' }}>
      <PPhoto kind={product.kind} illo={cover ? undefined : PORCE_ILLO.illoFor(product)} img={cover} slot={`pstoryfull-${story.id}-${slide}`} placeholder="Arraste a arte do story (9:16)" style={{ position: 'absolute', inset: 0 }} />
      <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(180deg, rgba(20,38,63,.5) 0%, transparent 22%, transparent 55%, rgba(20,38,63,.78) 100%)', pointerEvents: 'none' }} />
      <div style={{ position: 'absolute', inset: 0, display: 'flex', zIndex: 5 }}>
        <div style={{ flex: 1 }} onClick={prev} />
        <div style={{ flex: 1.4 }} onClick={next} />
      </div>
      <div style={{ position: 'absolute', top: 54, left: 12, right: 12, display: 'flex', gap: 5, zIndex: 10 }}>
        {story.slides.map((_, i) => (
          <div key={i} style={{ flex: 1, height: 3, borderRadius: 99, background: 'rgba(255,255,255,.35)', overflow: 'hidden' }}>
            <div style={{ height: '100%', background: '#fff', width: i < slide ? '100%' : i === slide ? '100%' : '0%', animation: i === slide ? `growBar ${DURATION}ms linear` : 'none' }} />
          </div>
        ))}
      </div>
      <div style={{ position: 'absolute', top: 66, left: 14, right: 14, display: 'flex', alignItems: 'center', gap: 10, zIndex: 10 }}>
        <PorceAvatar size={32} />
        <span style={{ color: '#fff', fontWeight: 800, fontSize: 14 }}>porceville</span>
        <span style={{ color: 'rgba(255,255,255,.7)', fontSize: 13 }}>{story.label}</span>
        <div style={{ flex: 1 }} />
        <button onClick={app.closeStory} style={{ ...porceIconBtn, color: '#fff' }}><PIcon name="close" size={26} stroke="#fff" /></button>
      </div>
      <div style={{ position: 'absolute', left: 0, right: 0, bottom: 0, padding: '0 24px 40px', zIndex: 10, textAlign: 'center', pointerEvents: 'none' }}>
        <div className="display" style={{ color: 'var(--gold)', fontSize: 15, letterSpacing: '.14em', textTransform: 'uppercase' }}>{data.headline}</div>
        <div className="display" style={{ color: '#fff', fontSize: 34, margin: '6px 0 6px' }}>{displayName(product.name)}</div>
        <div style={{ color: 'rgba(255,255,255,.88)', fontSize: 14, fontWeight: 600, marginBottom: 18 }}>{data.sub}</div>
        <button className="btn btn-gold btn-block" style={{ pointerEvents: 'auto', padding: '15px', fontSize: 16 }}
          onClick={() => { app.closeStory(); app.openDetail(product.id); }}>
          Adicionar ao orçamento
        </button>
      </div>
    </div>
  );
}

Object.assign(window, { PorceFeedScreen, PorceStoryViewer, PorceTopBar });
