<?php
// components/CampaignFlow/BranchViz.php
namespace Components\CampaignFlow;

use Components\Base;

/**
 * Render a branching block consisting of two horizontal lanes (top/bottom)
 * starting from a single trunk. The trunk is drawn with rounded elbows that
 * connect into each lane. Each lane receives its own FlowViz items array.
 *
 * Input shape (example):
 *   [
 *     'type' => 'branch',
 *     'top' => FlowItems,     // array from FlowBuilder::toArray()
 *     'bottom' => FlowItems,  // array from FlowBuilder::toArray()
 *     'gap' => 'md',          // optional spacing between lanes: sm|md|lg
 *   ]
 *
 * Notes:
 * - Orientation currently supports only horizontal parent flows.
 * - We intentionally use SVG for the elbows to ensure smooth, rounded 90°
 *   corners regardless of CSS rounding support ("rounded-bi-lg" etc.).
 */
class BranchViz extends Base
{
    public static function render(array $branch, array $opts = []): string
    {
        $size = $opts['size'] ?? 'md'; // xs|sm|md|lg
        $editable = (bool)($opts['editable'] ?? false);

        $gap = (string)($branch['gap'] ?? 'md');
        if ($gap === 'sm') {
            $gapY = 'gap-y-4';
            $gapFactorY = 4;
        } elseif ($gap === 'lg') {
            $gapY = 'gap-y-12';
            $gapFactorY = 12;
        } else {
            $gapY = 'gap-y-8';
            $gapFactorY = 8;
        }

        // Lane paddings so elbows have some vertical room to look rounded
        if ($size === 'xs') {
            $lanePadY = 'py-1';
        } elseif ($size === 'sm') {
            $lanePadY = 'py-2';
        } elseif ($size === 'lg') {
            $lanePadY = 'py-4';
        } else {
            $lanePadY = 'py-3';
        }

        // Left column width hosting the trunk + elbows
        if ($size === 'xs') {
            $leftW = 20;
        } elseif ($size === 'sm') {
            $leftW = 28;
        } elseif ($size === 'lg') {
            $leftW = 36;
        } else {
            $leftW = 32;
        }

        // Compose lanes list: prefer 'lanes' (N lanes), fallback to 'top'/'bottom'
        $lanesItems = [];
        if (isset($branch['lanes']) && is_array($branch['lanes'])) {
            foreach ($branch['lanes'] as $li) {
                $lanesItems[] = is_array($li) ? $li : [];
            }
        } else {
            $topItems = is_array($branch['top'] ?? null) ? $branch['top'] : [];
            $bottomItems = is_array($branch['bottom'] ?? null) ? $branch['bottom'] : [];
            if ($topItems !== [] || $bottomItems !== []) {
                $lanesItems = [$topItems, $bottomItems];
            }
        }
        // If still empty, nothing to render
        if (!$lanesItems) {
            return '';
        }

        // Prepare per-lane HTML using FlowViz recursion
        $laneHtmls = [];
        foreach ($lanesItems as $li) {
            $laneHtmls[] = FlowViz::render($li, [
                    'orientation' => 'horizontal',
                    'size' => $size,
                    'editable' => $editable,
                    'addTail' => $opts['addTail'] ?? null,
            ]);
        }

        // CSS-only elbows & trunk using borders
        // Elbow box width per size (px equivalent of Tailwind w-*)
        if ($size === 'xs') {
            $elbowW = 16;   // w-4
            $connectW = 10; // short horizontal connector into lane
            $radiusTL = 'rounded-tl-md';
            $radiusBL = 'rounded-bl-md';
        } elseif ($size === 'sm') {
            $elbowW = 20;   // w-5
            $connectW = 12;
            $radiusTL = 'rounded-tl-lg';
            $radiusBL = 'rounded-bl-lg';
        } elseif ($size === 'lg') {
            $elbowW = 28;   // ~w-7
            $connectW = 18;
            $radiusTL = 'rounded-tl-2xl';
            $radiusBL = 'rounded-bl-2xl';
        } else {
            // md
            $elbowW = 24;   // w-6
            $connectW = 16;
            $radiusTL = 'rounded-tl-xl';
            $radiusBL = 'rounded-bl-xl';
        }

        $laneH = 44;

        $leftCenter = (int)floor($leftW / 2);

        // Build HTML using output buffering (ob_start) to comply with inline HTML guidelines
        $gridCls = 'grid ' . $gapY . ' ' . $lanePadY;
        $gridStyle = 'grid-template-columns: ' . $leftW . 'px 1fr';

        ob_start();
        ?>
        <div class="relative " style="width: 100%">
            <!-- Trunk overlay spanning all rows, aligned to middle of left column -->
<!--
            <div class="pointer-events-none absolute inset-y-0"
                 style="left: <?= (int)$leftCenter ?>px; height: calc(100% -  <?= 2*(int)$laneH ?>px); top: <?= (int)$laneH ?>px;">
                <div class="h-full border-l border-gray-300"></div>
            </div>
-->

            <!-- Intro horizontal line from left edge into the trunk center -->
            <div id="c1" class="pointer-events-none absolute left-0 top-1/2 -translate-y-1/2 h-px bg-flow"
                 style="width: <?= (int)$leftCenter ?>px">
                <div class="absolute size-2 rounded-full bg-flow -right-1 -top-1"></div>
            </div>

            <div class="<?= self::h($gridCls) ?>" style="<?= self::h($gridStyle) ?>">

                <?php $rowCount = count($laneHtmls);
                foreach ($laneHtmls as $i => $laneHtml):
                    $isFirst = ($i === 0);
                    $isAboveCenter = ($i < ($rowCount - 1) / 2);
                    $isCenter = ($i === ($rowCount - 1) / 2);
                    $isLast = ($i === $rowCount - 1);
                    $isBelowCenter = (!$isLast) ? ($i > ($rowCount - 1) / 2) : false;
                    ?>
                    <div class="relative">
                        <?php if ($isFirst || $isAboveCenter): ?>
                                <div class="pointer-events-none absolute <?= self::h($radiusTL) ?> border-t border-l border-flow"
                                     style="left: <?= (int)$leftCenter ?>px; top: calc(50%  - 0.5px); width: <?= (int)$elbowW ?>px; height: <?= (int)$elbowW ?>px"></div>
                        <?php elseif ($isCenter): ?>
                            <div class="border-l border-flow h-full" style="margin-left: <?= (int)$leftCenter ?>px;">
                                <div class="pointer-events-none absolute top-1/2 -translate-y-1/2 h-px bg-flow"
                                     style="left: <?= (int)$leftCenter ?>px; width: <?= (int)$elbowW ?>px"></div>
                            </div>
                        <?php elseif ($isBelowCenter || $isLast): ?>
                            <div class="pointer-events-none absolute <?= self::h($radiusBL) ?> border-b border-l border-flow"
                                 style="left: <?= (int)$leftCenter ?>px; top: calc(50%  + 0.5px - <?= (int)($elbowW) ?>px); width: <?= (int)$elbowW ?>px; height: <?= (int)$elbowW ?>px"></div>
                        <?php endif; ?>
                    </div>
                    <div class="relative flex items-center">
                        <?= $laneHtml ?>
                    <?php if ($isFirst): ?>
                        <div class="border-l border-flow absolute " style="left: -<?= (int)$leftCenter ?>px;height: calc(50% + (var(--spacing) * 0.5 * <?= $gapFactorY ?>)); top: calc(50% + (var(--spacing) * 0.5 * <?= $gapFactorY ?>)); "></div>
                    <?php elseif ($isAboveCenter): ?>
                        <div class="border-l border-flow absolute " style="left: -<?= (int)$leftCenter ?>px;height: calc(100% + (var(--spacing) * 1 * <?= $gapFactorY ?>)); "></div>
                    <?php elseif ($isCenter): ?>
                        <div class="border-l border-flow absolute " style="left: -<?= (int)$leftCenter ?>px;height: calc(100% + (var(--spacing) * 1 * <?= $gapFactorY ?>));; "></div>
                    <?php elseif ($isBelowCenter): ?>

                        <div class="border-l border-flow absolute " style="left: -<?= (int)$leftCenter ?>px;height: calc(100% + (var(--spacing) * 1 * <?= $gapFactorY ?>));; "></div>
                    <?php elseif ($isLast): ?>
                        <div class="border-l border-flow absolute " style="left: -<?= (int)$leftCenter ?>px;height: calc(100% - (var(--spacing) * 0.5 * <?= $gapFactorY ?>)); top: calc(-50%); "></div>
                    <?php endif; ?>
                    </div>
                <?php endforeach; ?>
<!--
                <div class="border-l border-flow  h-full absolute t-0" style="height: calc(100% -  <?= 2*(int)$laneH ?>px); left: <?= (int)$leftCenter ?>px; top: <?= $laneH; ?>px"></div>
-->
            </div>
        </div>
        <?php
        return (string)ob_get_clean();
    }
}
