<?php //子テーマ用関数
if ( !defined( 'ABSPATH' ) ) exit;

//子テーマ用のビジュアルエディタースタイルを適用
add_editor_style();

// 子テーマ用カスタムJSを登録
function enqueue_custom_js() {
    wp_enqueue_script(
        'custom-header-js',
        get_stylesheet_directory_uri() . '/javascript.js',
        array(),
        '1.0',
        true
    );
}
add_action('wp_enqueue_scripts', 'enqueue_custom_js');

// 通常投稿（コラム）以外のページ（制作実績など）で、前後ナビ・関連記事・目次を非表示
add_action('wp_head', function() {
    if (is_singular() && !is_singular('post')) {
        echo '<style>
            #under-entry-body,
            .under-entry-body,
            .pager-post-navi,
            .post-navi,
            .related-list,
            .related-entry-card-wrap,
            .related-box,
            .related-entries,
            .related-entry-heading,
            .toc,
            .entry-toc,
            #toc,
            .toc-box,
            .widget_toc {
                display: none !important;
            }
        </style>';
    }
});

// 独自カスタムヘッダーのショートコード定義 [custom_header]
add_shortcode('custom_header', 'add_custom_header_shortcode');
function add_custom_header_shortcode() {
    ob_start();
    ?>
    <script>
    function openCustomDrawer(e) {
        if (e) {
            if (e.preventDefault) e.preventDefault();
            if (e.stopPropagation) e.stopPropagation();
        }
        var nav = document.getElementById("custom-nav-sp");
        if (nav) {
            nav.style.setProperty("right", "0", "important");
            nav.classList.add("is-open");
        }
        return false;
    }

    function closeCustomDrawer(e) {
        if (e) {
            if (e.preventDefault) e.preventDefault();
            if (e.stopPropagation) e.stopPropagation();
        }
        var nav = document.getElementById("custom-nav-sp");
        if (nav) {
            nav.style.setProperty("right", "-100%", "important");
            nav.classList.remove("is-open");
        }
        return false;
    }
    </script>

    <!-- PCヘッダ -->
    <header id="custom-header-pc">
        <div class="logo">
            <a href="/" title="トップページへ">IMC SEO & Contents Factory</a>
        </div>
        <nav id="custom-nav-pc">
            <a href="/">TOP</a>
            <a href="/service/">商品・サービス</a>
            <a href="/work-flow/">お仕事の流れ</a>
            <a href="/contact/">お問い合わせ</a>
            <a href="/company/">運営会社情報</a>
        </nav>
    </header>

    <!-- タブレットヘッダ -->
    <header id="custom-header-tb">
        <div class="logo">
            <a href="/" title="トップページへ">IMC SEO & Contents Factory</a>
        </div>
        <nav id="custom-nav-tb">
            <a href="/">TOP</a>
            <a href="/service/">商品・サービス</a>
            <a href="/work-flow/">お仕事の流れ</a>
            <a href="/contact/">お問い合わせ</a>
            <a href="/company/">運営会社情報</a>
        </nav>
    </header>

    <!-- SPヘッダ -->
    <header id="custom-header-sp">
        <div class="logo">
            <a href="/" title="トップページへ">IMC SEO & Contents Factory</a>
        </div>
        <button class="navi-menu-button" id="customSpMenuBtn" type="button" onclick="openCustomDrawer(event)" aria-label="モバイルメニュー開閉">
            <span class="fa fa-bars"></span>
            <div class="menu-text">メニュー</div>
        </button>

        <nav id="custom-nav-sp">
            <div id="customSpMenuClose" onclick="closeCustomDrawer(event)" role="button" aria-label="メニューを閉じる">?</div>
            <a href="/">TOP</a>
            <a href="/service/">商品・サービス</a>
            <a href="/work-flow/">お仕事の流れ</a>
            <a href="/contact/">お問い合わせ</a>
            <a href="/company/">運営会社情報</a>
            <div class="custom-mobile-links">
                <ul>
                    <li><a href="/privacy">プライバシーポリシー</a></li>
                    <li><a href="/terms">利用規約</a></li>
                    <li><a href="/commerce">特定商取引法に基づく表記</a></li>
                    <li><a href="/faq">FAQ（よくある質問）</a></li>
                </ul>
            </div>
        </nav>
    </header>

    <style>
    #custom-header-sp #customSpMenuBtn {
        position: relative !important;
        z-index: 99999 !important;
        pointer-events: auto !important;
        cursor: pointer !important;
    }

    #custom-nav-sp {
        position: fixed !important;
        top: 0 !important;
        right: -100% !important;
        width: 80% !important;
        max-width: 300px !important;
        height: 100vh !important;
        background: #444444 !important;
        color: #ffffff !important;
        z-index: 999999 !important;
        padding: 60px 20px 20px 20px !important;
        box-shadow: -2px 0 10px rgba(0,0,0,0.3) !important;
        overflow-y: auto !important;
        transition: right 0.3s ease !important;
    }

    #custom-nav-sp a {
        display: block !important;
        padding: 12px 0 !important;
        color: #ffffff !important;
        border-bottom: 1px solid rgba(255,255,255,0.15) !important;
        text-decoration: none !important;
    }

    #customSpMenuClose {
        position: absolute !important;
        top: 15px !important;
        right: 15px !important;
        width: 44px !important;
        height: 44px !important;
        font-size: 32px !important;
        line-height: 44px !important;
        text-align: center !important;
        color: #ffffff !important;
        cursor: pointer !important;
        z-index: 10000000 !important;
        pointer-events: auto !important;
    }
    </style>
    <?php
    return ob_get_clean();
}

// メインビジュアルショートコード [col_mv img="..." title="..."]
add_shortcode('col_mv', function($atts) {
    $atts = shortcode_atts(array(
        'img'   => '',
        'title' => '',
    ), $atts);

    if (empty($atts['img'])) return '';

    return '<div class="col-main-visual" style="background-image: url(' . $atts['img'] . ');"><div class="col-mv-inner"><h1 class="col-mv-title">' . $atts['title'] . '</h1></div></div>';
});

// 章画像ショートコード [col_img src="..." alt="..."]
add_shortcode('col_img', function($atts) {
    $atts = shortcode_atts(array(
        'src' => '',
        'alt' => '',
    ), $atts);

    if (empty($atts['src'])) return '';

    return '<div class="column-image" style="width: 100%; margin: 20px 0;"><img src="' . $atts['src'] . '" alt="' . $atts['alt'] . '" style="width: 100%; height: auto; display: block; border-radius: 4px;"></div>';
});

// 自動描画型 目次ショートコード [col_toc]
add_shortcode('col_toc', function() {
    return '<div class="custom-col-toc-target"></div>';
});

// 記事本文内のH2だけを抽出して目次を挿入するJS
add_action('wp_footer', function() {
    if (!is_singular()) return;
    ?>
    <script>
    (function renderCustomToc() {
        function initToc() {
            var targets = document.querySelectorAll('.custom-col-toc-target');
            if (!targets.length) return;

            var contentArea = document.querySelector('.entry-content') || document.querySelector('.post-content') || document.querySelector('article');
            if (!contentArea) return;

            var allH2 = Array.from(contentArea.querySelectorAll('h2')).filter(function(h2) {
                return !h2.classList.contains('col-mv-title') && !h2.closest('.custom-col-toc-target');
            });

            targets.forEach(function(target) {
                if (allH2.length === 0) return;

                var html = '<div style="border: 1px solid #e0e0e0; background: #f9f9f9; padding: 20px; margin: 30px 0; border-radius: 4px;">';
                html += '<div style="display: flex; align-items: center; gap: 12px; border-bottom: 2px solid #333; padding-bottom: 8px;">';
                html += '<span style="font-weight: bold; font-size: 16px; color: #333;">目次</span>';
                html += '<button type="button" class="col-toc-toggle" style="background: none; border: none; color: #666; font-size: 13px; cursor: pointer; padding: 0;">[閉じる]</button>';
                html += '</div>';
                html += '<ul class="col-toc-ul" style="list-style: none; padding-left: 0; margin: 15px 0 0 0; display: block;">';

                var count = 0;

                allH2.forEach(function(h2, i) {
                    var anchorId = "index_id" + (i + 1);
                    h2.id = anchorId;

                    var titleText = h2.textContent.trim();
                    var isMatome = titleText.indexOf('まとめ') !== -1 || h2.classList.contains('matome-h2') || h2.classList.contains('sec-h2-matome');

                    html += '<li style="margin-bottom: 10px; font-size: 14px; line-height: 1.6;">';
                    html += '<a href="#' + anchorId + '" style="color: #333; text-decoration: none; display: flex; align-items: baseline;">';

                    if (!isMatome) {
                        count++;
                        var numStr = String(count).padStart(2, "0");
                        html += '<span style="font-weight: bold; margin-right: 10px; color: #666; font-family: Montserrat, sans-serif;">' + numStr + '</span>';
                    }

                    html += '<span>' + titleText + '</span>';
                    html += '</a></li>';
                });

                html += '</ul></div>';
                target.innerHTML = html;

                var btn = target.querySelector('.col-toc-toggle');
                var ul = target.querySelector('.col-toc-ul');
                if (btn && ul) {
                    btn.addEventListener('click', function() {
                        if (ul.style.display === 'none') {
                            ul.style.display = 'block';
                            btn.textContent = '[閉じる]';
                        } else {
                            ul.style.display = 'none';
                            btn.textContent = '[開く]';
                        }
                    });
                }
            });
        }

        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', initToc);
        } else {
            initToc();
        }
    })();
    </script>
    <?php
});

// カスタムSNSシェアボタンショートコード [col_sns]
add_shortcode('col_sns', function() {
    if (!is_singular()) return '';

    $url   = urlencode(get_permalink());
    $title = urlencode(get_the_title());

    return '
    <div class="col-sns-share" style="margin: 40px 0; padding: 24px 20px; background: #fdfdfd; border: 1px solid #eee; border-radius: 6px; text-align: center;">
        <p style="font-weight: bold; font-size: 15px; color: #333; margin: 0 0 16px 0;">この記事をシェアする</p>
        <div style="display: flex; justify-content: center; align-items: center; gap: 10px; flex-wrap: wrap;">
            <a href="https://twitter.com/share?url=' . $url . '&text=' . $title . '" target="_blank" rel="nofollow noopener" style="display: flex; align-items: center; justify-content: center; width: 44px; height: 44px; background: #000; color: #fff; border-radius: 50%; text-decoration: none; font-weight: bold; font-size: 14px;" title="Xでシェア">X</a>
            <a href="https://www.facebook.com/sharer/sharer.php?u=' . $url . '" target="_blank" rel="nofollow noopener" style="display: flex; align-items: center; justify-content: center; width: 44px; height: 44px; background: #1877f2; color: #fff; border-radius: 50%; text-decoration: none; font-weight: bold; font-size: 14px;" title="Facebookでシェア">fb</a>
            <a href="https://social-plugins.line.me/lineit/share?url=' . $url . '" target="_blank" rel="nofollow noopener" style="display: flex; align-items: center; justify-content: center; width: 44px; height: 44px; background: #06c755; color: #fff; border-radius: 50%; text-decoration: none; font-weight: bold; font-size: 13px;" title="LINEで送る">LINE</a>
            <a href="https://b.hatena.ne.jp/entry/' . get_permalink() . '" target="_blank" rel="nofollow noopener" style="display: flex; align-items: center; justify-content: center; width: 44px; height: 44px; background: #00a4de; color: #fff; border-radius: 50%; text-decoration: none; font-weight: bold; font-size: 14px;" title="はてなブックマークに追加">B!</a>
            <button type="button" onclick="navigator.clipboard.writeText(\'' . get_permalink() . '\'); alert(\'URLをコピーしました！\');" style="display: flex; align-items: center; justify-content: center; width: 44px; height: 44px; background: #666; color: #fff; border: none; border-radius: 50%; cursor: pointer; font-size: 12px; font-weight: bold;" title="URLをコピー">Copy</button>
        </div>
    </div>';
});

// 制作実績用カスタムスライダーショートコード [works_carousel count="4" cat_id="カテゴリーID"]
add_shortcode('works_carousel', function($atts) {
    $atts = shortcode_atts(array(
        'count'  => 4,
        'cat_id' => '',
    ), $atts);

    $args = array(
        'posts_per_page' => intval($atts['count']),
        'post_type'      => 'post', // カスタム投稿タイプなどの場合は変更
        'orderby'        => 'date',
        'order'          => 'DESC',
    );

    if (!empty($atts['cat_id'])) {
        $args['cat'] = intval($atts['cat_id']);
    }

    $query = new WP_Query($args);
    if (!$query->have_posts()) return '';

    ob_start();
    ?>
    <div class="works-custom-grid">
        <?php while ($query->have_posts()) : $query->the_post(); 
            $cats = get_the_category();
            $cat_name = !empty($cats) ? esc_html($cats[0]->name) : '';
            $thumb_url = get_the_post_thumbnail_url(get_the_ID(), 'medium');
            if (!$thumb_url) $thumb_url = get_cocoon_site_default_image_url(); // アイキャッチがない場合のデフォルト画像
        ?>
            <div class="works-custom-item">
                <a href="<?php the_permalink(); ?>" class="works-custom-link">
                    <div class="works-custom-image">
                        <img src="<?php echo esc_url($thumb_url); ?>" alt="<?php the_title_attribute(); ?>">
                    </div>
                    <h3 class="works-custom-title"><?php the_title(); ?></h3>
                    <?php if ($cat_name) : ?>
                        <div class="works-custom-category">
                            <span class="works-custom-cat-label"><?php echo $cat_name; ?></span>
                        </div>
                    <?php endif; ?>
                </a>
            </div>
        <?php endwhile; wp_reset_postdata(); ?>
    </div>
    <?php
    return ob_get_clean();
});