RamiEjailat / CamelCamelCamel Price History and Sales Rank

// ==UserScript==
// @name         CamelCamelCamel Price History and Sales Rank
// @description  Embeds CamelCamelCamel charts in Amazon product pages
// @author       Rami S Ejailat
// @copyright    RamiEjailat (https://openuserjs.org/users/RamiEjailat)
// @license      MIT
// @version      20250131
// @namespace    http://tampermonkey.net/
// @include      *://*.amazon.tld/dp/*
// @include      *://*.amazon.tld/*/dp/*
// @include      *://*.amazon.tld/gp/product/*
// @include      *://*.amazon.tld/*/ASIN/*
// @exclude      *://aws.amazon.tld/*
// @grant        none
// @icon         https://www.amazon.com/favicon.ico
// @run-at       document-idle
// ==/UserScript==
/* jshint esversion: 6 */

(function () {
    'use strict';

    // Map Amazon domains to CamelCamelCamel country codes
    const countryMap = {
        'com': 'us',
        'ca': 'ca',
        'cn': 'cn',
        'de': 'de',
        'es': 'es',
        'fr': 'fr',
        'it': 'it',
        'co.jp': 'jp',
        'co.uk': 'uk',
        'com.au': 'au'
    };

    // Extract the country code from the domain
    const domain = document.domain.toLowerCase();
    const country = countryMap[domain.split('.').pop()] || 'us';

    // Get the ASIN from the page
    const asinElement = document.querySelector(`[id="asin" i]`);
    if (!asinElement) {
        console.error('CamelCamelCamel:', 'Target element (#ASIN) not found on the page.');
        return;
    }
    const asin = asinElement.value.trim();

    // Define chart parameters
    const duration = '3m'; // Options: "all", "1y", "6m", "1m"
    const width = document.body.clientWidth;
    const height = 400;

    // Construct the CamelCamelCamel chart URL
    const chartUrl = `https://charts.camelcamelcamel.com/${country}/${asin}/amazon-new-used.png?force=1&zero=0&w=${width}&h=${height}&desired=false&legend=1&ilt=1&tp=${duration}&fo=0&lang=en`;
    const chartLink = `https://${country}.camelcamelcamel.com/product/${asin}`;

    // Create the chart container
    const chartContainer = document.createElement('div');
    chartContainer.id = 'camelcamelcamel';
    chartContainer.style.margin = '10px';
    chartContainer.style.clear = 'both';

    // Create the chart image and link
    const chartImage = document.createElement('img');
    chartImage.src = chartUrl;
    const chartLinkElement = document.createElement('a');
    chartLinkElement.href = chartLink;
    chartLinkElement.target = '_blank';
    chartLinkElement.append(chartImage);

    // Append the chart to the container
    chartContainer.append(chartLinkElement);

    // Insert the chart into the DOM
    const targetElement = document.querySelector(`[id="ppd" i]`);
    if (targetElement) {
        targetElement.after(chartContainer);
    } else {
        console.error('CamelCamelCamel:', 'Target element (#ppd) not found on the page.');
    }
})();