<?php
if (!defined('ABSPATH')) exit;

class SailWP_Copilot_Rail {
    const HANDLE = 'sailwp-copilot-rail';

    public function __construct() {
        add_action('admin_enqueue_scripts', [$this, 'enqueue']);
        add_action('wp_enqueue_scripts',    [$this, 'enqueue']);
        add_action('admin_footer',          [$this, 'render']);
        add_action('wp_footer',             [$this, 'render']);
        add_action('admin_body_class',      [$this, 'admin_body_class']);
        add_filter('body_class',            [$this, 'frontend_body_class']);
    }

    public function should_render() {
        $show = is_user_logged_in() && current_user_can('edit_posts');
        return (bool) apply_filters('sailwp_copilot_rail_show', $show);
    }

    public function enqueue() {
        if (!$this->should_render()) return;
        // Cache-bust on every asset edit. Cloudflare in front of the test
        // sites was serving stale rail.js / rail.css for 30 days because the
        // plain SAILWP_COPILOT_VERSION URL had no querystring there. Using
        // the file's mtime as the version string forces a new URL whenever
        // we touch the asset, so CF treats it as a brand new resource.
        $css_path = SAILWP_COPILOT_DIR . 'assets/css/rail.css';
        $js_path  = SAILWP_COPILOT_DIR . 'assets/js/rail.js';
        $css_ver  = file_exists($css_path) ? (string) filemtime($css_path) : SAILWP_COPILOT_VERSION;
        $js_ver   = file_exists($js_path)  ? (string) filemtime($js_path)  : SAILWP_COPILOT_VERSION;
        wp_enqueue_style(
            self::HANDLE,
            SAILWP_COPILOT_URL . 'assets/css/rail.css',
            [],
            $css_ver
        );
        wp_enqueue_script(
            self::HANDLE,
            SAILWP_COPILOT_URL . 'assets/js/rail.js',
            [],
            $js_ver,
            true
        );
        wp_localize_script(self::HANDLE, 'SailWPCopilot', [
            'restUrl'    => esc_url_raw(rest_url(SailWP_Copilot_REST::NAMESPACE_V1 . '/')),
            'restNonce'  => wp_create_nonce('wp_rest'),
            'connected'  => SailWP_Copilot_Plugin::is_connected_to_cloud(),
            'cloudUrl'   => SailWP_Copilot_Plugin::get_cloud_url(),
            'aiProxyUrl' => SailWP_Copilot_Plugin::get_ai_proxy_url(),
            'licenseKey' => SailWP_Copilot_Plugin::get_license_key(),
            'isAdmin'    => is_admin(),
            'pluginUrl'  => esc_url_raw(SAILWP_COPILOT_URL),
            'siteLocale' => str_replace('_', '-', get_locale()),
            'context'    => $this->context_for_page(),
            'i18n'       => [
                'title'         => __('Co-pilot', 'sailwp-ai-copilot'),
                'placeholder'   => __('Ask anything', 'sailwp-ai-copilot'),
                'send'          => __('Send', 'sailwp-ai-copilot'),
                'collapse'      => __('Close', 'sailwp-ai-copilot'),
                'expand'        => __('Open co-pilot', 'sailwp-ai-copilot'),
                'newChat'       => __('New chat', 'sailwp-ai-copilot'),
                'standalone'    => __('Local mode', 'sailwp-ai-copilot'),
                'connected'     => __('Cloud connected', 'sailwp-ai-copilot'),
                'emptyTitle'    => __('How can I help?', 'sailwp-ai-copilot'),
                'emptySub'      => __('Pick one or just type. You can paste a Word document or talk through the microphone too.', 'sailwp-ai-copilot'),
                'errorPrefix'   => __('', 'sailwp-ai-copilot'),
            ],
            'suggestions' => $this->suggestions_for_page(),
            // Heavy-action quota (image/video/music gen + page design). The
            // rail footer renders this when heavy_limit !== null; Pro and
            // Founder plans return null = "no cap, hide counter".
            'quota'      => SailWP_Copilot_Plugin::get_quota_cache(),
            'pricingUrl' => 'https://sailwp.com/copilot',
            // Hint to the rail JS that it should expand on first load for
            // this screen if the user hasn't manually toggled it before.
            // Joost 2026-05-19 video feedback: switching to the AI editor
            // and still having to hunt for the bubble breaks the flow.
            'autoOpen'   => $this->should_auto_open(),
        ]);
    }

    public function admin_body_class($classes) {
        if ($this->should_render()) {
            $classes .= ' has-sailwp-copilot-rail';
        }
        return $classes;
    }

    public function frontend_body_class($classes) {
        if ($this->should_render()) {
            $classes[] = 'has-sailwp-copilot-rail';
        }
        return $classes;
    }

    public function render() {
        if (!$this->should_render()) return;
        ?>
        <div id="sailwp-copilot-rail" class="sw-rail" data-collapsed="true" aria-label="SailWP Co-pilot"></div>
        <?php
    }

    /**
     * Screens where the Co-pilot should expand by default the first time
     * the user lands there (localStorage still wins for explicit closes):
     *
     *   - the front-end inline-edit overlay (?swcp_edit=1) — Co-pilot is
     *     the whole point of being there
     *   - any post/page edit screen — Joost's video feedback was that
     *     "switch to SailWP AI" should drop you in with the rail open
     *   - the front-end of a Co-pilot-designed page (the user can iterate
     *     on it via chat without re-opening manually)
     *
     * Everything else (Dashboard widgets, plugin admin pages, archives,
     * the front-end of un-designed pages) stays collapsed by default.
     */
    private function should_auto_open() {
        // Inline-edit overlay on the front end (either explicit ?swcp_edit=1
        // OR the iframe-bridge session cookie that persists edit-mode across
        // navigation).
        if (!is_admin()
            && class_exists('SailWP_Copilot_Iframe_Bridge')
            && SailWP_Copilot_Iframe_Bridge::is_edit_mode_requested()
        ) {
            return true;
        }
        if (is_admin() && function_exists('get_current_screen')) {
            $screen = get_current_screen();
            if ($screen && in_array($screen->base, ['post'], true)
                && in_array($screen->post_type, ['page', 'post'], true)) {
                return true;
            }
        }
        if (!is_admin() && is_singular()) {
            $pid = (int) get_queried_object_id();
            if ($pid && (int) get_post_meta($pid, '_swcp_designed', true) === 1) {
                return true;
            }
        }
        return false;
    }

    private function context_for_page() {
        $ctx = [
            'url'         => is_admin() ? (isset($_SERVER['REQUEST_URI']) ? esc_url_raw(home_url($_SERVER['REQUEST_URI'])) : '') : (function_exists('home_url') ? home_url(add_query_arg(null, null)) : ''),
            'siteName'    => get_bloginfo('name'),
            'screen'      => '',
            'postId'      => 0,
            'postTitle'   => '',
            'postType'    => '',
            'pageBuilder' => '',
            'designed'    => false, // _swcp_designed flag — true when this page was built by the Co-pilot. v0.24.6 (Joost 2026-05-17): Claude needs to know so it routes "add a section" through iterate_page_design (preserves scoped CSS), not insert_block (which adds raw Gutenberg blocks outside the design-root and looks unstyled).
        ];
        $current_post_id = 0;
        if (is_admin() && function_exists('get_current_screen')) {
            $screen = get_current_screen();
            if ($screen) $ctx['screen'] = $screen->id;
            // Editor screen ('post' / 'page') exposes the post being edited
            // via the GET 'post' param.
            if (isset($_GET['post']) && is_numeric($_GET['post'])) {
                $current_post_id = (int) $_GET['post'];
            }
        } else {
            if (is_singular())      $ctx['screen'] = 'frontend:singular:' . get_post_type();
            elseif (is_archive())   $ctx['screen'] = 'frontend:archive';
            elseif (is_home())      $ctx['screen'] = 'frontend:home';
            elseif (is_front_page())$ctx['screen'] = 'frontend:front';
            else                    $ctx['screen'] = 'frontend';
            if (is_singular()) $current_post_id = (int) get_queried_object_id();
        }
        if ($current_post_id > 0) {
            $ctx['postId']    = $current_post_id;
            $ctx['postTitle'] = (string) get_the_title($current_post_id);
            $ctx['postType']  = (string) get_post_type($current_post_id);
            if (function_exists('swcp_detect_page_builder')) {
                $ctx['pageBuilder'] = swcp_detect_page_builder($current_post_id);
            }
            $ctx['designed'] = (int) get_post_meta($current_post_id, '_swcp_designed', true) === 1;
        }
        return $ctx;
    }

    private function suggestions_for_page() {
        $screen = '';
        if (is_admin() && function_exists('get_current_screen')) {
            $sc = get_current_screen();
            if ($sc) $screen = $sc->id;
        }

        $on_post_edit = (strpos($screen, 'post') === 0 || $screen === 'page');

        // Suggestions map directly to the v1 tool-set so a click is one
        // command away from a real edit. Worded the way the user would
        // type it — no jargon, no block-editor terms.
        if ($on_post_edit) {
            return [
                __('Redesign this page', 'sailwp-ai-copilot'),
                __('Fix the headings on this page', 'sailwp-ai-copilot'),
                __('Remove duplicate titles on this page', 'sailwp-ai-copilot'),
                __('Turn testimonials on this page into a carousel', 'sailwp-ai-copilot'),
                __('Make the contact form on this page send to my email', 'sailwp-ai-copilot'),
                __('Show me what you can do', 'sailwp-ai-copilot'),
            ];
        }

        return [
            __('Redesign my About page', 'sailwp-ai-copilot'),
            __('Remove duplicate titles on my homepage', 'sailwp-ai-copilot'),
            __('Fix the headings on my homepage', 'sailwp-ai-copilot'),
            __('Turn the testimonials on my homepage into a carousel', 'sailwp-ai-copilot'),
            __('Wire my contact form to send to my email', 'sailwp-ai-copilot'),
            __('Show me what you can do', 'sailwp-ai-copilot'),
        ];
    }
}
