/* ProductDetail — fullscreen overlay; zoomed hero + tabs (Overview/Specs/HowTo/Assembly) */
const ProductDetail = ({ lang, product, onClose }) => {
  const [tab, setTab] = React.useState('overview');
  const [currentImageIndex, setCurrentImageIndex] = React.useState(0); // Image carousel state
  
  if (!product) return null;

  const cat = window.CATALOG.categories[product.category];

  // Determine if this is an accessory product
  const isAccessory = cat && cat.folder === 'accessories';

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

  // Get all images for carousel
  const images = product.images || [product.hero];
  const currentImage = images[currentImageIndex] || product.hero;

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

  // Pick a few highlight specs for overview
  const wantedHighlights = [
    'Μέγιστο βάρος εξασκούμενου','Βάρος εξασκούμενου','Μέγιστη ταχύτητα',
    'Ιπποδύναμη μοτέρ','Επίπεδα αντίστασης','Διαστάσεις τάπητα τρεξίματος',
    'Μέγιστο βάρος φόρτωσης','Διαστάσεις, συναρμολογημένο',
    'Πεντάλ με ιμάντα','Αναδίπλωση','Εγγύηση','ΕΓΓΥΗΣΗ '
  ];
  const highlights = [];
  wantedHighlights.forEach(lbl => {
    const s = product.specs.find(x => (x.label_el || x.label) === lbl);
    if (s && !highlights.find(h => (h.label_el || h.label) === lbl)) highlights.push(s);
  });
  while (highlights.length < 4 && highlights.length < product.specs.length) {
    const next = product.specs[highlights.length];
    if (!highlights.find(h => (h.label_el || h.label) === (next.label_el || next.label))) highlights.push(next);
    else break;
  }

  const stop = (e) => e.stopPropagation();
  
  // Get bilingual product name
  const productName = lang === 'el' ? (product.name_el || product.name || product.code) : (product.name_en || product.name || product.code);

  return (
    <div className="product-detail-overlay" onClick={onClose}>
      <div className="product-detail" onClick={stop}>
        <div className="detail-header">
          <div className="detail-header-main">
            <div className="detail-eyebrow">
              <span className="detail-brand">ENERGETICS</span>
              <span className="detail-cat">{lang === 'el' ? cat.label_el : cat.label_en}</span>
            </div>
            <h2 className="detail-title">{productName}</h2>
            <div className="detail-code">
              <span>{t('code_label', lang)}:</span> <strong>{product.code}</strong>
            </div>
          </div>
          <button className="detail-close" onClick={onClose} aria-label="Close">
            <Icon name="close" size={22} />
          </button>
        </div>

        <div className="detail-body">
          <div className="detail-hero">
            {product.hero_folded && !currentImageIndex ? (
              <div className="detail-hero-duo">
                <div className="detail-hero-single">
                  <img src={product.hero} alt={productName} title={lang === 'el' ? 'Κανονική θέση' : 'Normal position'} />
                </div>
                <div className="detail-hero-single">
                  <img src={product.hero_folded} alt={`${productName} folded`} title={lang === 'el' ? 'Διπλωμένη θέση' : 'Folded position'} />
                </div>
              </div>
            ) : (
              <img src={currentImage} alt={productName} />
            )}
            <div className="detail-hero-tag">{product.code}</div>
            
            {/* Image carousel navigation */}
            {images.length > 1 && (
              <div className="detail-image-carousel">
                <button 
                  className="carousel-btn prev"
                  onClick={() => setCurrentImageIndex((currentImageIndex - 1 + images.length) % images.length)}
                  title={lang === 'el' ? 'Προηγούμενη εικόνα' : 'Previous image'}
                >
                  <Icon name="arrowLeft" size={20} />
                </button>
                <div className="carousel-counter">
                  {currentImageIndex + 1} / {images.length}
                </div>
                <button 
                  className="carousel-btn next"
                  onClick={() => setCurrentImageIndex((currentImageIndex + 1) % images.length)}
                  title={lang === 'el' ? 'Επόμενη εικόνα' : 'Next image'}
                >
                  <Icon name="arrowRight" size={20} />
                </button>
              </div>
            )}
          </div>

          <div className="detail-info">
            <div className="detail-tabs">
              {(['overview','specs','howto'].concat(isAccessory ? [] : ['assembly'])).map(k => (
                <button
                  key={k}
                  className={`detail-tab ${tab === k ? 'on' : ''}`}
                  onClick={() => setTab(k)}
                >
                  {t('tab_' + k, lang)}
                </button>
              ))}
            </div>

            <div className="detail-tab-body">
              {tab === 'overview' && (
                <div className="overview-pane">
                  <div className="badges">
                    <span className="badge"><Icon name="shield" size={16}/> {t('certified', lang)}</span>
                    <span className="badge"><Icon name="check" size={16}/> {t('warranty', lang)}: 2 {t('warranty_years', lang)}</span>
                  </div>
                  <ul className="highlights">
                    {highlights.map((h,i) => (
                      <li key={i}>
                        <span className="hl-label">{specLabel(h)}</span>
                        <span className="hl-value">{specValue(h)}</span>
                      </li>
                    ))}
                  </ul>
                  <div className="price-block">
                    <span className="price-label">{t('price_label', lang)}</span>
                    <span className="price-value">
                      {lang==='el' ? product.priceLabel_el : product.priceLabel_en}
                    </span>
                  </div>
                </div>
              )}

              {tab === 'specs' && (
                <div className="specs-pane">
                  {Object.keys(grouped).map(sec => (
                    <div key={sec} className="spec-group">
                      {sec !== '—' && <h4 className="spec-group-title">{sectionLabel(sec)}</h4>}
                      <table className="spec-table">
                        <tbody>
                          {grouped[sec].map((s,i) => (
                            <tr key={i}>
                              <th>{specLabel(s)}</th>
                              <td>{specValue(s)}</td>
                            </tr>
                          ))}
                        </tbody>
                      </table>
                    </div>
                  ))}
                </div>
              )}

              {tab === 'howto' && (
                <VideoPlaceholder lang={lang} kind="howto" src={product.video_howto} />
              )}

              {tab === 'assembly' && (
                <VideoPlaceholder lang={lang} kind="assembly" src={product.video_assembly} />
              )}
            </div>
          </div>
        </div>

      </div>
    </div>
  );
};

const VideoPlaceholder = ({ lang, kind, src }) => {
  if (src) {
    return (
      <div className="video-placeholder">
        <video controls width="100%" style={{ borderRadius: '12px', maxHeight: '100%' }}>
          <source src={src} type="video/mp4" />
          {t('video_unsupported', lang)}
        </video>
      </div>
    );
  }
  
  return (
    <div className="video-placeholder">
      <div className="vp-frame">
        <Icon name="play" size={56} />
        <p>{t('video_placeholder', lang)}</p>
        <span className="vp-kind">{t('tab_' + kind, lang)}</span>
      </div>
    </div>
  );
};

window.ProductDetail = ProductDetail;
