<?php
defined( 'ABSPATH' ) || exit;

// ── Load website kit manifests ────────────────────────────────────────────────

$jalpi_kits_dir = JALPI_DIR . 'websites/';
$jalpi_kits     = [];

foreach ( (array) glob( $jalpi_kits_dir . '*.json' ) as $jalpi_file ) {
    // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents -- reading a local plugin JSON file; WP_Filesystem requires credentials and is not suitable here
    $jalpi_raw = file_get_contents( $jalpi_file );
    $jalpi_kit = json_decode( $jalpi_raw, true );
    if ( ! $jalpi_kit || empty( $jalpi_kit['id'] ) || empty( $jalpi_kit['name'] ) ) continue;

    $jalpi_gradient = (array) ( $jalpi_kit['preview_gradient'] ?? [] );

    $jalpi_page_titles = array_map(
        fn( $p ) => sanitize_text_field( $p['title'] ?? '' ),
        $jalpi_kit['pages'] ?? []
    );

    $jalpi_page_slugs = array_map(
        fn( $p ) => sanitize_key( $p['slug'] ?? '' ),
        $jalpi_kit['pages'] ?? []
    );

    // Real screenshot thumbnail. A kit may ship `thumbnail` as a filename in
    // websites/thumbnails/ (preferred) or an absolute https URL. When present
    // the card shows the actual site instead of the CSS wireframe placeholder.
    $jalpi_thumb     = '';
    $jalpi_thumb_raw = trim( (string) ( $jalpi_kit['thumbnail'] ?? '' ) );
    if ( '' !== $jalpi_thumb_raw ) {
        if ( preg_match( '#^https://#i', $jalpi_thumb_raw ) ) {
            $jalpi_thumb = esc_url_raw( $jalpi_thumb_raw );
        } else {
            // Local file: basename only, so a manifest can never traverse out
            // of the thumbnails directory.
            $jalpi_thumb_file = basename( $jalpi_thumb_raw );
            if ( preg_match( '/^[A-Za-z0-9._-]+\.(png|jpe?g|webp)$/', $jalpi_thumb_file )
                && file_exists( $jalpi_kits_dir . 'thumbnails/' . $jalpi_thumb_file ) ) {
                $jalpi_thumb = JALPI_URL . 'websites/thumbnails/' . $jalpi_thumb_file;
            }
        }
    }

    $jalpi_kits[] = [
        'id'           => sanitize_key( $jalpi_kit['id'] ),
        'name'         => sanitize_text_field( $jalpi_kit['name'] ),
        'description'  => sanitize_text_field( $jalpi_kit['description'] ?? '' ),
        'category'     => sanitize_key( $jalpi_kit['category'] ?? 'general' ),
        'color'        => sanitize_hex_color( $jalpi_kit['color'] ?? '#5b6af5' ) ?: '#5b6af5',
        'grad_from'    => sanitize_hex_color( $jalpi_gradient[0] ?? $jalpi_kit['color'] ?? '#5b6af5' ) ?: '#5b6af5',
        'grad_to'      => sanitize_hex_color( $jalpi_gradient[1] ?? '#1a1a2e' ) ?: '#1a1a2e',
        'thumbnail'    => $jalpi_thumb,
        'pages_count'  => count( $jalpi_kit['pages'] ?? [] ),
        'page_titles'  => $jalpi_page_titles,
        'page_slugs'   => $jalpi_page_slugs,
    ];
}

usort( $jalpi_kits, fn( $a, $b ) => strcmp( $a['name'], $b['name'] ) );

$jalpi_all_categories = array_values( array_unique( array_column( $jalpi_kits, 'category' ) ) );
sort( $jalpi_all_categories );

// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only GET param for display filtering, no state change
$jalpi_active_cat    = sanitize_key( $_GET['category'] ?? '' );
$jalpi_filtered_kits = $jalpi_active_cat
    ? array_values( array_filter( $jalpi_kits, fn( $k ) => $k['category'] === $jalpi_active_cat ) )
    : $jalpi_kits;

$jalpi_base_url = admin_url( 'admin.php?page=jalpi-website-templates' );
?>
<div class="wrap cbss-wrap">

  <!-- ── Header ──────────────────────────────────────────────────────────── -->
  <div class="cbss-header">
    <div>
      <h1 class="cbss-heading"><?php esc_html_e( 'Starter Sites', 'jalpi-page-builder' ); ?></h1>
      <p class="cbss-intro"><?php esc_html_e( 'Import a complete website in one click — pages, navigation, and design included.', 'jalpi-page-builder' ); ?></p>
    </div>
  </div>

  <!-- ── Category tabs ───────────────────────────────────────────────────── -->
  <nav class="nav-tab-wrapper cbss-tabs">
    <a href="<?php echo esc_url( $jalpi_base_url ); ?>"
       class="nav-tab<?php echo '' === $jalpi_active_cat ? ' nav-tab-active' : ''; ?>">
      <?php esc_html_e( 'All', 'jalpi-page-builder' ); ?>
      <span class="cbss-tab-count"><?php echo esc_html( count( $jalpi_kits ) ); ?></span>
    </a>
    <?php foreach ( $jalpi_all_categories as $jalpi_cat ) :
      $jalpi_cat_count = count( array_filter( $jalpi_kits, fn( $k ) => $k['category'] === $jalpi_cat ) );
    ?>
    <a href="<?php echo esc_url( add_query_arg( 'category', $jalpi_cat, $jalpi_base_url ) ); ?>"
       class="nav-tab<?php echo esc_attr( $jalpi_active_cat === $jalpi_cat ? ' nav-tab-active' : '' ); ?>">
      <?php echo esc_html( ucfirst( $jalpi_cat ) ); ?>
      <span class="cbss-tab-count"><?php echo esc_html( $jalpi_cat_count ); ?></span>
    </a>
    <?php endforeach; ?>
  </nav>

  <!-- ── Kit grid ────────────────────────────────────────────────────────── -->
  <div class="cbss-grid" id="cbss-grid">

    <?php foreach ( $jalpi_filtered_kits as $jalpi_kit ) :
      $jalpi_kit_data = wp_json_encode( [
          'id'          => $jalpi_kit['id'],
          'name'        => $jalpi_kit['name'],
          'description' => $jalpi_kit['description'],
          'category'    => $jalpi_kit['category'],
          'color'       => $jalpi_kit['color'],
          'grad_from'   => $jalpi_kit['grad_from'],
          'grad_to'     => $jalpi_kit['grad_to'],
          'pages_count' => $jalpi_kit['pages_count'],
          'page_titles' => $jalpi_kit['page_titles'],
          'page_slugs'  => $jalpi_kit['page_slugs'],
      ] );
    ?>
    <article class="cbss-card"
             data-category="<?php echo esc_attr( $jalpi_kit['category'] ); ?>"
             data-kit="<?php echo esc_attr( $jalpi_kit_data ); ?>">

      <!-- Preview / hover overlay -->
      <div class="cbss-card__preview"
           style="background:linear-gradient(145deg,<?php echo esc_attr( $jalpi_kit['grad_from'] ); ?>,<?php echo esc_attr( $jalpi_kit['grad_to'] ); ?>)">
        <?php if ( $jalpi_kit['thumbnail'] ) : ?>
          <!-- Real screenshot of the kit's home page. Anchored to the top so the
               hero is always visible; the card scrolls it on hover. -->
          <img class="cbss-card__shot"
               src="<?php echo esc_url( $jalpi_kit['thumbnail'] ); ?>"
               alt=""
               loading="lazy"
               aria-hidden="true" />
        <?php else : ?>
        <!-- Wire mockup (fallback when a kit ships no screenshot) -->
        <div class="cbss-card__wire" aria-hidden="true">
          <div class="cbss-card__wire-bar" style="background:<?php echo esc_attr( $jalpi_kit['color'] ); ?>40"></div>
          <div class="cbss-card__wire-hero" style="background:<?php echo esc_attr( $jalpi_kit['color'] ); ?>25"></div>
          <div class="cbss-card__wire-cols">
            <div style="background:<?php echo esc_attr( $jalpi_kit['color'] ); ?>30"></div>
            <div style="background:<?php echo esc_attr( $jalpi_kit['color'] ); ?>30"></div>
            <div style="background:<?php echo esc_attr( $jalpi_kit['color'] ); ?>30"></div>
          </div>
          <div class="cbss-card__wire-footer" style="background:<?php echo esc_attr( $jalpi_kit['color'] ); ?>20"></div>
        </div>
        <?php endif; ?>
        <!-- Hover overlay — Preview + Import -->
        <div class="cbss-card__overlay">
          <button type="button"
                  class="button cbss-preview-btn"
                  data-id="<?php echo esc_attr( $jalpi_kit['id'] ); ?>">
            <?php esc_html_e( 'Preview', 'jalpi-page-builder' ); ?>
          </button>
          <button type="button"
                  class="button button-primary cbss-import-btn"
                  data-id="<?php echo esc_attr( $jalpi_kit['id'] ); ?>"
                  data-name="<?php echo esc_attr( $jalpi_kit['name'] ); ?>"
                  data-pages="<?php echo esc_attr( $jalpi_kit['pages_count'] ); ?>">
            <?php esc_html_e( 'Import', 'jalpi-page-builder' ); ?>
          </button>
        </div>
      </div>

      <!-- Card body -->
      <div class="cbss-card__body">
        <div class="cbss-card__top">
          <span class="cbss-card__dot" style="background:<?php echo esc_attr( $jalpi_kit['color'] ); ?>"></span>
          <h3 class="cbss-card__name"><?php echo esc_html( $jalpi_kit['name'] ); ?></h3>
          <span class="cbss-card__pages-badge">
            <?php echo esc_html( $jalpi_kit['pages_count'] ); ?>&nbsp;<?php esc_html_e( 'pages', 'jalpi-page-builder' ); ?>
          </span>
        </div>
        <p class="cbss-card__desc"><?php echo esc_html( $jalpi_kit['description'] ); ?></p>
        <div class="cbss-card__actions">
          <button type="button"
                  class="button cbss-preview-btn"
                  data-id="<?php echo esc_attr( $jalpi_kit['id'] ); ?>">
            <?php esc_html_e( 'Preview', 'jalpi-page-builder' ); ?>
          </button>
          <button type="button"
                  class="button button-primary cbss-import-btn"
                  data-id="<?php echo esc_attr( $jalpi_kit['id'] ); ?>"
                  data-name="<?php echo esc_attr( $jalpi_kit['name'] ); ?>"
                  data-pages="<?php echo esc_attr( $jalpi_kit['pages_count'] ); ?>">
            <?php esc_html_e( 'Import', 'jalpi-page-builder' ); ?>
          </button>
        </div>
      </div>

    </article>
    <?php endforeach; ?>

    <?php if ( empty( $jalpi_filtered_kits ) ) : ?>
    <div class="cbss-empty">
      <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.2" stroke-linecap="round">
        <rect x="2" y="3" width="20" height="14" rx="2"/><line x1="8" y1="21" x2="16" y2="21"/><line x1="12" y1="17" x2="12" y2="21"/>
      </svg>
      <p><?php esc_html_e( 'No website kits found in this category.', 'jalpi-page-builder' ); ?></p>
    </div>
    <?php endif; ?>

  </div><!-- .cbss-grid -->

</div><!-- .wrap -->

<!-- ═══════════════════════ Preview modal ═════════════════════════════════ -->
<div id="cbss-preview-overlay" class="cbss-overlay" aria-hidden="true" role="dialog" aria-labelledby="cbss-preview-title">
  <div class="cbss-modal cbss-modal--preview">

    <!-- ── Close ─────────────────────────────────────────────────────────── -->
    <button type="button" class="cbss-modal__close cbss-preview-close-x" id="cbss-preview-close" aria-label="<?php esc_attr_e( 'Close preview', 'jalpi-page-builder' ); ?>">
      <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round">
        <line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>
      </svg>
    </button>

    <!-- ── Split layout ───────────────────────────────────────────────────── -->
    <div class="cbss-preview-split">

      <!-- Left — large visual mockup -->
      <div class="cbss-preview-left" id="cbss-preview-left">
        <!-- Filled by JS with gradient + detailed wireframe -->
      </div>

      <!-- Right — details + actions -->
      <div class="cbss-preview-right">

        <div class="cbss-preview-meta">
          <span class="cbss-preview-cat" id="cbss-preview-cat"></span>
          <h2 class="cbss-preview-title" id="cbss-preview-title"></h2>
          <p class="cbss-preview-desc" id="cbss-preview-desc"></p>
        </div>

        <div class="cbss-preview-pages">
          <p class="cbss-preview-pages__label"><?php esc_html_e( 'Included pages', 'jalpi-page-builder' ); ?></p>
          <ul id="cbss-preview-page-list" class="cbss-preview-page-list"></ul>
        </div>

        <div class="cbss-preview-actions">
          <button type="button" class="button" id="cbss-preview-cancel">
            <?php esc_html_e( 'Close', 'jalpi-page-builder' ); ?>
          </button>
          <button type="button"
                  class="button button-primary cbss-preview-import-btn"
                  id="cbss-preview-import">
            <?php esc_html_e( 'Import Website', 'jalpi-page-builder' ); ?>
          </button>
        </div>

      </div><!-- .cbss-preview-right -->
    </div><!-- .cbss-preview-split -->
  </div><!-- .cbss-modal -->
</div><!-- #cbss-preview-overlay -->

<!-- ═══════════════════════ Import modal ══════════════════════════════════ -->
<div id="cbss-overlay" class="cbss-overlay" aria-hidden="true" role="dialog" aria-labelledby="cbss-modal-title">
  <div class="cbss-modal" id="cbss-modal">

    <!-- ── State: Confirm ──────────────────────────────────────────────── -->
    <div id="cbss-state-confirm" class="cbss-state">
      <div class="cbss-modal__hd">
        <div class="cbss-modal__hd-icon">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round">
            <rect x="2" y="3" width="20" height="14" rx="2"/><line x1="8" y1="21" x2="16" y2="21"/><line x1="12" y1="17" x2="12" y2="21"/>
          </svg>
        </div>
        <div class="cbss-modal__hd-text">
          <h2 id="cbss-modal-title" class="cbss-modal__title"></h2>
          <p class="cbss-modal__sub" id="cbss-modal-sub"></p>
        </div>
        <button type="button" class="cbss-modal__close" id="cbss-close" aria-label="<?php esc_attr_e( 'Close', 'jalpi-page-builder' ); ?>">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round">
            <line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>
          </svg>
        </button>
      </div>
      <div class="cbss-modal__body">
        <div class="cbss-notice">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round">
            <circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/>
          </svg>
          <p><?php esc_html_e( 'This will create new pages on your site. Your existing content will not be affected.', 'jalpi-page-builder' ); ?></p>
        </div>
        <label class="cbss-checkbox-row">
          <input type="checkbox" id="cbss-set-front" checked>
          <span><?php esc_html_e( 'Set the imported Home page as the site front page', 'jalpi-page-builder' ); ?></span>
        </label>
      </div>
      <div class="cbss-modal__ft">
        <button type="button" class="button" id="cbss-cancel"><?php esc_html_e( 'Cancel', 'jalpi-page-builder' ); ?></button>
        <button type="button" class="button button-primary" id="cbss-confirm">
          <?php esc_html_e( 'Import Website', 'jalpi-page-builder' ); ?>
        </button>
      </div>
    </div>

    <!-- ── State: Importing ────────────────────────────────────────────── -->
    <div id="cbss-state-progress" class="cbss-state" style="display:none">
      <div class="cbss-modal__body cbss-progress-body">
        <div class="cbss-spinner" aria-hidden="true"></div>
        <p class="cbss-progress-label"><?php esc_html_e( 'Importing website…', 'jalpi-page-builder' ); ?></p>
        <p class="cbss-progress-sub"><?php esc_html_e( 'Creating pages and setting up navigation.', 'jalpi-page-builder' ); ?></p>
      </div>
    </div>

    <!-- ── State: Success ──────────────────────────────────────────────── -->
    <div id="cbss-state-success" class="cbss-state" style="display:none">
      <div class="cbss-modal__hd">
        <div class="cbss-modal__hd-icon cbss-modal__hd-icon--success">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round">
            <polyline points="20 6 9 17 4 12"/>
          </svg>
        </div>
        <div class="cbss-modal__hd-text">
          <h2 class="cbss-modal__title"><?php esc_html_e( 'Website Imported!', 'jalpi-page-builder' ); ?></h2>
          <p class="cbss-modal__sub" id="cbss-success-sub"></p>
        </div>
      </div>
      <div class="cbss-modal__body">
        <p class="cbss-success-label"><?php esc_html_e( 'Pages created:', 'jalpi-page-builder' ); ?></p>
        <ul id="cbss-page-list" class="cbss-page-list"></ul>
      </div>
      <div class="cbss-modal__ft">
        <a id="cbss-view-site" href="<?php echo esc_url( home_url( '/' ) ); ?>" target="_blank" class="button">
          <?php esc_html_e( 'View Site', 'jalpi-page-builder' ); ?>
        </a>
        <button type="button" class="button button-primary" id="cbss-done">
          <?php esc_html_e( 'Done', 'jalpi-page-builder' ); ?>
        </button>
      </div>
    </div>

    <!-- ── State: Error ────────────────────────────────────────────────── -->
    <div id="cbss-state-error" class="cbss-state" style="display:none">
      <div class="cbss-modal__hd">
        <div class="cbss-modal__hd-icon cbss-modal__hd-icon--error">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round">
            <circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/>
          </svg>
        </div>
        <div class="cbss-modal__hd-text">
          <h2 class="cbss-modal__title"><?php esc_html_e( 'Import Failed', 'jalpi-page-builder' ); ?></h2>
          <p class="cbss-modal__sub" id="cbss-error-msg"></p>
        </div>
        <button type="button" class="cbss-modal__close" id="cbss-err-close" aria-label="<?php esc_attr_e( 'Close', 'jalpi-page-builder' ); ?>">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round">
            <line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>
          </svg>
        </button>
      </div>
      <div class="cbss-modal__ft">
        <button type="button" class="button button-primary" id="cbss-err-close-btn">
          <?php esc_html_e( 'Close', 'jalpi-page-builder' ); ?>
        </button>
      </div>
    </div>

  </div><!-- .cbss-modal -->
</div><!-- #cbss-overlay -->

<!-- ═══════════════════════ Full Site Preview ══════════════════════════════ -->
<div id="cbss-fullpv-overlay" class="cbss-fullpv-overlay" aria-hidden="true" role="dialog" aria-label="<?php esc_attr_e( 'Site Preview', 'jalpi-page-builder' ); ?>">
  <div class="cbss-fullpv-wrap">

    <!-- ── Toolbar ──────────────────────────────────────────────────────── -->
    <div class="cbss-fullpv-bar">

      <div class="cbss-fullpv-bar__left">
        <button type="button" class="cbss-fullpv-close" id="cbss-fullpv-close"
                title="<?php esc_attr_e( 'Close preview', 'jalpi-page-builder' ); ?>">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round">
            <line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>
          </svg>
        </button>
        <span class="cbss-fullpv-bar__name" id="cbss-fullpv-name"></span>
      </div>

      <div class="cbss-fullpv-bar__pages" id="cbss-fullpv-pages">
        <!-- Page tab buttons injected by JS -->
      </div>

      <div class="cbss-fullpv-bar__right">

        <!-- Viewport switcher -->
        <div class="cbss-fullpv-vp" id="cbss-fullpv-vp">
          <button type="button" class="cbss-fullpv-vp__btn is-active" data-vp="desktop"
                  title="<?php esc_attr_e( 'Desktop', 'jalpi-page-builder' ); ?>">
            <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round">
              <rect x="2" y="3" width="20" height="14" rx="2"/><line x1="8" y1="21" x2="16" y2="21"/><line x1="12" y1="17" x2="12" y2="21"/>
            </svg>
          </button>
          <button type="button" class="cbss-fullpv-vp__btn" data-vp="tablet"
                  title="<?php esc_attr_e( 'Tablet', 'jalpi-page-builder' ); ?>">
            <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round">
              <rect x="4" y="2" width="16" height="20" rx="2"/>
              <circle cx="12" cy="17.5" r="0.5" fill="currentColor"/>
            </svg>
          </button>
          <button type="button" class="cbss-fullpv-vp__btn" data-vp="mobile"
                  title="<?php esc_attr_e( 'Mobile', 'jalpi-page-builder' ); ?>">
            <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round">
              <rect x="7" y="2" width="10" height="20" rx="2"/>
              <circle cx="12" cy="17.5" r="0.5" fill="currentColor"/>
            </svg>
          </button>
        </div>

        <!-- Import -->
        <button type="button" class="cbss-fullpv-import-btn" id="cbss-fullpv-import">
          <?php esc_html_e( 'Import Website', 'jalpi-page-builder' ); ?>
        </button>

      </div>
    </div><!-- .cbss-fullpv-bar -->

    <!-- ── iframe area ──────────────────────────────────────────────────── -->
    <div class="cbss-fullpv-stage" id="cbss-fullpv-stage">
      <!-- Loading state -->
      <div class="cbss-fullpv-loader" id="cbss-fullpv-loader">
        <div class="cbss-fullpv-spinner"></div>
        <p class="cbss-fullpv-loader__text"><?php esc_html_e( 'Loading preview…', 'jalpi-page-builder' ); ?></p>
      </div>
      <!-- iframe -->
      <div class="cbss-fullpv-frame-shell" id="cbss-fullpv-frame-shell">
        <iframe id="cbss-fullpv-iframe"
                class="cbss-fullpv-iframe"
                src="about:blank"
                title="<?php esc_attr_e( 'Site Preview', 'jalpi-page-builder' ); ?>"
                sandbox="allow-same-origin allow-scripts allow-popups allow-forms"></iframe>
      </div>
    </div>

  </div><!-- .cbss-fullpv-wrap -->
</div><!-- #cbss-fullpv-overlay -->
