import React, { Component } from 'react';
import { withProduct } from '../context/ProductContext.js';
import { withCategory } from '../context/CategoryContext.js';

// Utility function to clean product names (duplicated from ProductDetailPage to ensure consistency)
const cleanProductName = (name) => {
  if (!name) return "";
  // Remove patterns like " (1)", " (3)", " (10)" at the end of the string
  return name.replace(/\s*\(\d+\)\s*$/, "").trim();
};

class TitleUpdater extends Component {
  componentDidMount() {
    this.updateTitle();
  }

  componentDidUpdate(prevProps) {
    console.log('TitleUpdater: Update triggered', {
      prevProduct: prevProps.productContext.currentProduct,
      currProduct: this.props.productContext.currentProduct,
      prevCategory: prevProps.categoryContext.currentCategory,
      currCategory: this.props.categoryContext.currentCategory
    });
    if (
      prevProps.productContext.currentProduct !== this.props.productContext.currentProduct ||
      prevProps.categoryContext.currentCategory !== this.props.categoryContext.currentCategory
    ) {
      this.updateTitle();
    }
  }

  updateTitle() {
    const { currentProduct } = this.props.productContext;
    const { currentCategory } = this.props.categoryContext;

    console.log('TitleUpdater: Updating title with', { currentProduct, currentCategory });

    if (currentProduct && currentProduct.name) {
      document.title = `GrowHeads.de - ${cleanProductName(currentProduct.name)}`;
    } else if (currentCategory && currentCategory.name) {
      document.title = `GrowHeads.de - ${currentCategory.name}`;
    } else {
      document.title = 'GrowHeads.de';
    }
  }

  render() {
    return null;
  }
}

export default withCategory(withProduct(TitleUpdater));

