/* PORCEVILLE — App: navegação, estado global */

const PORCE_TABS = [
  { id: 'feed', label: 'Início', icon: 'home' },
  { id: 'produtos', label: 'Produtos', icon: 'grid' },
  { id: 'caco', label: 'Caco', icon: 'spark', center: true },
  { id: 'orcamento', label: 'Orçamento', icon: 'doc' },
  { id: 'enviados', label: 'Enviados', icon: 'clock' },
];

function PorceTabBar({ app }) {
  return (
    <div style={{ flex: 'none', position: 'relative', zIndex: 40, display: 'flex', alignItems: 'flex-end', justifyContent: 'space-around', height: 76, paddingBottom: 18, background: 'rgba(255,255,255,.94)', backdropFilter: 'blur(16px) saturate(160%)', WebkitBackdropFilter: 'blur(16px) saturate(160%)', borderTop: '1px solid var(--line)', boxShadow: 'var(--sh-tab)' }}>
      {PORCE_TABS.filter(t => t.id !== 'caco' || ((PORCE_DATA.settings && PORCE_DATA.settings.caco) || {}).enabled !== false).map(t => {
        const active = app.tab === t.id;
        if (t.center) {
          return (
            <button key={t.id} onClick={() => app.go(t.id)} style={{ position: 'relative', border: 'none', background: 'none', cursor: 'pointer', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 3, marginTop: -22 }}>
              <div style={{ width: 54, height: 54, borderRadius: '50%', background: 'var(--navy)', border: '3px solid var(--gold)', display: 'flex', alignItems: 'center', justifyContent: 'center', boxShadow: '0 8px 20px rgba(29,53,87,.4)' }}>
                <span style={{ fontFamily: 'var(--font-display)', color: 'var(--gold)', fontSize: 24 }}>C</span>
              </div>
              <span style={{ fontSize: 10.5, fontWeight: 800, color: active ? 'var(--gold-700)' : 'var(--ink-soft)' }}>{t.label}</span>
            </button>
          );
        }
        return (
          <button key={t.id} onClick={() => app.go(t.id)} style={{ position: 'relative', border: 'none', background: 'none', cursor: 'pointer', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4, width: 62, paddingTop: 4 }}>
            <div style={{ position: 'relative' }}>
              <PIcon name={t.icon} size={24} stroke={active ? 'var(--navy)' : 'var(--ink-mute)'} sw={active ? 2.2 : 1.8} />
              {t.id === 'orcamento' && app.quoteCount > 0 && <span className="dot-badge" style={{ borderColor: 'rgba(255,255,255,.94)' }}>{app.quoteCount}</span>}
            </div>
            <span style={{ fontSize: 10.5, fontWeight: active ? 800 : 700, color: active ? 'var(--navy)' : 'var(--ink-soft)' }}>{t.label}</span>
          </button>
        );
      })}
    </div>
  );
}

// eventos de conversão pros pixels já instalados (tracking.js injeta gtag/fbq/ttq/dataLayer)
function PORCE_TRACK(ev, data) {
  try {
    const d = data || {};
    if (window.dataLayer) window.dataLayer.push({ event: ev, ...d });
    if (typeof window.gtag === 'function') window.gtag('event', ev, d);
    if (typeof window.fbq === 'function') window.fbq('trackCustom', ev, d);
    if (typeof window.ttq === 'object' && window.ttq.track) window.ttq.track(ev, d);
    // conversão oficial do Google Ads no evento de lead (send_to = id/label do admin)
    const t = window.PORCE_TRACKING_CFG || {};
    if (ev === 'generate_lead' && t.gads_id && t.gads_label && typeof window.gtag === 'function') {
      window.gtag('event', 'conversion', { send_to: `${t.gads_id}/${t.gads_label}` });
    }
  } catch (e) {}
}
window.PORCE_TRACK = PORCE_TRACK;

function usePorceState() {
  const [tab, setTab] = React.useState('feed');
  const [productsCat, setProductsCat] = React.useState('todos');
  const [quote, setQuote] = React.useState(() => {
    try {
      const raw = JSON.parse(localStorage.getItem('porce_quote') || '[]');
      return Array.isArray(raw) ? raw.filter(e => e && e.productId && PORCE_DATA.getProduct(e.productId)) : [];
    } catch (e) { return []; }
  });
  const [sent, setSent] = React.useState(() => {
    try { const raw = JSON.parse(localStorage.getItem('porce_sent') || '[]'); return Array.isArray(raw) ? raw : []; } catch (e) { return []; }
  });
  React.useEffect(() => { try { localStorage.setItem('porce_quote', JSON.stringify(quote)); } catch (e) {} }, [quote]);
  React.useEffect(() => { try { localStorage.setItem('porce_sent', JSON.stringify(sent)); } catch (e) {} }, [sent]);
  const [caco, setCaco] = React.useState([]);
  const [detailId, setDetailId] = React.useState(null);
  const [storyIndex, setStoryIndex] = React.useState(null);
  const [seenStories, setSeenStories] = React.useState([]);
  const [admin, setAdmin] = React.useState(false);
  const [capturing, setCapturing] = React.useState(false);
  const [cartOpen, setCartOpen] = React.useState(false);
  const [landing, setLanding] = React.useState(true);

  const quoteCount = quote.length;

  const app = {
    tab, quote, quoteCount, sent, caco, productsCat,
    seenStories, storyIndex, detailId, admin, capturing, landing, cartOpen,
    go: setTab,
    setLanding,
    goHome: () => { setLanding(true); setTab('feed'); },
    openCart: () => setCartOpen(true),
    closeCart: () => setCartOpen(false),
    openAdmin: () => setAdmin(true),
    closeAdmin: () => setAdmin(false),
    openProducts: (cat) => { setProductsCat(cat || 'todos'); setTab('produtos'); },
    openDetail: (id) => { PORCE_TRACK('view_item', { item_id: id }); setDetailId(id); },
    closeDetail: () => setDetailId(null),
    addToQuote: (entry) => { PORCE_TRACK('add_to_cart', { item_id: entry.productId, quantity: entry.qty }); return setQuote(p => {
      const i = p.findIndex(e => e.productId === entry.productId && e.colors === entry.colors && e.piece === entry.piece && e.size === entry.size);
      if (i >= 0) { const n = [...p]; n[i] = { ...n[i], qty: n[i].qty + entry.qty }; return n; }
      return [...p, { ...entry, key: 'q' + Date.now() + Math.random().toString(36).slice(2, 5) }];
    }); },
    removeFromQuote: (key) => setQuote(p => p.filter(e => e.key !== key)),
    setQuoteQty: (key, q) => setQuote(p => p.map(e => e.key === key ? { ...e, qty: q } : e)),
    // captura de contato + gravação do pedido (mobile + desktop)
    requestSend: () => { if (quote.length) { PORCE_TRACK('begin_checkout', { items: quote.length }); try { PORCE_PING('checkout', `🟡 Visitante INICIOU envio de orçamento (${quote.length} ${quote.length === 1 ? 'item' : 'itens'}) — se não chegar o pedido completo, desistiu no formulário`); } catch (e) {} setCapturing(true); } },
    cancelSend: () => setCapturing(false),
    commitSent: ({ pieces, summary }) => {
      setSent(p => [{ id: String(101 + p.length), summary, pieces, when: 'Agora' }, ...p]);
      setQuote([]); setCapturing(false); setTab('enviados');
    },
    openStory: (i) => setStoryIndex(i),
    setStoryIndex,
    closeStory: () => setStoryIndex(null),
    markStorySeen: (id) => setSeenStories(p => p.includes(id) ? p : [...p, id]),
    pushCaco: (m) => setCaco(p => [...p, m]),
  };
  return app;
}

// lê texto da landing do site_content (com fallback) — editável no editor visual
const LC = (f, d) => { const c = (window.PORCE_DATA && window.PORCE_DATA.content && window.PORCE_DATA.content.landing) || {}; return (c[f] != null && c[f] !== '') ? c[f] : d; };
const HEROIMG = () => { const h = (window.PORCE_DATA && window.PORCE_DATA.content && window.PORCE_DATA.content.hero) || {}; return h.image_mobile || undefined; };

function MobileLanding({ onEnter }) {
  // capa = banner formato story (base: banner do site original porceville.com.br); editável via content.landing.capa_story
  const capa = LC('capa_story', 'uploads/banner/capa-story.jpg');
  return (
    <div className="porc-app porc-landing" style={{ position: 'relative', height: '100%', background: 'var(--porc-bg)', overflow: 'hidden' }}>
      <img data-edit-img="landing.capa_story" src={capa} alt="Porceville — brindes personalizados"
        style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover' }} />
      {/* CTA real por cima da capa */}
      <div className="lz" style={{ position: 'absolute', left: 0, right: 0, bottom: 0, padding: '14px 24px 36px', background: 'linear-gradient(180deg, transparent, rgba(244,243,240,.92) 55%)', '--d': '200ms' }}>
        <button className="btn btn-navy btn-block" style={{ padding: 17, fontSize: 16 }} onClick={onEnter}>
          {PORCE_TX('cta_capa', 'Ver catálogo')}
        </button>
      </div>
    </div>
  );
}

function PorceApp({ app }) {
  const screens = {
    feed: <PorceFeedScreen app={app} />,
    produtos: <PorceProductsScreen app={app} />,
    caco: <CacoScreen app={app} />,
    orcamento: <PorceQuoteScreen app={app} />,
    enviados: <PorceHistoryScreen app={app} />,
  };

  return (
    <div className="porc-app" style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      {app.landing ? (
        <MobileLanding onEnter={() => { React.startTransition(() => { app.setLanding(false); app.go('feed'); }); }} />
      ) : (
        <>
          <FloatBar />
          <div style={{ flex: 1, position: 'relative', overflow: 'hidden' }}>
            {screens[app.tab]}
          </div>
          <PorceTabBar app={app} />
          {!app.detailId && app.storyIndex === null && !app.capturing && !app.admin && <WhatsFab bottom={92} />}
        </>
      )}
      {app.detailId && <PorceProductDetail app={app} />}
      {app.storyIndex !== null && <PorceStoryViewer app={app} />}
      {app.admin && <AdminPanel app={app} />}
      {app.capturing && <OrderCaptureModal app={app} />}
      {!app.landing && !app.detailId && app.storyIndex === null && <CupomPopup />}
    </div>
  );
}

function PorceRoot() {
  const app = usePorceState();
  // deep-link ?p=<id> (botão "Ver no site" do admin) abre direto o detalhe do produto
  React.useEffect(() => {
    try {
      const pid = new URLSearchParams(window.location.search).get('p');
      if (pid && PORCE_DATA.getProduct(pid)) { app.setLanding(false); app.openDetail(pid); }
    } catch (e) {}
  }, []);
  const forced = (typeof window !== 'undefined' && new URLSearchParams(window.location.search).get('view')) || null;
  const [desktop, setDesktop] = React.useState(() => forced ? forced === 'desktop' : (typeof window !== 'undefined' && window.innerWidth >= 980));
  React.useEffect(() => {
    if (forced) return;
    const f = () => setDesktop(window.innerWidth >= 980);
    window.addEventListener('resize', f);
    return () => window.removeEventListener('resize', f);
  }, [forced]);

  if (desktop) return <PorceDesktop app={app} />;

  // celular DE VERDADE (tela estreita): app em tela cheia, sem moldura — a moldura de iPhone
  // estourava a largura em aparelhos reais. Moldura fica só como preview no desktop (?view=mobile) ou ?frame=1.
  const telaEstreita = typeof window !== 'undefined' && window.innerWidth < 700;
  const querMoldura = forced === 'mobile' || (typeof window !== 'undefined' && new URLSearchParams(window.location.search).get('frame') === '1');
  if (telaEstreita && !querMoldura) {
    return (
      <div style={{ height: '100dvh', width: '100vw', overflow: 'hidden', background: 'var(--porc-bg)' }}>
        <PorceApp app={app} />
      </div>
    );
  }

  return (
    <div style={{ minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'radial-gradient(120% 120% at 50% 0%, #22436e, #14263F)', padding: 20 }}>
      <IOSDevice>
        <PorceApp app={app} />
      </IOSDevice>
    </div>
  );
}

// Error Boundary — impede que um registro malformado (ex.: story sem slides) derrube a loja inteira em tela branca.
class PorceErrorBoundary extends React.Component {
  constructor(props) { super(props); this.state = { error: null }; }
  static getDerivedStateFromError(error) { return { error }; }
  componentDidCatch(error, info) { try { console.error('[porce] erro de render:', error, info); } catch (e) {} }
  render() {
    if (this.state.error) {
      const wa = `https://wa.me/${(window.PORCE_DATA && PORCE_DATA.WHATS) || '5547991626122'}?text=${encodeURIComponent('Olá, Porceville! Tive um problema no site e gostaria de falar com vocês.')}`;
      return (
        <div style={{ minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'radial-gradient(120% 120% at 50% 0%, #22436e, #14263F)', padding: 24, fontFamily: 'system-ui, sans-serif' }}>
          <div style={{ maxWidth: 360, textAlign: 'center', color: '#fff' }}>
            <div style={{ fontSize: 22, fontWeight: 800, marginBottom: 10 }}>Tivemos um probleminha aqui</div>
            <p style={{ fontSize: 14.5, opacity: .85, lineHeight: 1.5, margin: '0 0 22px' }}>Recarregue a página. Se continuar, fale com a gente no WhatsApp que resolvemos seu pedido na hora.</p>
            <div style={{ display: 'flex', gap: 10, justifyContent: 'center', flexWrap: 'wrap' }}>
              <button onClick={() => window.location.reload()} style={{ padding: '12px 20px', borderRadius: 12, border: 'none', background: '#C9A86A', color: '#14263F', fontWeight: 800, fontSize: 14.5, cursor: 'pointer' }}>Recarregar</button>
              <a href={wa} target="_blank" rel="noopener noreferrer" style={{ padding: '12px 20px', borderRadius: 12, background: '#25D366', color: '#fff', fontWeight: 800, fontSize: 14.5, textDecoration: 'none' }}>Falar no WhatsApp</a>
            </div>
          </div>
        </div>
      );
    }
    return this.props.children;
  }
}

function PORCE_MOUNT() { ReactDOM.createRoot(document.getElementById('root')).render(<PorceErrorBoundary><PorceRoot /></PorceErrorBoundary>); }
// aguarda o loader do Supabase (porce/store.js) preencher os dados; se não houver, renderiza já.
if (window.PORCE_READY && typeof window.PORCE_READY.then === 'function') {
  window.PORCE_READY.then(PORCE_MOUNT);
} else {
  PORCE_MOUNT();
}
