# Homepage Hero Slide Import Implementation Plan

> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.

**Goal:** Scrape the four live Kaindl homepage hero slides and append them to the existing dev homepage hero block without removing the current test slides.

**Architecture:** A Node scraper writes a reviewable manifest and downloaded image files under `scripts/catalog/image-import`. A Drupal service plus Drush command reads the manifest, creates idempotent `homepage_hero_slide` block content entities, creates file entities for the images, and appends those slides to the existing `homepage_hero` block.

**Tech Stack:** Node.js built-ins and global `fetch`; Drupal 11 custom module services; Drush 13 attribute commands; Drupal `block_content`, `file`, and image/link fields.

---

## File Structure

- Create `scripts/catalog/image-import/scrape_homepage_hero_slides.js`
  - Fetches `https://www.kaindl.com/en/`, extracts slide metadata and image URLs, downloads images, and writes `homepage_hero_slides.en.json` plus a report.
- Create `web/modules/custom/kaindl_content_blocks/kaindl_content_blocks.services.yml`
  - Registers the homepage hero import manager.
- Create `web/modules/custom/kaindl_content_blocks/drush.services.yml`
  - Registers the Drush command class.
- Create `web/modules/custom/kaindl_content_blocks/src/HomepageHeroSlideImportManager.php`
  - Imports manifest slides into Drupal entities and appends references to the existing homepage hero block.
- Create `web/modules/custom/kaindl_content_blocks/src/Drush/Commands/KaindlContentBlocksCommands.php`
  - Provides `kaindl-content-blocks:import-homepage-hero-slides`.
- Modify `web/modules/custom/kaindl_content_blocks/README.md`
  - Documents the scrape/import workflow.

## Task 1: Scrape Live Homepage Hero Slides

**Files:**
- Create: `scripts/catalog/image-import/scrape_homepage_hero_slides.js`

- [ ] **Step 1: Create the scraper script**

Implement a Node script with these constants and responsibilities:

```javascript
#!/usr/bin/env node

'use strict';

const fs = require('fs');
const path = require('path');

const SITE_BASE = 'https://www.kaindl.com';
const SOURCE_URL = `${SITE_BASE}/en/`;
const SCRIPT_DIR = __dirname;
const OUTPUT_ROOT = path.join(SCRIPT_DIR, 'homepage-hero');
const MANIFEST_PATH = path.join(SCRIPT_DIR, 'homepage_hero_slides.en.json');
const REPORT_PATH = path.join(SCRIPT_DIR, 'homepage_hero_slides_report.json');
```

The script must:

- Fetch `SOURCE_URL`.
- Extract `.caption-slider__slide[data-index]` entries for title, description, CTA title, and CTA URL.
- Extract first unique `.slice-slider__slice[data-index]` entries for desktop image (`.slice-slider__img-landscape`) and mobile image (`.slice-slider__img-portrait`).
- Prefer `data-src` over `src` to avoid lazy placeholder GIFs.
- Normalize relative URLs with `new URL(value, SITE_BASE).toString()`.
- Download each slide image to:
  - `scripts/catalog/image-import/homepage-hero/slide-<index>-desktop.<ext>`
  - `scripts/catalog/image-import/homepage-hero/slide-<index>-mobile.<ext>`
- Write `homepage_hero_slides.en.json` in this shape:

```json
{
  "source_url": "https://www.kaindl.com/en/",
  "generated_at": "2026-05-15T00:00:00.000Z",
  "slides": [
    {
      "source_index": 0,
      "source_key": "floors-2025",
      "title": "FLOORS 2025",
      "description": "The new floors impress with sophisticated ideas...",
      "cta": {
        "title": "Find out more",
        "url": "https://www.kaindl.com/en/flooring-collection-2025/"
      },
      "desktop_image": {
        "source_url": "https://www.kaindl.com/fileadmin/...",
        "path": "homepage-hero/slide-1-desktop.png",
        "alt": "FLOORS 2025"
      },
      "mobile_image": {
        "source_url": "https://www.kaindl.com/fileadmin/...",
        "path": "homepage-hero/slide-1-mobile.png",
        "alt": "FLOORS 2025"
      }
    }
  ]
}
```

The script must fail with a non-zero exit if:

- no caption slides are found,
- no image slices are found,
- a slide has no title,
- a slide has no desktop image.

- [ ] **Step 2: Run the scraper**

Run:

```bash
node scripts/catalog/image-import/scrape_homepage_hero_slides.js
```

Expected:

- `scripts/catalog/image-import/homepage_hero_slides.en.json` exists.
- `scripts/catalog/image-import/homepage_hero_slides_report.json` exists.
- `scripts/catalog/image-import/homepage-hero/` contains 8 images if all four desktop and mobile images are present.
- Console output reports 4 scraped slides.

- [ ] **Step 3: Inspect manifest summary**

Run a Node summary command that prints only slide essentials:

```bash
node -e "const m=require('./scripts/catalog/image-import/homepage_hero_slides.en.json'); console.log(m.slides.map(s => ({title:s.title, cta:s.cta, desktop:s.desktop_image.path, mobile:s.mobile_image.path})))"
```

Expected titles:

- `FLOORS 2025`
- `BOARDS 2025`
- `IDEAS`
- `EVENTS`

## Task 2: Add Drupal Import Manager

**Files:**
- Create: `web/modules/custom/kaindl_content_blocks/src/HomepageHeroSlideImportManager.php`
- Create: `web/modules/custom/kaindl_content_blocks/kaindl_content_blocks.services.yml`

- [ ] **Step 1: Create service registration**

Create `kaindl_content_blocks.services.yml`:

```yaml
services:
  kaindl_content_blocks.homepage_hero_slide_import_manager:
    class: Drupal\kaindl_content_blocks\HomepageHeroSlideImportManager
    arguments:
      - '@entity_type.manager'
      - '@file_system'
      - '@file.repository'
      - '@extension.list.module'
```

- [ ] **Step 2: Create import manager class**

Create `HomepageHeroSlideImportManager.php` with these dependencies and public method:

```php
<?php

declare(strict_types=1);

namespace Drupal\kaindl_content_blocks;

use Drupal\block_content\BlockContentInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Extension\ModuleExtensionList;
use Drupal\Core\File\FileExists;
use Drupal\Core\File\FileSystemInterface;
use Drupal\file\FileInterface;
use Drupal\file\FileRepositoryInterface;

final class HomepageHeroSlideImportManager
{
  public function __construct(
    private readonly EntityTypeManagerInterface $entityTypeManager,
    private readonly FileSystemInterface $fileSystem,
    private readonly FileRepositoryInterface $fileRepository,
    private readonly ModuleExtensionList $moduleExtensionList,
  ) {}

  public function import(?string $manifestPath = NULL, ?string $imagesDir = NULL): array
  {
    // Implementation in later steps.
  }
}
```

The implementation must include private helpers:

- `defaultManifestPath(): string`
- `defaultImagesDir(): string`
- `loadManifest(string $manifestPath): array`
- `loadHomepageHeroBlock(): BlockContentInterface`
- `findExistingImportedSlide(string $sourceKey, string $title): ?BlockContentInterface`
- `createSlide(array $slide, string $imagesDir): BlockContentInterface`
- `createImageFile(array $image, string $imagesDir): FileInterface`
- `appendSlides(BlockContentInterface $hero, array $slides): int`
- `projectRoot(): string`

- [ ] **Step 3: Implement manifest path defaults**

`defaultManifestPath()` should resolve from the module path back to the repo root:

```php
$modulePath = $this->moduleExtensionList->getPath('kaindl_content_blocks');
$root = dirname($modulePath, 4);
return $root . '/scripts/catalog/image-import/homepage_hero_slides.en.json';
```

`defaultImagesDir()` should return:

```php
return $root . '/scripts/catalog/image-import';
```

- [ ] **Step 4: Implement homepage hero lookup**

`loadHomepageHeroBlock()` must load all `block_content` entities with bundle `homepage_hero`.

Expected behavior:

- 0 blocks: throw `RuntimeException('No homepage_hero block was found.')`
- more than 1 block: throw `RuntimeException('Multiple homepage_hero blocks were found; pass a single target implementation before importing.')`
- exactly 1 block: return it

- [ ] **Step 5: Implement idempotent slide detection**

Imported slide labels must be:

```php
$label = 'Homepage Hero: ' . $slide['title'];
```

`findExistingImportedSlide()` must query `block_content` where:

- `type = homepage_hero_slide`
- `info = $label`

If found, load and return that block. Otherwise return `NULL`.

- [ ] **Step 6: Implement file import**

`createImageFile()` must:

- validate the manifest image path is relative,
- resolve it under `$imagesDir`,
- fail if the local file does not exist,
- copy file bytes into `public://homepage-hero-import/<basename>`,
- create or replace a file entity through `FileRepositoryInterface::writeData()`,
- mark the file permanent.

Use `FileExists::Replace`.

- [ ] **Step 7: Implement slide creation**

`createSlide()` must create `block_content` with:

```php
[
  'type' => 'homepage_hero_slide',
  'info' => 'Homepage Hero: ' . $slide['title'],
  'field_slide_meta_label' => $slide['title'],
  'field_slide_description' => $slide['description'] ?? '',
  'field_slide_cta' => [
    'uri' => $slide['cta']['url'] ?? '',
    'title' => $slide['cta']['title'] ?? '',
  ],
  'field_slide_desktop_image' => [
    'target_id' => $desktopFile->id(),
    'alt' => $slide['desktop_image']['alt'] ?: $slide['title'],
  ],
  'field_slide_mobile_image' => [
    'target_id' => $mobileFile->id(),
    'alt' => $slide['mobile_image']['alt'] ?: $slide['title'],
  ],
]
```

If mobile image data is missing, leave `field_slide_mobile_image` empty.

- [ ] **Step 8: Implement append behavior**

`appendSlides()` must preserve existing `field_hero_slides` items and append imported slide target IDs only if not already referenced.

Return the number of newly appended references.

- [ ] **Step 9: Implement result payload**

`import()` must return:

```php
[
  'manifest' => $manifestPath,
  'images_dir' => $imagesDir,
  'hero_block_id' => '61',
  'slides_seen' => 4,
  'slides_created' => 4,
  'slides_reused' => 0,
  'references_appended' => 4,
  'slides' => [
    ['title' => 'FLOORS 2025', 'id' => '123', 'created' => TRUE, 'appended' => TRUE],
  ],
]
```

## Task 3: Add Drush Command

**Files:**
- Create: `web/modules/custom/kaindl_content_blocks/drush.services.yml`
- Create: `web/modules/custom/kaindl_content_blocks/src/Drush/Commands/KaindlContentBlocksCommands.php`

- [ ] **Step 1: Register Drush command service**

Create `drush.services.yml`:

```yaml
services:
  kaindl_content_blocks.commands:
    class: Drupal\kaindl_content_blocks\Drush\Commands\KaindlContentBlocksCommands
    arguments:
      - '@kaindl_content_blocks.homepage_hero_slide_import_manager'
    tags:
      - { name: drush.command }
```

- [ ] **Step 2: Create command class**

Create the command class:

```php
<?php

declare(strict_types=1);

namespace Drupal\kaindl_content_blocks\Drush\Commands;

use Drupal\kaindl_content_blocks\HomepageHeroSlideImportManager;
use Drush\Attributes as CLI;
use Drush\Commands\DrushCommands;

final class KaindlContentBlocksCommands extends DrushCommands
{
  public function __construct(
    private readonly HomepageHeroSlideImportManager $importManager,
  ) {
    parent::__construct();
  }

  #[CLI\Command(name: 'kaindl-content-blocks:import-homepage-hero-slides', aliases: ['kcb-import-hero-slides'])]
  #[CLI\Option(name: 'manifest', description: 'Path to homepage_hero_slides.en.json. Defaults to scripts/catalog/image-import/homepage_hero_slides.en.json.')]
  #[CLI\Option(name: 'images-dir', description: 'Path to image import root. Defaults to scripts/catalog/image-import.')]
  public function importHomepageHeroSlides(array $options = ['manifest' => NULL, 'images-dir' => NULL]): void
  {
    $this->output()->writeln((string) json_encode(
      $this->importManager->import($options['manifest'], $options['images-dir']),
      JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE,
    ));
  }
}
```

## Task 4: Document Workflow

**Files:**
- Modify: `web/modules/custom/kaindl_content_blocks/README.md`

- [ ] **Step 1: Add import instructions**

Append a section:

```markdown
## Homepage hero slide import

Scrape the current live homepage hero slides and download their images:

```bash
node scripts/catalog/image-import/scrape_homepage_hero_slides.js
```

Review `scripts/catalog/image-import/homepage_hero_slides.en.json`, then import into Drupal:

```bash
vendor/bin/drush -l http://127.0.0.1:8888 kaindl-content-blocks:import-homepage-hero-slides
vendor/bin/drush -l http://127.0.0.1:8888 cr
```

The importer appends imported slides to the existing homepage hero block and skips duplicates on rerun.
```

## Task 5: Run Import and Verify

**Files:**
- Generated: `scripts/catalog/image-import/homepage_hero_slides.en.json`
- Generated: `scripts/catalog/image-import/homepage_hero_slides_report.json`
- Generated: `scripts/catalog/image-import/homepage-hero/*`

- [ ] **Step 1: Run syntax checks**

Run:

```bash
node --check scripts/catalog/image-import/scrape_homepage_hero_slides.js
php -l web/modules/custom/kaindl_content_blocks/src/HomepageHeroSlideImportManager.php
php -l web/modules/custom/kaindl_content_blocks/src/Drush/Commands/KaindlContentBlocksCommands.php
```

Expected: all commands pass.

- [ ] **Step 2: Run scraper**

Run:

```bash
node scripts/catalog/image-import/scrape_homepage_hero_slides.js
```

Expected: manifest contains 4 slides and image downloads exist.

- [ ] **Step 3: Rebuild cache for new Drush command**

Run outside sandbox if CLI cannot reach DB:

```bash
vendor/bin/drush -l http://127.0.0.1:8888 cr
```

- [ ] **Step 4: Run importer**

Run outside sandbox if CLI cannot reach DB:

```bash
vendor/bin/drush -l http://127.0.0.1:8888 kaindl-content-blocks:import-homepage-hero-slides
```

Expected first run:

- `slides_seen = 4`
- `slides_created = 4`
- `references_appended = 4`

- [ ] **Step 5: Verify idempotency**

Run importer a second time:

```bash
vendor/bin/drush -l http://127.0.0.1:8888 kaindl-content-blocks:import-homepage-hero-slides
```

Expected second run:

- `slides_seen = 4`
- `slides_created = 0`
- `slides_reused = 4`
- `references_appended = 0`

- [ ] **Step 6: Verify homepage hero references**

Run:

```bash
vendor/bin/drush -l http://127.0.0.1:8888 ev '$blocks = \Drupal::entityTypeManager()->getStorage("block_content")->loadByProperties(["type" => "homepage_hero"]); $hero = reset($blocks); echo count($hero->get("field_hero_slides")) . PHP_EOL; foreach ($hero->get("field_hero_slides")->referencedEntities() as $slide) { echo $slide->label() . " | " . $slide->get("field_slide_meta_label")->value . PHP_EOL; }'
```

Expected: existing test slide labels remain first, followed by `Homepage Hero: FLOORS 2025`, `Homepage Hero: BOARDS 2025`, `Homepage Hero: IDEAS`, and `Homepage Hero: EVENTS`.

- [ ] **Step 7: Browser verify**

Open `http://127.0.0.1:8888/en` and verify:

- imported slides appear after the two current test slides,
- imported slide titles appear in the black navigation when cycling,
- title click opens the description and CTA,
- CTA links navigate to the imported live paths,
- desktop image renders at desktop viewport,
- mobile image renders at mobile viewport.

## Task 6: Review and Commit

**Files:**
- All files from previous tasks.

- [ ] **Step 1: Run final checks**

Run:

```bash
git diff --check
git status --short
```

Expected: no whitespace errors; changed files are only the planned code/docs/generated import assets.

- [ ] **Step 2: Request code review**

Dispatch a reviewer agent with:

- feature summary,
- changed file list,
- commands run,
- import output summary,
- browser verification notes.

Fix Critical and Important findings before final response.

- [ ] **Step 3: Commit implementation**

Commit code and manifest/downloaded assets after verification:

```bash
git add scripts/catalog/image-import/scrape_homepage_hero_slides.js scripts/catalog/image-import/homepage_hero_slides.en.json scripts/catalog/image-import/homepage_hero_slides_report.json scripts/catalog/image-import/homepage-hero web/modules/custom/kaindl_content_blocks
git commit -m "feat: import homepage hero slides"
```
