// ==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',
        excludeWords: '【電子特典付】'
    };

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

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

    // 設定をJSONファイルとしてエクスポート
    function exportSettings() {
        const settings = getSettings();
        const json = JSON.stringify(settings, null, 2);
        const blob = new Blob([json], { type: 'application/json' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        const timestamp = new Date().toISOString().slice(0, 10);
        a.href = url;
        a.download = `amazon-wp-helper-settings_${timestamp}.json`;
        a.click();
        URL.revokeObjectURL(url);
    }

    // JSONファイルから設定を読み込み（不足項目はデフォルトで補完）
    function importSettingsFromFile(file, onLoaded) {
        const reader = new FileReader();
        reader.onload = () => {
            try {
                const imported = JSON.parse(reader.result);
                const merged = {
                    shortcodeTag: typeof imported.shortcodeTag === 'string' ? imported.shortcodeTag : DEFAULT_SETTINGS.shortcodeTag,
                    blogUrl: typeof imported.blogUrl === 'string' ? imported.blogUrl : DEFAULT_SETTINGS.blogUrl,
                    affiliateId: typeof imported.affiliateId === 'string' ? imported.affiliateId : DEFAULT_SETTINGS.affiliateId,
                    excludeWords: typeof imported.excludeWords === 'string' ? imported.excludeWords : DEFAULT_SETTINGS.excludeWords
                };
                onLoaded(merged);
            } catch (err) {
                alert('インポートに失敗しました。JSONファイルの形式を確認してください。\n' + err);
            }
        };
        reader.readAsText(file);
    }

    // 除外ワードリスト文字列（改行区切り）を配列に変換
    function parseExcludeWords(excludeWordsText) {
        return excludeWordsText
            .split('\n')
            .map(word => word.trim())
            .filter(word => word.length > 0);
    }

    // タイトルから除外ワードを取り除く
    function stripExcludeWords(title, excludeWordsText) {
        const words = parseExcludeWords(excludeWordsText);
        let result = title;
        words.forEach(word => {
            result = result.split(word).join('');
        });
        return result.replace(/\s+/g, ' ').trim();
    }

    // 設定画面を表示
    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="display: flex; gap: 10px; margin-bottom: 20px;">
                <button id="exportBtn" style="
                    padding: 8px 16px;
                    background: #f0f0f0;
                    border: 1px solid #ddd;
                    border-radius: 6px;
                    cursor: pointer;
                    font-size: 13px;
                    font-weight: 500;
                ">📤 エクスポート</button>
                <button id="importBtn" style="
                    padding: 8px 16px;
                    background: #f0f0f0;
                    border: 1px solid #ddd;
                    border-radius: 6px;
                    cursor: pointer;
                    font-size: 13px;
                    font-weight: 500;
                ">📥 インポート</button>
                <input type="file" id="importFileInput" accept="application/json,.json" style="display: none;">
            </div>

            <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="margin-bottom: 20px;">
                <label style="display: block; margin-bottom: 5px; font-weight: bold; color: #555;">
                    ショートコード除外ワード（1行に1つ）
                </label>
                <textarea id="excludeWords" rows="4"
                    style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px; box-sizing: border-box; font-family: inherit; resize: vertical;">${settings.excludeWords}</textarea>
                <small style="color: #666;">例: 【電子特典付】（ショートコードの商品名から自動的に除去されます）</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,
                excludeWords: dialog.querySelector('#excludeWords').value
            };
            saveSettings(newSettings);
            overlay.remove();
            dialog.remove();
            alert('設定を保存しました。ページを再読み込みしてください。');
        };

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

        // エクスポートボタン
        dialog.querySelector('#exportBtn').onclick = () => {
            exportSettings();
        };

        // インポートボタン（ファイル選択を開く）
        dialog.querySelector('#importBtn').onclick = () => {
            dialog.querySelector('#importFileInput').click();
        };

        // ファイル選択後、フォームに反映（保存ボタンを押すまで確定しない）
        dialog.querySelector('#importFileInput').onchange = (e) => {
            const file = e.target.files[0];
            if (!file) return;
            importSettingsFromFile(file, (merged) => {
                dialog.querySelector('#shortcodeTag').value = merged.shortcodeTag;
                dialog.querySelector('#blogUrl').value = merged.blogUrl;
                dialog.querySelector('#affiliateId').value = merged.affiliateId;
                dialog.querySelector('#excludeWords').value = merged.excludeWords;
                alert('設定を読み込みました。内容を確認して「保存」ボタンを押してください。');
            });
        };

        // オーバーレイクリックで閉じる
        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 cleanedTitle = stripExcludeWords(title, settings.excludeWords);
        const shortcode = `[affiliate_link asin="${asin}" kw="${cleanedTitle}"]`;
        
        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
        });
    }
})();