// ==UserScript==
// @name         Amazon商品ページ - WordPress連携ボタン
// @namespace    http://tampermonkey.net/
// @version      2.00
// @description  Amazon商品ページにWordPressショートコードコピーとブログ投稿ボタンを追加（設定可能）
// @match        https://www.amazon.co.jp/*
// @match        https://www.amazon.co.jp/dp/*
// @match        https://www.amazon.co.jp/gp/*
// @grant        GM_getValue
// @grant        GM_setValue
// ==/UserScript==

(function() {
    'use strict';

    // ========== デフォルト設定 ==========
    const DEFAULT_SETTINGS = {
        shortcodeTag: 'takehana-22',
        blogUrl: 'https://',
        affiliateId: 'takehana-22'
    };

    // 設定を取得（保存された設定がない場合はデフォルトを使用）
    function getSettings() {
        return {
            shortcodeTag: GM_getValue('shortcodeTag', DEFAULT_SETTINGS.shortcodeTag),
            blogUrl: GM_getValue('blogUrl', DEFAULT_SETTINGS.blogUrl),
            affiliateId: GM_getValue('affiliateId', DEFAULT_SETTINGS.affiliateId)
        };
    }

    // 設定を保存
    function saveSettings(settings) {
        GM_setValue('shortcodeTag', settings.shortcodeTag);
        GM_setValue('blogUrl', settings.blogUrl);
        GM_setValue('affiliateId', settings.affiliateId);
    }

    // 設定画面を表示
    function showSettingsDialog() {
        const settings = getSettings();
        
        const dialog = document.createElement('div');
        dialog.style.cssText = `
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: white;
            padding: 30px;
            border-radius: 12px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.3);
            z-index: 10000;
            min-width: 500px;
        `;

        dialog.innerHTML = `
            <h2 style="margin: 0 0 20px 0; font-size: 20px; color: #333;">Amazon WPボタン 設定</h2>
            
            <div style="margin-bottom: 20px;">
                <label style="display: block; margin-bottom: 5px; font-weight: bold; color: #555;">
                    ショートコード用タグ（ボタン1）
                </label>
                <input type="text" id="shortcodeTag" value="${settings.shortcodeTag}" 
                    style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px; box-sizing: border-box;">
                <small style="color: #666;">例: takehana-22</small>
            </div>
            
            <div style="margin-bottom: 20px;">
                <label style="display: block; margin-bottom: 5px; font-weight: bold; color: #555;">
                    ブログ投稿画面URL（ボタン2）
                </label>
                <input type="text" id="blogUrl" value="${settings.blogUrl}" 
                    style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px; box-sizing: border-box;">
                <small style="color: #666;">例: https://example.com/wp-admin/post-new.php</small>
            </div>
            
            <div style="margin-bottom: 20px;">
                <label style="display: block; margin-bottom: 5px; font-weight: bold; color: #555;">
                    アフィリエイトID（ボタン3）
                </label>
                <input type="text" id="affiliateId" value="${settings.affiliateId}" 
                    style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px; box-sizing: border-box;">
                <small style="color: #666;">例: your-affiliate-id-22</small>
            </div>
            
            <div style="display: flex; gap: 10px; justify-content: flex-end; margin-top: 25px;">
                <button id="cancelBtn" style="
                    padding: 10px 20px;
                    background: #f0f0f0;
                    border: none;
                    border-radius: 6px;
                    cursor: pointer;
                    font-size: 14px;
                    font-weight: 500;
                ">キャンセル</button>
                <button id="saveBtn" style="
                    padding: 10px 20px;
                    background: #FF9900;
                    color: white;
                    border: none;
                    border-radius: 6px;
                    cursor: pointer;
                    font-size: 14px;
                    font-weight: 500;
                ">保存</button>
            </div>
        `;

        const overlay = document.createElement('div');
        overlay.style.cssText = `
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0,0,0,0.5);
            z-index: 9999;
        `;

        document.body.appendChild(overlay);
        document.body.appendChild(dialog);

        // 保存ボタン
        dialog.querySelector('#saveBtn').onclick = () => {
            const newSettings = {
                shortcodeTag: dialog.querySelector('#shortcodeTag').value,
                blogUrl: dialog.querySelector('#blogUrl').value,
                affiliateId: dialog.querySelector('#affiliateId').value
            };
            saveSettings(newSettings);
            overlay.remove();
            dialog.remove();
            alert('設定を保存しました。ページを再読み込みしてください。');
        };

        // キャンセルボタン
        dialog.querySelector('#cancelBtn').onclick = () => {
            overlay.remove();
            dialog.remove();
        };

        // オーバーレイクリックで閉じる
        overlay.onclick = () => {
            overlay.remove();
            dialog.remove();
        };
    }

    // 商品ページかどうかをチェック
    function isProductPage() {
        return document.getElementById('ASIN') || 
               document.querySelector("[data-asin]") || 
               location.href.match(/\/dp\/[A-Z0-9]{10}/);
    }

    // ASINと商品名を取得
    function getProductInfo() {
        const asin = document.getElementById('ASIN')?.value || 
                    document.querySelector("[data-asin]")?.getAttribute("data-asin") || 
                    location.href.match(/\/dp\/([A-Z0-9]{10})/)?.[1];
        
        const title = document.querySelector("#productTitle")?.innerText.trim();
        
        return { asin, title };
    }

    // ショートコードをクリップボードにコピー
    function copyShortcode() {
        const settings = getSettings();
        const { asin, title } = getProductInfo();
        
        if (!asin || !title) {
            alert("ASIN または商品名が見つかりません");
            return;
        }
        
        const shortcode = `[affiliate_link asin="${asin}" kw="${title}"]`;
        
        navigator.clipboard.writeText(shortcode).then(() => {
            alert(`ショートコードをコピーしました：\n${shortcode}`);
        }).catch(err => {
            alert("コピーに失敗しました: " + err);
        });
    }

    // ブログ投稿画面を開く
    function openBlogEditor() {
        const settings = getSettings();
        window.open(settings.blogUrl, '_blank');
    }

    // アフィリエイトリンクを開く
    function openAffiliateLink() {
        const settings = getSettings();
        const asin = document.getElementById('ASIN')?.value || 
                    document.querySelector("[data-asin]")?.getAttribute("data-asin") || 
                    location.href.match(/\/dp\/([A-Z0-9]{10})/)?.[1];
        
        if (!asin) {
            alert("ASINが見つかりません");
            return;
        }
        
        const affiliateUrl = `https://www.amazon.co.jp/dp/${asin}?tag=${settings.affiliateId}`;
        location.href = affiliateUrl; // 同じタブで開く
    }

    // ボタンを作成して追加
    function addButtons() {
        // 既にボタンが追加されていたら何もしない
        if (document.getElementById('wp-helper-buttons')) {
            return;
        }

        // 商品タイトル要素を探す
        const titleElement = document.querySelector('#productTitle');
        
        if (!titleElement) {
            console.log('商品タイトルが見つかりません');
            return;
        }

        // ボタンコンテナを作成
        const buttonContainer = document.createElement('div');
        buttonContainer.id = 'wp-helper-buttons';
        buttonContainer.style.cssText = `
            margin: 0 0 16px 0;
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        `;

        // ショートコードコピーボタン
        const copyButton = document.createElement('button');
        copyButton.textContent = '📋 WPショートコードをコピー';
        copyButton.style.cssText = `
            background-color: #FF9900;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 8px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 500;
            transition: background-color 0.2s;
        `;
        copyButton.onmouseover = () => copyButton.style.backgroundColor = '#E88B00';
        copyButton.onmouseout = () => copyButton.style.backgroundColor = '#FF9900';
        copyButton.onclick = copyShortcode;

        // ブログ投稿ボタン
        const blogButton = document.createElement('button');
        blogButton.textContent = '✏️ ブログ投稿画面を開く';
        blogButton.style.cssText = `
            background-color: #146EB4;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 8px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 500;
            transition: background-color 0.2s;
        `;
        blogButton.onmouseover = () => blogButton.style.backgroundColor = '#0D5A91';
        blogButton.onmouseout = () => blogButton.style.backgroundColor = '#146EB4';
        blogButton.onclick = openBlogEditor;

        // アフィリエイトリンクボタン
        const affiliateButton = document.createElement('button');
        affiliateButton.textContent = '🔗 アフィリエイトリンクを開く';
        affiliateButton.style.cssText = `
            background-color: #008296;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 8px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 500;
            transition: background-color 0.2s;
        `;
        affiliateButton.onmouseover = () => affiliateButton.style.backgroundColor = '#006B7D';
        affiliateButton.onmouseout = () => affiliateButton.style.backgroundColor = '#008296';
        affiliateButton.onclick = openAffiliateLink;

        // 設定ボタン
        const settingsButton = document.createElement('button');
        settingsButton.textContent = '⚙️ 設定';
        settingsButton.style.cssText = `
            background-color: #666;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 8px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 500;
            transition: background-color 0.2s;
        `;
        settingsButton.onmouseover = () => settingsButton.style.backgroundColor = '#555';
        settingsButton.onmouseout = () => settingsButton.style.backgroundColor = '#666';
        settingsButton.onclick = showSettingsDialog;

        // ボタンをコンテナに追加
        buttonContainer.appendChild(copyButton);
        buttonContainer.appendChild(blogButton);
        buttonContainer.appendChild(affiliateButton);
        buttonContainer.appendChild(settingsButton);

        // 商品タイトルの前（上）に挿入
        titleElement.parentNode.insertBefore(buttonContainer, titleElement);
    }

    // ページ読み込み完了後に実行
    if (isProductPage()) {
        // DOMの読み込みを待つ
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', addButtons);
        } else {
            addButtons();
        }

        // 動的に価格が読み込まれる場合に対応
        const observer = new MutationObserver((mutations) => {
            if (!document.getElementById('wp-helper-buttons')) {
                addButtons();
            }
        });

        observer.observe(document.body, {
            childList: true,
            subtree: true
        });
    }
})();