// ProductPage.jsx — /producto/<handle>
//
// Per-product detail page. Fetches the catalog via window.Shop, finds the
// product by handle, and renders a two-column layout: image gallery on the
// left, title + price + description + add-to-cart on the right. Optional
// metadata-driven sections (subtitle, ingredients, how_to_use, badge) light
// up when set on the Stripe product.
//
// Per-product SEO + Product JSON-LD so Google can show price + availability
// in rich results.
//
// Stripe product metadata read (all optional, set per product in the
// Stripe Dashboard → Metadata):
//   subtitle      — italic one-liner under the title
//   ingredients   — items separated by `|` (or commas)  →  bulleted list
//   how_to_use    — paragraphs (use `\n\n` between)     →  "Cómo usarlo"
//   badge         — pill text on the image (e.g. NUEVO, BESTSELLER)
//   handle        — pretty URL slug (otherwise the Stripe product ID)

const productPageStyles = {
  page: { background: '#fff' },

  // ---- Hero (breadcrumb strip) ---------------------------------------------
  hero: {
    background: 'var(--brand-cream)',
    borderBottom: '1px solid var(--color-divider)',
    padding: '32px 0 24px',
  },
  heroInner: { maxWidth: 1200, margin: '0 auto', padding: '0 32px' },
  breadcrumb: {
    display: 'flex', alignItems: 'center', gap: 8,
    fontFamily: 'var(--font-sans)', fontSize: 12, fontWeight: 600,
    letterSpacing: '0.14em', textTransform: 'uppercase',
    color: 'var(--color-fg-muted)',
  },
  breadcrumbLink: { color: 'inherit', textDecoration: 'none' },
  breadcrumbSep: { opacity: 0.4 },
  breadcrumbCurrent: { color: 'var(--color-fg-strong)' },

  // ---- Main (image + info) -------------------------------------------------
  main: { padding: '56px 0 80px' },
  mainInner: {
    maxWidth: 1200, margin: '0 auto', padding: '0 32px',
    display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 64,
    alignItems: 'flex-start',
  },

  // Image column
  gallery: { display: 'flex', flexDirection: 'column', gap: 14 },
  mainImg: {
    width: '100%', aspectRatio: '1 / 1',
    borderRadius: 16, overflow: 'hidden',
    background: 'var(--brand-mint-wash)',
    display: 'flex', alignItems: 'center', justifyContent: 'center',
    position: 'relative',
  },
  mainImgImg: { width: '100%', height: '100%', objectFit: 'cover', display: 'block' },
  mainImgFallback: {
    fontFamily: 'var(--font-serif)', fontStyle: 'italic',
    color: 'var(--brand-leaf)', fontSize: 72,
  },
  badge: {
    position: 'absolute', top: 16, left: 16, zIndex: 2,
    padding: '5px 12px', borderRadius: 9999,
    background: 'var(--brand-coral)', color: '#fff',
    fontFamily: 'var(--font-sans)', fontSize: 11, fontWeight: 700,
    letterSpacing: '0.14em', textTransform: 'uppercase',
  },
  thumbs: { display: 'flex', gap: 10, flexWrap: 'wrap' },
  thumb: {
    width: 72, height: 72, borderRadius: 10, overflow: 'hidden',
    border: '2px solid transparent', cursor: 'pointer',
    background: 'var(--brand-mint-wash)', padding: 0,
  },
  thumbActive: { borderColor: 'var(--brand-leaf)' },
  thumbImg: { width: '100%', height: '100%', objectFit: 'cover', display: 'block' },

  // Info column
  info: { display: 'flex', flexDirection: 'column' },
  title: {
    fontFamily: 'var(--font-serif)', fontWeight: 700,
    fontSize: 40, lineHeight: 1.1, letterSpacing: '-0.01em',
    color: 'var(--color-fg-strong)', margin: '0 0 10px',
    textWrap: 'balance',
  },
  subtitle: {
    fontFamily: 'var(--font-serif)', fontStyle: 'italic',
    fontSize: 18, lineHeight: 1.45, color: 'var(--color-fg-muted)',
    margin: '0 0 20px',
  },
  price: {
    fontFamily: 'var(--font-sans)', fontWeight: 700, fontSize: 28,
    color: '#151414', margin: '0 0 24px',
  },
  description: {
    fontFamily: 'var(--font-sans)', fontSize: 16, lineHeight: 1.7,
    color: 'var(--color-fg)', margin: '0 0 28px', whiteSpace: 'pre-wrap',
  },
  addBtn: {
    display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
    gap: 10, width: '100%',
    padding: '16px 22px', borderRadius: 10,
    background: 'var(--brand-leaf)', color: '#fff', border: 'none',
    fontFamily: 'var(--font-sans)', fontSize: 15, fontWeight: 700,
    letterSpacing: '0.04em', cursor: 'pointer',
    transition: 'background 200ms var(--ease-out)',
  },
  addBtnDisabled: { background: '#C9C5C0', cursor: 'not-allowed' },
  hint: {
    fontFamily: 'var(--font-sans)', fontSize: 12,
    color: 'var(--color-fg-muted)', marginTop: 12, textAlign: 'center',
  },

  // ---- Optional metadata sections ------------------------------------------
  detailsWrap: { background: 'var(--brand-cream)', padding: '64px 0' },
  detailsInner: { maxWidth: 760, margin: '0 auto', padding: '0 32px' },
  detailsBlock: { marginBottom: 40 },
  detailsLabel: {
    fontFamily: 'var(--font-sans)', fontWeight: 700,
    fontSize: 12, letterSpacing: '0.22em', textTransform: 'uppercase',
    color: 'var(--brand-leaf)', marginBottom: 14,
  },
  detailsTitle: {
    fontFamily: 'var(--font-serif)', fontWeight: 700,
    fontSize: 26, color: 'var(--color-fg-strong)', margin: '0 0 18px',
  },
  ingList: {
    fontFamily: 'var(--font-sans)', fontSize: 16, lineHeight: 1.7,
    color: 'var(--color-fg)', paddingLeft: 22, margin: 0,
  },
  howToUse: {
    fontFamily: 'var(--font-sans)', fontSize: 16, lineHeight: 1.75,
    color: 'var(--color-fg)', margin: 0, whiteSpace: 'pre-wrap',
  },

  // ---- Related -------------------------------------------------------------
  relatedWrap: { background: '#fff', padding: '72px 0 96px', borderTop: '1px solid var(--color-divider)' },
  relatedInner: { maxWidth: 1200, margin: '0 auto', padding: '0 32px' },
  relatedHead: { marginBottom: 28 },
  relatedTitle: {
    fontFamily: 'var(--font-serif)', fontWeight: 700,
    fontSize: 28, color: 'var(--color-fg-strong)', margin: 0,
  },
  relatedGrid: {
    display: 'grid',
    gridTemplateColumns: 'repeat(auto-fit, minmax(240px, 300px))',
    justifyContent: 'center', gap: 24,
  },

  loading: {
    minHeight: '40vh',
    display: 'flex', alignItems: 'center', justifyContent: 'center',
    fontFamily: 'var(--font-serif)', fontStyle: 'italic',
    fontSize: 20, color: 'var(--color-fg-muted)',
  },
};

// Parse `metadata.ingredients` into a list. Accepts pipes, semicolons, or
// commas as separators; trims whitespace; drops empties.
function parseIngredients(raw) {
  if (!raw) return [];
  return String(raw)
    .split(/[|;\n]|,(?![^()]*\))/g)
    .map(s => s.trim())
    .filter(Boolean);
}

// Short plain-text description, capped at ~160 chars for meta description / OG.
function shortDescription(s, max) {
  const flat = String(s || '').replace(/\s+/g, ' ').trim();
  if (flat.length <= (max || 160)) return flat;
  return flat.slice(0, (max || 160) - 1).trimEnd() + '…';
}

function ProductPage({ productHandle }) {
  const lang = React.useContext(LangContext);
  const tr = useT();
  const isMobile = useIsMobile();
  const [products, setProducts] = React.useState(null);
  const [loading,  setLoading]  = React.useState(true);
  const [activeImg, setActiveImg] = React.useState(0);
  const [addedToast, setAddedToast] = React.useState(false);

  // Fetch the catalog (cached after first call) and find this product.
  React.useEffect(() => {
    let cancelled = false;
    setActiveImg(0);
    (async () => {
      if (!window.Shop || !window.Shop.fetchProducts) {
        if (!cancelled) { setProducts([]); setLoading(false); }
        return;
      }
      const list = await window.Shop.fetchProducts();
      if (cancelled) return;
      setProducts(list || []);
      setLoading(false);
    })();
    const onShop = (e) => { if (!cancelled) setProducts(e.detail || []); };
    window.addEventListener('tnt-shop-updated', onShop);
    return () => { cancelled = true; window.removeEventListener('tnt-shop-updated', onShop); };
  }, [productHandle]);

  const product = React.useMemo(() => {
    if (!products) return null;
    return products.find(p => p.handle === productHandle)
        || products.find(p => p.id === productHandle)
        || null;
  }, [products, productHandle]);

  // SEO — runs once product is resolved.
  React.useEffect(() => {
    if (!product) return;
    const canonical = SEO.url(buildPath({ view: 'product', productHandle: product.handle || product.id }));
    const desc = shortDescription(product.description) || (lang === 'es' ? 'Disponible en Top Natural Tips.' : 'Available at Top Natural Tips.');
    const ogImage = product.image || SEO.url('/og-image.jpg');
    updateSeo({
      title: product.title,
      description: desc,
      canonical,
      ogType: 'product',
      ogImage,
      lang,
      jsonLd: {
        '@context': 'https://schema.org',
        '@type': 'Product',
        name: product.title,
        image: (product.images && product.images.length) ? product.images : (product.image ? [product.image] : undefined),
        description: desc,
        sku: product.id,
        brand: { '@type': 'Brand', name: 'Top Natural Tips' },
        offers: {
          '@type': 'Offer',
          url: canonical,
          priceCurrency: product.currency || 'USD',
          price: (product.priceAmount != null) ? product.priceAmount : undefined,
          availability: product.available ? 'https://schema.org/InStock' : 'https://schema.org/OutOfStock',
        },
      },
    });
  }, [product, lang]);

  // Loading
  if (loading) {
    return <div style={productPageStyles.loading}>{lang === 'es' ? 'Cargando…' : 'Loading…'}</div>;
  }
  // Not found — defer to the soft 404 page (consistent with the rest of the site).
  if (!product) {
    return <NotFoundPage/>;
  }

  // ---------- derived bits ----------
  const md = product.metadata || {};
  const subtitle = md.subtitle || md.meta || '';
  const ingredients = parseIngredients(md.ingredients);
  const howToUse = (md.how_to_use || md.how_to_use_md || '').trim();
  const badge = md.badge ? String(md.badge).toUpperCase() : null;
  const images = (product.images && product.images.length) ? product.images : (product.image ? [product.image] : []);
  const mainImageSrc = images[activeImg] || product.image || null;
  const buyable = !!(product.defaultVariantId && product.available !== false);

  const related = (products || [])
    .filter(p => p && p.handle !== product.handle && p.defaultVariantId)
    .slice(0, 3);

  // ---------- handlers ----------
  const addToCart = () => {
    if (!buyable || !window.Shop) return;
    window.Shop.addLine(product.defaultVariantId, 1, {
      title: product.title,
      price: product.price,
      priceAmount: product.priceAmount,
      image: product.image,
      handle: product.handle,
    });
    window.dispatchEvent(new CustomEvent('app:open-cart'));
    // tiny "added" pulse on the button label (visual confirmation in case the
    // drawer is off-screen on the right)
    setAddedToast(true);
    setTimeout(() => setAddedToast(false), 1500);
  };

  const T = lang === 'es' ? {
    home: 'Inicio', shop: 'Tienda',
    add: 'Añadir al carrito', added: '✓ Añadido',
    soon: 'Próximamente',
    hint: 'Envío e impuestos calculados en el checkout.',
    ingredientsLabel: 'Ingredientes',
    ingredientsTitle: 'Qué contiene',
    howToUseLabel: 'Cómo usarlo',
    howToUseTitle: 'Modo de uso',
    related: 'Más en la tienda',
  } : {
    home: 'Home', shop: 'Shop',
    add: 'Add to cart', added: '✓ Added',
    soon: 'Coming soon',
    hint: 'Shipping and taxes calculated at checkout.',
    ingredientsLabel: 'Ingredients',
    ingredientsTitle: 'What it contains',
    howToUseLabel: 'How to use',
    howToUseTitle: 'How to use it',
    related: 'More from the shop',
  };

  return (
    <main style={productPageStyles.page}>

      {/* Breadcrumb hero */}
      <header style={{ ...productPageStyles.hero, ...(isMobile ? { padding: '24px 0 18px' } : {}) }}>
        <div style={{ ...productPageStyles.heroInner, ...(isMobile ? { padding: '0 20px' } : {}) }}>
          <nav style={productPageStyles.breadcrumb} aria-label="Breadcrumb">
            <a href={hrefFor({ view: 'home' })} style={productPageStyles.breadcrumbLink}>{T.home}</a>
            <span style={productPageStyles.breadcrumbSep}>/</span>
            <a href={hrefFor({ view: 'shop' })} style={productPageStyles.breadcrumbLink}>{T.shop}</a>
            <span style={productPageStyles.breadcrumbSep}>/</span>
            <span style={productPageStyles.breadcrumbCurrent} aria-current="page">{product.title}</span>
          </nav>
        </div>
      </header>

      {/* Main — image + info */}
      <section style={{ ...productPageStyles.main, ...(isMobile ? { padding: '32px 0 56px' } : {}) }}>
        <div style={{ ...productPageStyles.mainInner,
                      ...(isMobile ? { gridTemplateColumns: '1fr', gap: 28, padding: '0 20px' } : {}) }}>

          {/* Image column */}
          <div style={productPageStyles.gallery}>
            <div style={productPageStyles.mainImg}>
              {badge && <span style={productPageStyles.badge}>{badge}</span>}
              {mainImageSrc
                ? <img src={mainImageSrc} alt={product.title} style={productPageStyles.mainImgImg}/>
                : <span style={productPageStyles.mainImgFallback}>{(product.title || '·').slice(0, 1)}</span>}
            </div>

            {images.length > 1 && (
              <div style={productPageStyles.thumbs} role="tablist" aria-label="Product images">
                {images.slice(0, 6).map((src, i) => (
                  <button key={src + i}
                          type="button"
                          role="tab"
                          aria-selected={i === activeImg}
                          aria-label={`Image ${i + 1}`}
                          onClick={() => setActiveImg(i)}
                          style={{ ...productPageStyles.thumb, ...(i === activeImg ? productPageStyles.thumbActive : {}) }}>
                    <img src={src} alt="" loading="lazy" style={productPageStyles.thumbImg}/>
                  </button>
                ))}
              </div>
            )}
          </div>

          {/* Info column */}
          <div style={productPageStyles.info}>
            <h1 style={{ ...productPageStyles.title, ...(isMobile ? { fontSize: 30 } : {}) }}>{product.title}</h1>
            {subtitle && <p style={productPageStyles.subtitle}>{subtitle}</p>}
            <p style={productPageStyles.price}>{product.price}</p>
            {product.description && <p style={productPageStyles.description}>{product.description}</p>}

            <button
              style={{ ...productPageStyles.addBtn, ...(buyable ? {} : productPageStyles.addBtnDisabled) }}
              disabled={!buyable}
              onClick={addToCart}
              aria-label={T.add}>
              <ShoppingBag size={18}/>
              {addedToast ? T.added : (buyable ? T.add : T.soon)}
            </button>
            <p style={productPageStyles.hint}>{T.hint}</p>
          </div>

        </div>
      </section>

      {/* Optional metadata-driven sections */}
      {(ingredients.length || howToUse) && (
        <section style={productPageStyles.detailsWrap}>
          <div style={{ ...productPageStyles.detailsInner, ...(isMobile ? { padding: '0 20px' } : {}) }}>
            {ingredients.length > 0 && (
              <div style={productPageStyles.detailsBlock}>
                <div style={productPageStyles.detailsLabel}>{T.ingredientsLabel}</div>
                <h2 style={productPageStyles.detailsTitle}>{T.ingredientsTitle}</h2>
                <ul style={productPageStyles.ingList}>
                  {ingredients.map((it, i) => <li key={i} style={{ marginBottom: 4 }}>{it}</li>)}
                </ul>
              </div>
            )}
            {howToUse && (
              <div style={productPageStyles.detailsBlock}>
                <div style={productPageStyles.detailsLabel}>{T.howToUseLabel}</div>
                <h2 style={productPageStyles.detailsTitle}>{T.howToUseTitle}</h2>
                <p style={productPageStyles.howToUse}>{howToUse}</p>
              </div>
            )}
          </div>
        </section>
      )}

      {/* Related products */}
      {related.length > 0 && (
        <section style={productPageStyles.relatedWrap}>
          <div style={{ ...productPageStyles.relatedInner, ...(isMobile ? { padding: '0 20px' } : {}) }}>
            <div style={productPageStyles.relatedHead}>
              <h2 style={productPageStyles.relatedTitle}>{T.related}</h2>
            </div>
            <div style={{ ...productPageStyles.relatedGrid, ...(isMobile ? { gridTemplateColumns: 'repeat(2, 1fr)', justifyContent: 'stretch', gap: 14 } : {}) }}>
              {related.map(p => (
                <ShopProductCard key={p.id || p.handle}
                                 product={window.stripeToCard ? window.stripeToCard(p) : {
                                   title: p.title, meta: '', price: p.price, priceAmount: p.priceAmount,
                                   image: p.image, tint: 'var(--brand-mint-wash)', badge: null, rating: null,
                                   defaultVariantId: p.defaultVariantId, available: p.available, handle: p.handle,
                                 }}/>
              ))}
            </div>
          </div>
        </section>
      )}

    </main>
  );
}

window.ProductPage = ProductPage;
