/* ProductGrid — grid + elevated in-place product focus (no modal) */

const ProductGrid = ({ lang, categoryId, onSelect, onBack, selectedProduct, onClearProduct, onVideoChange }) => {
  const [showVideo, setShowVideo] = React.useState(null); // null | 'usage' | 'assembly'
  const [phase, setPhase] = React.useState(selectedProduct ? 'focus' : 'grid'); // 'grid' | 'fading' | 'focus'
  const [currentSlide, setCurrentSlide] = React.useState(1); // Pagination state

  React.useEffect(() => {
    if (onVideoChange) onVideoChange(!!showVideo);
  }, [showVideo]);
  
  // Reset slide when category changes
  React.useEffect(() => {
    setCurrentSlide(1);
  }, [categoryId]);

  const cat = window.CATALOG;
  const category = cat.categories[categoryId];
  const allProducts = cat.getProductsByCategory(categoryId) || [];
  
  // Group products by slide and get current slide's products
  const productsBySlide = {};
  allProducts.forEach(p => {
    const slideNum = p.slide || 1;
    if (!productsBySlide[slideNum]) productsBySlide[slideNum] = [];
    productsBySlide[slideNum].push(p);
  });
  
  const slideNumbers = Object.keys(productsBySlide).map(Number).sort((a, b) => a - b);
  const totalSlides = slideNumbers.length;
  const products = productsBySlide[currentSlide] || [];
  
  const isPlaceholder = !!(category && category.placeholder) || allProducts.length === 0;
  const categoryName = lang === 'el' ? category.label_el : category.label_en;

  // Drive a brief "fading" phase so cards smoothly disappear before the focus view enters.
  // Use a ref-backed timer so the cleanup tied to dep changes doesn't cancel our own scheduled flip.
  const phaseTimerRef = React.useRef(null);
  React.useEffect(() => {
    if (phaseTimerRef.current) {
      clearTimeout(phaseTimerRef.current);
      phaseTimerRef.current = null;
    }
    if (selectedProduct) {
      setPhase('fading');
      phaseTimerRef.current = setTimeout(() => {
        setPhase('focus');
        phaseTimerRef.current = null;
      }, 280);
    } else {
      setPhase('grid');
      setShowVideo(null);
    }
    return () => {
      if (phaseTimerRef.current) {
        clearTimeout(phaseTimerRef.current);
        phaseTimerRef.current = null;
      }
    };
  }, [selectedProduct]);

  // Reset video sub-view when product changes
  React.useEffect(() => {
    setShowVideo(null);
  }, [selectedProduct ? selectedProduct.id : null]);

  // Distribute images evenly: divide container into N equal slots, center each image in its slot
  const getImageStyle = (imgIdx, totalImages) => {
    const xPercent = ((imgIdx + 0.5) / totalImages) * 100;
    const maxW = `${Math.round(86 / totalImages)}%`;
    return {
      left: `${xPercent}%`,
      transform: 'translate(-50%, -50%)',
      maxWidth: maxW,
      opacity: 1,
    };
  };

  /* ---------- GRID VIEW (no product selected, or fading out) ---------- */
  if (!selectedProduct || phase === 'fading') {
    return (
      <section
        className={`product-grid-screen${phase === 'fading' ? ' is-leaving' : ''}`}
        data-screen-label="products"
      >
        <header className="screen-head">
          <h2>{categoryName}</h2>
        </header>

        {isPlaceholder ? (
          <div className="placeholder-block">
            <div className="placeholder-icon"><Icon name={category.icon || 'box-m'} size={120} /></div>
            <h3>{t('no_products', lang)}</h3>
            <p>{t('placeholder_text', lang)}</p>
          </div>
        ) : (
          <>
            <div className="product-grid">
              {products.map((p, idx) => {
                const pname = lang === 'el' ? (p.name_el || p.code) : (p.name_en || p.code);
                const isTarget = phase === 'fading' && selectedProduct && p.id === selectedProduct.id;
                const images = p.images || [p.hero];
                return (
                  <button
                    key={p.id}
                    className={`product-card${phase === 'fading' ? (isTarget ? ' is-rising' : ' is-fading') : ''}`}
                    onClick={(e) => { e.stopPropagation(); if (phase === 'grid') onSelect(p.id); }}
                    style={{ '--card-i': idx }}
                  >
                    <div className="product-card-img">
                      {/* Stack all images in clockwise pattern for depth effect */}
                      {images.map((img, imgIdx) => (
                        <img
                          key={imgIdx}
                          src={img}
                          alt={pname}
                          loading="lazy"
                          className="product-card-image"
                          style={{
                            zIndex: images.length - imgIdx,
                            ...getImageStyle(imgIdx, images.length)
                          }}
                        />
                      ))}
                    </div>
                    <div className="product-card-code">{p.code}</div>
                    <div className="product-card-name">{pname}</div>
                  </button>
                );
              })}
            </div>
            
            {/* Pagination controls */}
            {totalSlides > 1 && (
              <div className="product-pagination">
                <div className="pagination-buttons">
                  {slideNumbers.map(slideNum => (
                    <button
                      key={slideNum}
                      className={`pagination-btn ${currentSlide === slideNum ? 'active' : ''}`}
                      onClick={() => setCurrentSlide(slideNum)}
                    >
                      {slideNum}
                    </button>
                  ))}
                </div>
              </div>
            )}
          </>
        )}
      </section>
    );
  }

  /* ---------- FOCUS VIEW (product selected) ---------- */
  const product = selectedProduct;
  const productName = lang === 'el' ? (product.name_el || product.code) : (product.name_en || product.code);
  const catInfo = window.CATALOG.categories[product.category];
  const catName = lang === 'el' ? catInfo.label_el : catInfo.label_en;
  const isAccessory = catInfo.folder === 'accessories';
  const isPlaceholderProduct = !!product.placeholder;

  // Group specs by section
  const grouped = {};
  product.specs.forEach(s => {
    const sec = s.section || '—';
    if (!grouped[sec]) grouped[sec] = [];
    grouped[sec].push(s);
  });

  // Friendly section titles
  const sectionLabel = (sec) => {
    const map = {
      'ΠΡΟΔΙΑΓΡΑΦΕΣ': lang === 'el' ? 'Προδιαγραφές' : 'Specifications',
      'ΔΙΑΣΤΑΣΕΙΣ':   lang === 'el' ? 'Διαστάσεις'   : 'Dimensions',
      'ΥΠΟΛΟΓΙΣΤΗΣ':  lang === 'el' ? 'Υπολογιστής'  : 'Computer',
      'ΠΛΗΡΟΦΟΡΙΕΣ':  lang === 'el' ? 'Πληροφορίες'  : 'Information',
    };
    return map[sec] || sec;
  };

  // Forward-compatible per-spec translation: prefer label_el/label_en if present.
  const specLabel = (s) => lang === 'el' ? (s.label_el || s.label) : (s.label_en || s.label);
  const specValue = (s) => lang === 'el' ? (s.value_el || s.value) : (s.value_en || s.value);

  // Distribute spec sections to left/right columns, balancing by item count
  const sectionList = Object.keys(grouped).filter(s => s !== '—');
  const leftSections = [];
  const rightSections = [];
  let leftWeight = 0;
  let rightWeight = 0;
  // Stable preferred sides so the layout is predictable across products
  const preferredLeft  = new Set(['ΠΡΟΔΙΑΓΡΑΦΕΣ', 'ΠΛΗΡΟΦΟΡΙΕΣ']);
  const preferredRight = new Set(['ΔΙΑΣΤΑΣΕΙΣ', 'ΥΠΟΛΟΓΙΣΤΗΣ']);
  sectionList.forEach(sec => {
    const w = grouped[sec].length;
    if (preferredLeft.has(sec))       { leftSections.push(sec);  leftWeight += w; }
    else if (preferredRight.has(sec)) { rightSections.push(sec); rightWeight += w; }
    else if (leftWeight <= rightWeight) { leftSections.push(sec);  leftWeight += w; }
    else                                 { rightSections.push(sec); rightWeight += w; }
  });

  // Video availability
  const hasUsageVideo    = ('video_usage' in product) || ('video_howto' in product);
  const hasAssemblyVideo = ('video_assembly' in product) && !isAccessory;

  /* ---------- VIDEO SUB-VIEW ---------- */
  if (showVideo) {
    const videoUrl = showVideo === 'assembly' ? product.video_assembly : (product.video_usage || product.video_howto);
    const videoTitle = showVideo === 'assembly'
      ? (lang === 'el' ? 'Βίντεο Συναρμολόγησης' : 'Assembly Video')
      : (lang === 'el' ? 'Βίντεο Χρήσης'         : 'How-To Video');

    return (
      <section className="product-grid-screen product-focus-view">
        <div className="focus-stage focus-stage-video">
          <div className="focus-top-bar">
            <div className="focus-title-block">
              <div className="focus-eyebrow">
                <span className="focus-cat-chip">{catName}</span>
                <span className="focus-code-line">{product.code}</span>
              </div>
              <h2 className="focus-title">{videoTitle}</h2>
            </div>
            <div className="focus-actions">
              <button className="focus-action-btn focus-action-back" onClick={() => setShowVideo(null)}>
                <Icon name="arrowLeft" size={14} />
                <span>{lang === 'el' ? 'Επιστροφή' : 'Return'}</span>
              </button>
            </div>
          </div>

          <div className="focus-video-area">
            {videoUrl ? (
              <video controls autoPlay key={videoUrl}>
                <source src={videoUrl} type="video/mp4" />
                {t('video_unsupported', lang)}
              </video>
            ) : (
              <div className="focus-video-empty">
                <Icon name="play" size={56} />
                <p>{lang === 'el' ? 'Το βίντεο θα προστεθεί σύντομα' : 'Video coming soon'}</p>
              </div>
            )}
          </div>
        </div>
      </section>
    );
  }

  /* ---------- MAIN FOCUS LAYOUT ---------- */
  return (
    <section className="product-grid-screen product-focus-view">
      <div className="focus-stage">
        {/* Top bar — title group on the left, action buttons on the right */}
        <div className="focus-top-bar">
          <div className="focus-title-block">
            <div className="focus-eyebrow">
              <span className="focus-brand">ENERGETICS</span>
              <span className="focus-eyebrow-sep">•</span>
              <span className="focus-cat-chip">{catName}</span>
            </div>
            <h2 className="focus-title">{productName}</h2>
            <div className="focus-code-line">
              <span className="focus-code-dim">{t('code_label', lang)}</span>
              <strong>{product.code}</strong>
            </div>
          </div>

          <div className="focus-actions">
            {hasUsageVideo && (
              <button className="focus-action-btn" onClick={() => setShowVideo('usage')}>
                <Icon name="play" size={13} />
                <span>{lang === 'el' ? 'Βίντεο Χρήσης' : 'How to Use'}</span>
              </button>
            )}
            {hasAssemblyVideo && (
              <button className="focus-action-btn" onClick={() => setShowVideo('assembly')}>
                <Icon name="play" size={13} />
                <span>{lang === 'el' ? 'Συναρμολόγηση' : 'Assembly'}</span>
              </button>
            )}
            <button className="focus-action-btn focus-action-back" onClick={onClearProduct}>
              <Icon name="arrowLeft" size={14} />
              <span>{lang === 'el' ? 'Πίσω' : 'Back'}</span>
            </button>
          </div>
        </div>

        {/* Three-column main: specs L | product | specs R */}
        <div className="focus-main">
          {/* Left specs */}
          <aside className="focus-side focus-side-left">
            {leftSections.length > 0 && leftSections.map((sec, i) => (
              <div key={sec} className="focus-spec-card" style={{ '--enter-i': i }}>
                <div className="focus-spec-card-head">{sectionLabel(sec)}</div>
                <ul className="focus-spec-list">
                  {grouped[sec].map((s, j) => (
                    <li key={j} className="focus-spec-row">
                      <span className="focus-spec-key">{specLabel(s)}</span>
                      <span className="focus-spec-val">{specValue(s)}</span>
                    </li>
                  ))}
                </ul>
              </div>
            ))}
            {!isAccessory && (
              <div className="focus-trust-card" style={{ '--enter-i': leftSections.length }}>
                <div className="focus-trust-row">
                  <Icon name="shield" size={15} />
                  <span>CE • EN-957</span>
                </div>
                <div className="focus-trust-row">
                  <Icon name="check" size={15} />
                  <span>{lang === 'el' ? 'Εγγύηση 2 έτη' : '2-Year Warranty'}</span>
                </div>
              </div>
            )}
          </aside>

          {/* Center — product hero */}
          <div className="focus-center">
            <div className="focus-image-glow" aria-hidden="true"></div>
            <div className="focus-image-stage">
              {product.hero_folded && product.hero_computer ? (
                <div className="focus-image-trio">
                  <div className="focus-image-slot focus-image-slot--hero">
                    <img src={product.hero} alt={productName} />
                    <span className="focus-image-tag">{product.hero_tag || product.code}</span>
                  </div>
                  <div className="focus-image-slot">
                    <img src={product.hero_folded} alt={`${productName} folded`} />
                    <span className="focus-image-tag">{product.hero_folded_tag || (lang === 'el' ? 'Διπλωμένο' : 'Folded')}</span>
                  </div>
                  <div className="focus-image-slot">
                    <img src={product.hero_computer} alt={`${productName} computer`} />
                    <span className="focus-image-tag">{product.hero_computer_tag || (lang === 'el' ? 'Υπολογιστής' : 'Computer')}</span>
                  </div>
                </div>
              ) : product.hero_folded ? (
                <div className="focus-image-duo">
                  <div className="focus-image-slot focus-image-slot--hero">
                    <img src={product.hero} alt={productName} />
                    <span className="focus-image-tag">{product.hero_tag || product.code}</span>
                  </div>
                  <div className="focus-image-slot">
                    <img src={product.hero_folded} alt={`${productName} folded`} />
                    <span className="focus-image-tag">{product.hero_folded_tag || (lang === 'el' ? 'Διπλωμένο' : 'Folded')}</span>
                  </div>
                </div>
              ) : (
                <img className="focus-image-hero" src={product.hero} alt={productName} />
              )}
            </div>
          </div>

          {/* Right specs */}
          <aside className="focus-side focus-side-right">
            {rightSections.length > 0 && rightSections.map((sec, i) => (
              <div key={sec} className="focus-spec-card" style={{ '--enter-i': i }}>
                <div className="focus-spec-card-head">{sectionLabel(sec)}</div>
                <ul className="focus-spec-list">
                  {grouped[sec].map((s, j) => (
                    <li key={j} className="focus-spec-row">
                      <span className="focus-spec-key">{specLabel(s)}</span>
                      <span className="focus-spec-val">{specValue(s)}</span>
                    </li>
                  ))}
                </ul>
              </div>
            ))}
          </aside>
        </div>
      </div>
    </section>
  );
};

window.ProductGrid = ProductGrid;
