# Project export: terra

This document was generated by HackStack to give an AI agent context about a hackathon project. Sections are labeled with their provenance; content marked as truncated was cut to keep this document small.

## Project metadata

- Hackathon: TreeHacks 2025
- Tagline: Imagine shopping online with full transparency—our Chrome extension scrapes product info, rates sustainability based on brand reports, and uses AI to highlight key materials and eco-friendly features.
- Devpost: https://devpost.com/software/terra-3kl0mg
- GitHub: https://github.com/yuyangp16/terra-chrome-extension.git
- Video: https://www.youtube.com/embed/ZK3_ttgIvMc?enablejsapi=1&hl=en_US&rel=0&start=&version=3&wmode=transparent
- Team: 2 GitHub contributor(s) — Yuyang Pang (8 commits), lisasunhwang (2 commits)

## Devpost submission (written by the team)

### Inspiration

In the past decade, online shopping has become a primary way people make purchases. While it offers convenience, it also has significant environmental consequences—including emissions from transportation, excessive plastic packaging, and a focus on convenience over sustainability. Corporations respond to demand, and consumers collectively have the power to influence industries by choosing to support ethical and sustainable brands. With technology rapidly evolving, it has the potential to be a powerful force for good. Empowered by AI agent, Terra was created to help consumers make informed, eco-friendly purchasing decisions effortlessly, making it easier to turn small choices into meaningful impact.

### What it does

Terra is a Chrome extension that: Obtains key information from major online retailers, identifying sustainability-related attributes without requiring manual input from the user. Assesses a brand's sustainability by analyzing a variety of sources, including: Corporate disclosures: Sustainability reports, Corporate Social Responsibility (CSR) documents, and environmental impact statements. Third-party certifications: Recognized labels like ISO 14001, B Corp, LEED, and Fair Trade that verify environmental responsibility. Independent assessments: News reports, NGO analyses, scientific studies, and regulatoriy actions that highlight industry benchmarks and concerns. Company transparency: Public statements, website sustainability pages, and executive interviews to detect greenwashing or genuine efforts. Corporate disclosures: Sustainability reports, Corporate Social Responsibility (CSR) documents, and environmental impact statements. Third-party certifications: Recognized labels like ISO 14001, B Corp, LEED, and Fair Trade that verify environmental responsibility. Independent assessments: News reports, NGO analyses, scientific studies, and regulatoriy actions that highlight industry benchmarks and concerns. Company transparency: Public statements, website sustainability pages, and executive interviews to detect greenwashing or genuine efforts. Generates clear, concise insights of a product's materials and environmental impact—helping users quickly understand the pros and cons of purchasing the product in question (e.g., polyester is non-recyclable and petroleum-based, while organic cotton has a lower carbon footprint). Provides alternative products that align with more sustainable practices, making it effortless for users to shop smarter. Empowers consumers to take action by drafting complaint reports that they can send to the brand themselves—ensuring brands are held accountable. User engagement is crucial for systemic change, and this feature makes it easy to voice concerns and demand better practices, allowing consumers to feel the impact of their choices.

### How we built it

We combined web scraping, AI-driven text generation, and sustainability data analysis to bring terra to life. Our development process involved: Extracting product information dynamically from various popular shopping sites. Implementing a scoring algorithm based on brand reports. Utilizing AI to summarizing key sustainability features for easy consumer understanding. Designing a user-friendly Chrome extension that integrates seamlessly into online shopping.

### Challenges we ran into

Building terra posed several challenges, including: Inconsistent data availability: One of the biggest challenges we faced was the lack of transparency in environmental reporting. Brands that perform well in sustainability proudly highlight their achievements, while those with unethical practices often hide or greenwash their reports to appear more responsible than they actually are. This leaves consumers vulnerable to misleading claims, making it difficult for them to distinguish between genuinely sustainable products and those that only appear eco-friendly on the surface. Our challenge was to filter through this noise and provide shoppers with an unbiased sustainability score that prioritizes verified, third-party information over corporate self-reporting. Adapting to different websites: We started by integrating terra with major retailers like Walmart, Best Buy, Amazon, and Target, as these platforms serve as hubs for multiple brands. However, expanding beyond these large companies presents a challenge: smaller brands and niche retailers have less standardized product listings and may not provide clear sustainability information. As we scale, our goal is to improve our web scraping and data analysis capabilities to support a wider range of online stores, helping consumers navigate sustainability efforts even when brands are aggressively marketed through large retailers. Balancing detail with simplicity: Sustainability is a complex issue, and we faced UI/UX challenges in ensuring that terra remains accessible to all consumers. While some users want in-depth reports on sustainability metrics, others just want a quick, digestible summary. To solve this divergence, we included a "Learn More" option, allowing users to delve deeper if they choose, without overwhelming those who prefer a more streamlined experience. Finding the right balance in these small details remains an ongoing challenge.

### Accomplishments we're proud of

Successfully integrating real-time product analysis into the online shopping experience. Creating an AI-driven sustainability report generator that simplifies complex data. Developing a tool that empowers consumers to not only make greener shopping decisions, but to also take action and demand accountability from their favorite brands.

### What we learned

Consumers want to make sustainable choices but need accessible, easy-to-understand information. AI and automation can enhance sustainability efforts. Transparency is key—many companies still lack clear sustainability reporting, highlighting the need for consumer advocacy tools like terra. Consumer spending has the power to drive corporate change. If more people choose sustainable brands, businesses are obligated to respond.

### What's next

for Terra Expanding support for more online retailers to maximize the tool's accessibility. Implementing a reward system for loyal users to increase engagement. Introducing personalized sustainability recommendations based on user preferences. Collaborating with eco-conscious brands to promote better business practices. With terra, we're making sustainable shopping effortless—join us to shop greener.

## README (from the GitHub repository)

# terra-chrome-extension

# In "chrome://extensions/", turn on developer mode on Chrome.
# Click "Load unpacked" and select the unzipped folder.
# The chrome extension works on walmart.com, amazon.com, bestbuy.com, and target.com
# If the chrome extension shows error messages, retry the analyze product button.

## Detected evidence (automated analysis)

Indexed codebase: 10 recognized source files, 39 KB.
- HTML (language) — detected in the code
- JavaScript (language) — detected in the code
- CSS (language) — claimed on Devpost, not found in the code
- OpenAI (technology) — claimed on Devpost, not found in the code

## Codebase structure (from repository index)

### Files (12 of 12)

```
.DS_Store
background.js
complaint.html
complaint.js
content_script.js
learn_more.html
learn_more.js
manifest.json
popup.html
popup.js
README.md
terra.html
```

### Dependencies

No dependency index available.

### Recent commits (newest first)

- Update manifest.json
- Update background.js
- change readme
- change name
- Working Prototype
- remove file
- add margin-top to complaint
- edited ui on learn more page
- first working prototype
- Initial commit

## Key source files (fetched from GitHub, selected and truncated for size)

### complaint.js

```javascript
document.addEventListener("DOMContentLoaded", function() {
    chrome.storage.local.get("complaintData", function(data) {
        console.log("Retrieved complaintData:", data);
        if (data.complaintData) {
            document.getElementById("brandEmail").innerText = data.complaintData.brand_email;
            document.getElementById("complaintEmail").innerText = data.complaintData.complaint_email;
        } else {
            document.getElementById("brandEmail").innerText = "No data available. Please prepare the complaint report.";
            document.getElementById("complaintEmail").innerText = "No data available.";
        }
    });
});

// document.getElementById("sendBtn").addEventListener("click", function() {
//     alert("Complaint email sent!");
//     window.close();
// });

// document.getElementById("deleteBtn").addEventListener("click", function() {
//     alert("Complaint email deleted.");
//     window.close();
// });

```

### learn_more.js

```javascript
document.addEventListener("DOMContentLoaded", function() {
    chrome.storage.local.get("analysisData", function(data) {
      if (!data.analysisData) {
        document.getElementById("headerTitle").innerText = "No analysis data available. Please run analysis first.";
        return;
      }
      const analysis = data.analysisData;
      
      // Update header with product name if available
      if (analysis.productName) {
        document.getElementById("headerTitle").innerText = "More Information for " + analysis.productName;
      }
      
      // Build three sections for Materials, Carbon Footprint, and Brand Accountability using the paragraphs from AI
      const sectionsDiv = document.getElementById("sectionsContainer");
      let html = "";
      html += `<div class="section" style="font-size:15px; line-height:20px; margin-top:-20px;">
        <h2>Materials</h2>
        <p>${analysis.materials || "No information available."}</p>
      </div>`;
      html += `<div class="section" style="font-size:15px; line-height:20px; margin-top:-20px;">
        <h2>Carbon Footprint</h2>
        <p>${analysis.carbon_footprint || "No information available."}</p>
      </div>`;
      html += `<div class="section" style="font-size:15px; line-height:20px; margin-top:-20px;">
        <h2>Brand Accountability</h2>
        <p>${analysis.brand_accountability || "No information available."}</p>
      </div>`;
      sectionsDiv.innerHTML = html;
      
      // Populate sources list
      const sourcesList = document.getElementById("sourcesList");
      sourcesList.innerHTML = "";
      if (analysis.sources && analysis.sources.length > 0) {
        analysis.sources.forEach(src => {
          const li = document.createElement("li");
          li.innerHTML = `${src.description} Retrieved from <a href="${src.website}" target="_blank">${src.website}</a>`;
          sourcesList.appendChild(li);
        });
      } else {
        sourcesList.innerHTML = "<li>No sources available.</li>";
      }
      
    });
  });
  
```

### learn_more.html

```html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>More Information</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      max-width: 800px;
      margin: 20px auto;
      padding: 20px;
      background-color: #f5f5f5;
    }
    .container {
      background-color: white;
      padding: 30px;
      border-radius: 10px;
      box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    }
    .header {
      display: flex;
      align-items: center;
      margin-bottom: 30px;
    }
    .logo {
      width: 240px;
      height: 80px;
      margin-right: 20px;
    }
    h1 {
      color: #333;
      font-size: 24px;
      margin: 0;
    }
    .section {
      margin-bottom: 20px;
      padding: 10px;
      border-bottom: 1px solid #ccc;
    }
    .section h2 {
      font-size: 20px;
      color: #444;
      margin-bottom: 5px;
    }
    .section img {
      width: 50px;
      vertical-align: middle;
      margin-right: 10px;
    }
    .sources {
      margin-top: 20px;
    }
    .sources ul {
      padding-left: 20px;
    }
    .sources li {
      margin-bottom: 10px;
    }
    .sources a {
      color: #1a73e8;
      text-decoration: none;
    }
    .permutable-link {
      margin-top: 20px;
      text-align: center;
    }
    .permutable-link a {
      color: #1a73e8;
      font-size: 16px;
      text-decoration: none;
      font-weight: bold;
    }
  </style>
</head>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>More Information</title>
    <style>
      /* (Your CSS styling as before) */
    </style>
  </head>
  <body>
    <div class="container">
      <div class="header">
        <img src="images/terra_logo.jpeg" alt="Terra Logo" class="logo">
        <h1 id="headerTitle">More Information</h1>
      </div>
      
      <!-- Container for three sections -->
      <div id="sectionsContainer">
        Loading...
      </div>
      
      <div class="sources">
        <p>Resources:</p>
        <ul id="sourcesList">
          <!-- Sources will be populated dynamically -->
        </ul>
      </div>
    </div>
    <script src="learn_more.js"></script>
  </body>
</html>

```

### complaint.html

```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Customer Sustainability Complaint Report</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 20px auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        
        .container {
            background-color: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }

        .header-container {
            margin-bottom: 30px;
            display: flex;
            flex-direction: column;
            align-items: center;
        }
        
        .logo-container {
            align-self: flex-start;
        }

        h1 {
            color: #333;
            font-size: 24px;
            margin: 15px 0;
            text-align: center;
        }

        .back-link-container {
            align-self: flex-start;
            width: 100%;
        }

        .back-link {
            color: #666;
            text-decoration: none;
            font-size: 14px;
            cursor: pointer;
        }

        .back-link:hover {
            color: #333;
        }

        .logo {
            width: 240px;
            height: 80px;
            margin-right: 20px;
        }

        h1 {
            color: #333;
            font-size: 24px;
            margin: 0;
        }

        .content {
            line-height: 1.6;
        }

        ul {
            padding-left: 20px;
        }

        li {
            margin-bottom: 10px;
            color: #444;
        }

        .button-container {
            display: flex;
            justify-content: center;
            margin-top: 20px;
        }

        .send-button {
            background-color: #bae2b9;
            color: #333;
            border: none;
            padding: 12px 120px;
            min-width: 300px;
            border-radius: 25px;
            font-size: 16px;
            cursor: pointer;
            transition: background-color 0.3s;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }

        .send-button:hover {
            background-color: #7BC9A3;
        }

        .complaint-section {
            font-size: 15px;
        }

    </style>
</head>
<body>
    <div class="container">
        <div class="header-container">
            <div class="logo-container" style="margin-bottom: 20px;">
                <img src="https://i.imgur.com/0aryVUI.png" alt="Terra Logo" class="logo">
            </div>
            <h1>Customer Sustainability Complaint Report</h1>
            <div class="back-link-container">
                <a href = 'terra.html' class="back-link">&lt; Back</a>
            </div>
        </div>
        
        <div class="content">
            
            <div class="complaint-section">
                <strong>Brand Email:</strong>
                <p id="brandEmail">Loading...</p>
            </div>
            <div class="complaint-section">
                <strong>Draft Complaint Email:</strong>
                <p id="complaintEmail">Loading...</p>
            </div>
            
            <div class="button-container">
                <button class="send-button">Send</button>
            </div>
        </div>
    </div>
    <script src="complaint.js" defer></script>
</body>
</html>
```

### content_script.js

```javascript
// // Listen for messages from the background script or popup
// chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
//     if(request.action === "get_product_specs") {
//         // Attempt to scrape key product details from a Walmart product page.
//         // (This is a basic example; adjust selectors as needed based on page structure.)
//         let titleElem = document.querySelector('h1');
//         let title = titleElem ? titleElem.innerText.trim() : '';
        
//         // Try to find manufacturer details via known selectors.
//         let manufacturer = '';
//         let manufacturerElem = document.querySelector('[itemprop="name"]');
//         if(manufacturerElem) {
//             manufacturer = manufacturerElem.innerText.trim();
//         }
        
//         // You can add more specifications as needed.
//         sendResponse({ title: title, manufacturer: manufacturer });
//     }
// });

// chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
//     if (request.action === "get_product_specs") {
//         // Attempt to find the product name in the Walmart page DOM
//         // Adjust the selector as needed based on the actual structure
//         let productNameElem = document.querySelector('[data-automation="product-title"] h1 span');
//         let productName = productNameElem ? productNameElem.textContent.trim() : '';
        
//         if (productName) {
//             sendResponse({ productName });
//         } else {
//             sendResponse({ error: "No product name found." });
//         }
//     }
// });

// chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
//     if (request.action === "get_product_specs") {
//         // Find the product name using the identified selector
//         let productNameElem = document.querySelector('h1#main-title');
//         let productName = productNameElem ? productNameElem.textContent.trim() : '';

//         if (productName) {
//             sendResponse({ productName });
//         } else {
//             sendResponse({ error: "No product name found." });
//         }
//     }
// });

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if (request.action === "get_product_specs") {
        let productName = '';
        let url = window.location.hostname;

        if (url.includes("walmart.com")) {
            // Walmart Selector
            let productNameElem = document.querySelector('h1#main-title');
            productName = productNameElem ? productNameElem.textContent.trim() : '';

        } else if (url.includes("amazon.com")) {
            // Amazon Selector
            let productNameElem = document.querySelector('#productTitle');
            productName = productNameElem ? productNameElem.textContent.trim() : '';

        } else if (url.includes("target.com")) {
            // Target Selector
            let productNameElem = document.querySelector('h1#pdp-product-title-id');
            productName = productNameElem ? productNameElem.textContent.trim() : '';

        } else if (url.includes("bestbuy.com")) {
            // Best Buy Selector
            let productNameElem = document.querySelector('.sku-title h1');
            productName = productNameElem ? productNameElem.textContent.trim() : '';

        } else {
            sendResponse({ error: "Retailer not supported." });
            return;
        }

        if (productName) {
            sendResponse({ productName });
        } else {
            sendResponse({ error: "No product name found." });
        }
    }
});

```

### terra.html

```html
<!DOCTYPE html>
<html>
<head>
    <style>
        body {
            width: 350px;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Arial, sans-serif;
            margin: 0;
            padding: 20px;
            color: #333;
        }
        
        .header {
            display: flex;
            flex-direction: column;
            align-items: center;
            margin-bottom: 30px;
        }
        
        .logo {
            display: flex;
            align-items: center;
            gap: 5px;
            margin-bottom: 3px;
            align-self: flex-start;
        }
        
        
        .logo img {
            width: 240px;
            height: 80px;
        }
        
        .leaf-container {
            display: flex;
            justify-content: center;
            gap: 10px;
            margin-bottom: 20px;
        }
        
        .leaf-container img {
            width: 40px;
            height: 40px;
            object-fit: contain;
        }
        
        .rating-list {
            list-style: none;
            padding: 0;
            margin: 0 0 30px 0;
        }
        
        .rating-item {
            display: flex;
            align-items: center;
            margin-bottom: 15px;
            font-size: 16px;
            color: #555;
        }
        
        .icon {
            width: 20px;
            height: 20px;
            margin-right: 15px;
            display: inline-flex;
            align-items: center;
            justify-content: center;
        }
        
        .icon-x {
            color: #ff4444;
            font-weight: bold;
        }
        
        .icon-check {
            color: #4CAF50;
            font-weight: bold;
        }
        
        .divider {
            height: 1px;
            background-color: #e0e0e0;
            margin: 20px 0;
        }
        
        .stats-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
            margin-bottom: 30px;
        }
        
        .stat-item {
            color: #666;
        }
        
        .stat-value {
            font-size: 20px;
            font-weight: 500;
            color: #333;
            margin-top: 5px;
        }
        
        .explore-button {
            background-color: #bae2b9;
            color: #333;
            padding: 15px;
            border: 2px solid #333;
            border-radius: 8px;
            width: 100%;
            font-size: 16px;
            font-weight: 500;
            cursor: pointer;
            margin-bottom: 15px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }
        
        .learn-more {
            text-align: center;
            color: #666;
            text-decoration: none;
            display: block;
            margin-top: 10px;
        }
    </style>
</head>
<body>
    <div class="header">
        <div class="logo">
            <img src="https://i.imgur.com/0aryVUI.png" alt="Terra logo">
        </div>

    </div>
    
    <ul class="rating-list">
        <li class="rating-item">
            <span class="icon icon-x">✕</span>
            3M Severe Risk ESG Rating
        </li>
        <li class="rating-item">
            <span class="icon icon-x">✕</span>
            Class action lawsuit - oil spill
        </li>
        <li class="rating-item">
            <span class="icon icon-x">✕</span>
            PFAS chemicals
        </li>
        <li class="rating-item">
            <span class="icon icon-x">✕</span>
            Plastic packaging
        </li>
        <li class="rating-item">
            <span class="icon icon-check">✓</span>
            100% Recycled content
        </li>
    </ul>
    <h3 style="text-align: center; margin: 12px 0;"> Certified planet protector! </h3>
    <div class="leaf-container">
      <img src="https://i.imgur.com/T5WahaY.png" alt="Leaf">
      <img src="https://i.imgur.com/T5WahaY.png" alt="Leaf">
      <img src="https://i.imgur.com/T5WahaY.png" alt="Leaf">
      <img src="https://i.imgur.com/T5WahaY.png" alt="Leaf">
      <img src="https://i.imgur.com/T5WahaY.png" alt="Leaf">
  </div>
    <div class="divider"></div>
    <h2 style="text-align: center; margin: 15px 0;"> 3 Green Options Found!</h2>
    <button class="explore-button">Explore Green Options</button>
    <a href="#" class="learn-more">Learn More</a>
</body>
</html>
```

### popup.html

```html
<!DOCTYPE html>
<html>
<head>
    <style>
        body {
            width: 350px;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Arial, sans-serif;
            margin: 0;
            padding: 20px;
            color: #333;
        }
        .header {
            display: flex;
            flex-direction: column;
            align-items: center;
            margin-bottom: 30px;
        }
        .logo {
            display: flex;
            align-items: center;
            gap: 5px;
            margin-bottom: 3px;
            align-self: flex-start;
        }
        .logo img {
            width: 240px;
            height: 80px;
        }
        .leaf-container {
            display: flex;
            justify-content: center;
            gap: 10px;
            margin-top: 12px;
        }
        .leaf-container img {
            width: 40px;
            height: 40px;
            object-fit: contain;
        }
        .rating-list {
            list-style: none;
            padding: 0;
            margin: 0 0 30px 0;
        }
        .rating-item {
            display: flex;
            align-items: center;
            margin-bottom: 15px;
            font-size: 16px;
            color: #555;
        }
        .icon {
            width: 20px;
            height: 20px;
            margin-right: 15px;
            display: inline-flex;
            align-items: center;
            justify-content: center;
        }
        .icon-x {
            color: #ff4444;
            font-weight: bold;
        }
        .icon-check {
            color: #4CAF50;
            font-weight: bold;
        }
        .divider {
            height: 1px;
            background-color: #e0e0e0;
            margin: 20px 0;
        }
        .analyze-button {
            background-color: #bae2b9;
            color: #333;
            padding: 15px;
            border: 2px solid #333;
            border-radius: 8px;
            width: 100%;
            font-size: 16px;
            font-weight: 500;
            cursor: pointer;
            margin-bottom: 15px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }
        .post-analysis-button {
            background-color: #4CAF50;
            color: white;
            padding: 10px;
            border: none;
            border-radius: 5px;
            font-size: 14px;
            cursor: pointer;
            flex: 1;
        }
        /* Different color for complaint report button */
        #sendComplaintButton {
            background-color: #ff4444;
        }
        .button-container {
            display: flex;
            gap: 10px;
        }
        #ratingMessage {
            text-align: center;
            margin: 12px 0;
        }
        #result {
            margin-top: 20px;
            font-size: 14px;
            color: #444;
        }
        /* Style for alternative green options hyperlinks */
        .green-option a {
            color: #4CAF50;
            text-decoration: underline;
        }
        /* Hidden container for extended references/details */
        #learnMoreContainer {
            display: none;
            margin-top: 10px;
            font-size: 14px;
            color: #333;
        }
        #learnMoreContainer h4 {
            margin-bottom: 5px;
        }
        #learnMoreContainer p {
            margin: 0 0 10px 0;
        }
    </style>
</head>
<body>
    <div class="header">
        <div class="logo">
            <img src="https://i.imgur.com/0aryVUI.png" alt="Terra logo">
        </div>
    </div>
    
    <!-- Sustainability highlights list (with bullet points and icons) -->
    <ul class="rating-list" id="sustainabilityHighlights">
        <!-- Dynamically inserted sustainability highlights go here -->
    </ul>
    
    <!-- Leaf container for ESG rating images -->
    <div class="leaf-container" id="leafContainer">
        <!-- Dynamically inserted leaf images go here -->
    </div>

    <!-- Rating message based on ESG score -->
    <h3 id="ratingMessage"></h3>
    
    <!-- Initially, display only the Analyze Product button -->
    <button class="analyze-button" id="analyzeButton">Analyze Product</button>
    
    <!-- Post-analysis actions container (hidden until analysis completes) -->
    <div id="postAnalysisActions" style="display: none;">
        <div class="divider"></div>
        <div class="button-container" style="margin-top: 10px;">
            <button class="post-analysis-button" id="learnMoreButton">Learn More</button>
            <button class="post-analysis-button" id="sendComplaintButton">Send Complaint Report</button>
        </div>
    </div>
    
    <!-- Hidden container for more detailed references -->
    <div id="learnMoreContainer"></div>
    
    <div id="result"></div>
    
    <script src="popup.js"></script>
</body>
</html>

```

### popup.js

```javascript
let currentAnalysisResponse = null;  // Used only for immediate UI update

// Utility function to create a leaf image element
function createLeafImage(src) {
    let img = document.createElement('img');
    img.src = chrome.runtime.getURL(src);
    img.alt = 'Leaf';
    return img;
}

document.getElementById('analyzeButton').addEventListener('click', function() {
    document.getElementById('result').innerText = 'Analyzing product...';
    chrome.runtime.sendMessage({ action: "analyze_product" }, function(response) {
        if (response && response.error) {
            document.getElementById('result').innerText = 'Error: ' + response.error;
            currentAnalysisResponse = null;
        } else if (response) {
            currentAnalysisResponse = response;
            
            // Update the sustainability highlights list
            let highlightsList = document.getElementById('sustainabilityHighlights');
            highlightsList.innerHTML = '';
            if (response.sustainability_highlights && response.sustainability_highlights.length > 0) {
                response.sustainability_highlights.forEach(item => {
                    let isPositive = false;
                    let text = item;
                    if(text.startsWith("True")) {
                        isPositive = true;
                        text = text.replace(/^True[:\s-]*/, '');
                    } else if(text.startsWith("False")) {
                        isPositive = false;
                        text = text.replace(/^False[:\s-]*/, '');
                    }
                    let li = document.createElement('li');
                    li.className = 'rating-item';
                    let span = document.createElement('span');
                    span.className = isPositive ? 'icon icon-check' : 'icon icon-x';
                    span.innerText = isPositive ? '\u2713' : '\u2715';
                    li.appendChild(span);
                    li.appendChild(document.createTextNode(text));
                    highlightsList.appendChild(li);
                });
            }
            
            // Append alternative green options if provided
            if (response.green_options && response.green_options.length > 0) {
                let header = document.createElement('h3');
                header.style.textAlign = 'center';
                header.style.margin = '12px 0';
                header.innerText = 'Alternative Green Options:';
                highlightsList.parentNode.insertBefore(header, highlightsList.nextSibling);
                
                let greenList = document.createElement('ul');
                greenList.className = 'rating-list';
                response.green_options.forEach(item => {
                    let li = document.createElement('li');
                    li.className = 'rating-item green-option';
                    // If item is an object with name and link, create a hyperlink
                    if (typeof item === 'object' && item.name && item.link) {
                        let a = document.createElement('a');
                        a.href = item.link;
                        a.target = "_blank";
                        a.innerText = item.name;
                        li.appendChild(a);
                    } else {
                        // Fallback if not in expected format
                        li.appendChild(document.createTextNode(item));
                    }
                    greenList.appendChild(li);
                });
                header.parentNode.insertBefore(greenList, header.nextSibling);
            }
            
            // Update the leaf container based on esg_score
            let leafContainer = document.getElementById('leafContainer');
            leafContainer.innerHTML = '';
            let esgScore = response.esg_score;
            if (typeof esgScore === 'number') {
                if (esgScore === 1) {
                    // 1 red leaf, 4 grey leaves
                    leafContainer.appendChild(createLeafImage("images/red_leaf.png"));
                    for (let i = 0; i < 4; i++) {
                        leafContainer.appendChild(createLeafImage("images/grey_leaf.png"));
                    }
                } else if (esgScore >= 2 && esgScore <= 4) {
                    for (let i = 0; i < esgScore; i++) {
                        leafContainer.appendChild(createLeafImage("images/yellow_leaf.png"));
                    }
                    for (let i = 0; i < 5 - esgScore; i++) {
                        leafContainer.appendChild(createLeafImage("images/grey_leaf.png"));
                    }
                } else if (esgScore === 5) {
                    for (let i = 0; i < 5; i++) {
                        leafContainer.appendChild(createLeafImage("images/green_leaf.png"));
                    }
                }
            }
            
            // Update rating message based on esg_score
            let ratingMessageEl = document.getElementById('ratingMessage');
            if (typeof esgScore === 'number') {
                let message = "";
                switch(esgScore) {
                    case 1:
                        message = "Unsustainable! Do better.";
                        break;
                    case 2:
                        message = "Leaf-ing me unimpressed...";
                        break;
                    case 3:
                        message = "Decent! But there's room to grow.";
                        break;
                    case 4:
                        message = "Eco-friendly! Almost tree-mendous, just a twig away!";
                        break;
                    case 5:
                        message = "Planet Protector! Green hero status.";
                        break;
                }
                ratingMessageEl.innerText = message;
            }
            
            // Hide the Analyze Product button and show the post-analysis actions
      
[truncated — 1114 more characters]
```

### background.js

```javascript
// Replace with your actual OpenAI API key
const OPENAI_API_KEY = '<your API key>';

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
  if (request.action === "analyze_product") {
    chrome.tabs.query({ active: true, currentWindow: true }, function(tabs) {
      if (tabs[0]) {
        chrome.tabs.sendMessage(tabs[0].id, { action: "get_product_specs" }, function(productSpecs) {
          if (chrome.runtime.lastError || !productSpecs || productSpecs.error) {
            sendResponse({ error: productSpecs?.error || "Failed to retrieve product specs." });
            return;
          }
          
          const prompt = `
You are an AI assistant. Given the following product name:
"${productSpecs.productName}"

1. Search the manufacturer of the product.
2. Rate the product on a scale of 1 to 5 leaves based on its sustainability. Search relevant information online to support your rating.
Key Aspects to Consider:
Carbon Footprint and Climate Impact
Does the company measure and report its greenhouse gas (GHG) emissions?
Are there targets and timelines for reducing emissions?
Does the company invest in carbon offsetting or renewable energy?
Resource Management and Waste Reduction
How does the company manage its material inputs and waste outputs?
Does it use circular economy practices (e.g., recycling, reuse, or composting)?
Does it have clear initiatives to reduce packaging and single-use materials?
Energy and Water Usage
Percentage of energy from renewable sources vs. non-renewable sources.
Water conservation strategies: does the company disclose water usage and work to reduce it?
Supply Chain Practices
Are suppliers held to environmental standards (e.g., code of conduct, audits)?
Does the company vet suppliers for sustainability or require certifications?
Product Lifecycle and Innovation
Are products designed to be more eco-friendly (e.g., biodegradable materials, longer lifespan)?
Do they invest in R&D for sustainable product or process innovation?
Transparency and Reporting
Does the company openly share progress, setbacks, and initiatives?
Is the data consistent and verified by third parties?
Social Impact (Optional but Relevant)
Consider whether the company’s sustainability efforts also include fair labor practices and community engagement, as social and environmental considerations often go hand in hand.

Scoring and Reasoning:
Assign a score between 1 and 5:
1: Severe underperformance. Little to no transparency, significant negative environmental impact, possible infractions of regulations.
2-3: Moderate performance. Shows some efforts but lacks consistency or transparent reporting.
4: Good performance. Demonstrates clear environmental strategies, targets, and ongoing improvements.
5: Exemplary performance. Strong leadership in sustainability, transparent reporting, and consistent third-party validation.

3. Search online (using at most 3 reputable websites) and provide fewer than five sustainability highlights/problems (less than 5 words each), focusing on aspects like recycled materials, plastic packaging, lawsuits, and chemicals. Before each bullet point, add a string False if it is a negative point and a string True if it is a positive point.
4. If the ESG Environmental Score is below 3, search and find at most three alternative green options. Each alternative should be an object with keys "name" (the product's name) and "website link" (the URL to the google search result of the product), so that they can be displayed as clickable hyperlinks.
5. Provide three separate paragraphs (each one approximately 200–250 words) that explain:
   a. **Materials:** The sustainable sourcing and recycled content of the product's materials.
   b. **Carbon Footprint:** The product’s carbon emissions from manufacturing and shipping.
   c. **Brand Accountability:** The brand’s transparency, environmental record, and any controversies.
6. Also provide up to 3 relevant websites you used, along with a short paragraph (under 75 words) for each.
Return your final response in valid JSON format with the following keys:
   - "esg_score" (number, 1-5),
   - "sustainability_highlights" (array of strings),
   - "green_options" (array of objects, each with "name" and "link"),
   - "materials" (string, paragraph on Materials),
   - "carbon_footprint" (string, paragraph on Carbon Footprint),
   - "brand_accountability" (string, paragraph on Brand Accountability),
   - "sources" (array of objects, each with "website" (a URL) and "description")
          `;
          
          fetch("https://api.openai.com/v1/chat/completions", {
            method: "POST",
            headers: {
              "Content-Type": "application/json",
              "Authorization": "Bearer " + OPENAI_API_KEY
            },
            body: JSON.stringify({
              model: "gpt-4o",
              messages: [{ role: "user", content: prompt }],
              max_tokens: 800,
              temperature: 0.5
            })
          })
          .then(response => response.json())
          .then(data => {
            console.log("OpenAI API Response:", data); // Debugging log

            if (data.error || !data.choices || !data.choices[0]?.message?.content) {
              sendResponse({ error: data.error?.message || "Unexpected API response format." });
              return;
            }

            const aiResponse = data.choices[0].message.content.trim();
            console.log("Raw AI Response:", aiResponse);

            // Extract JSON inside ```json ... ```
            const jsonMatch = aiResponse.match(/```json([\s\S]*?)```/);
            if (!jsonMatch) {
              sendResponse({ error: "Response does not contain valid JSON." });
              return;
            }

            try {
              const result = JSON.parse(jsonMatch[1].trim());
              const esgScore = result.esg_score;
              
              chrome.storage.local.set({ analysisData: {
                productName: p
[truncated — 4433 more characters]
```