<?php
$d = $dependencyData ?? [];
$packages = (array) ($d['packages'] ?? []);
$selected = is_array($d['selected'] ?? null) ? $d['selected'] : null;
$metrics = (array) ($d['metrics'] ?? []);
$graph = (array) ($d['graph'] ?? []);
$cycles = (array) ($d['cycles'] ?? []);

$h = static fn($value): string =>
    htmlspecialchars((string) $value, ENT_QUOTES, 'UTF-8');

$badge = static fn(string $decision): string => match ($decision) {
    'RESOLVED' => 'ok',
    'WARNING' => 'warn',
    'INCOMPATIBLE' => 'bad',
    default => 'info',
};
?>
<style>
.dep{display:grid;gap:18px}.dep *{box-sizing:border-box}
.dep-hero{border-radius:24px;padding:26px;background:linear-gradient(135deg,#10223c,#1c4f79 58%,#2671a8);color:#fff;display:flex;justify-content:space-between;gap:20px;align-items:center;box-shadow:0 18px 44px rgba(15,43,70,.18)}
.dep-hero h1{margin:5px 0 8px;font-size:clamp(28px,4vw,42px)}.dep-hero p{margin:0;color:#dbeafe}
.dep-actions{display:flex;gap:9px;flex-wrap:wrap}.dep-btn{border:1px solid #cbd8e6;border-radius:11px;background:#fff;color:#1c4e77;padding:10px 14px;font-weight:800;text-decoration:none;cursor:pointer;display:inline-flex}
.dep-btn.primary{background:#1f67a2;border-color:#1f67a2;color:#fff}.dep-btn.ghost{background:rgba(255,255,255,.1);border-color:rgba(255,255,255,.35);color:#fff}
.dep-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(160px,1fr));gap:12px}
.dep-card{background:#fff;border:1px solid #dbe5ef;border-radius:18px;padding:18px;box-shadow:0 8px 26px rgba(23,50,77,.055)}
.dep-kpi small{color:#64748b}.dep-kpi strong{display:block;font-size:30px;color:#173b5a;margin-top:4px}
.dep-layout{display:grid;grid-template-columns:minmax(300px,.75fr) minmax(0,1.25fr);gap:14px}
.dep-list{display:grid;gap:9px;max-height:760px;overflow:auto}.dep-package{display:flex;justify-content:space-between;gap:12px;align-items:center;padding:12px;border:1px solid #e1e9f1;border-radius:13px;text-decoration:none;color:#173b5a}
.dep-package.active{border-color:#2d76ad;background:#eef7fe}.dep-package small{display:block;color:#64748b}
.dep-badge{display:inline-flex;padding:5px 8px;border-radius:999px;font-size:11px;font-weight:900}.dep-badge.ok{background:#dcfce7;color:#166534}.dep-badge.warn{background:#fef3c7;color:#92400e}.dep-badge.bad{background:#fee2e2;color:#991b1b}.dep-badge.info{background:#e0f2fe;color:#075985}
.dep-table-wrap{overflow:auto}.dep-table{width:100%;border-collapse:collapse;min-width:680px}.dep-table th,.dep-table td{padding:10px;border-bottom:1px solid #e6edf4;text-align:left}.dep-table th{font-size:11px;text-transform:uppercase;color:#64748b}
.dep-plan{display:grid;gap:8px;counter-reset:step}.dep-step{display:flex;gap:11px;align-items:center;padding:11px;background:#f7f9fc;border-radius:12px}.dep-step:before{counter-increment:step;content:counter(step);width:28px;height:28px;border-radius:50%;background:#1f67a2;color:#fff;display:grid;place-items:center;font-weight:900}
.dep-empty{text-align:center;color:#64748b;padding:32px}
.dep-graph-toolbar{display:flex;gap:9px;align-items:center;flex-wrap:wrap;margin-bottom:12px}.dep-filter{border:1px solid #cbd8e6;background:#fff;border-radius:999px;padding:8px 11px;font-weight:800;color:#345}.dep-filter.active{background:#1f67a2;color:#fff;border-color:#1f67a2}
.dep-canvas-wrap{border:1px solid #dbe5ef;border-radius:16px;background:linear-gradient(#f8fbfe,#fff);overflow:auto;min-height:560px}
.dep-canvas{width:100%;min-width:980px;height:620px;display:block}
.dep-legend{display:flex;gap:14px;flex-wrap:wrap;margin-top:12px;color:#475569;font-size:13px}.dep-dot{width:11px;height:11px;border-radius:50%;display:inline-block;margin-right:5px}.dep-dot.required{background:#2563eb}.dep-dot.optional{background:#d97706}.dep-dot.conflict{background:#dc2626}
.dep-cycle{border:1px solid #fecaca;background:#fff1f2;color:#9f1239;border-radius:12px;padding:11px;margin-top:8px}
.dep-impact{display:grid;gap:8px}.dep-impact-item{padding:10px 12px;border-left:4px solid #8b5cf6;background:#f8f5ff;border-radius:8px}
@media(max-width:900px){.dep-hero{align-items:flex-start;flex-direction:column}.dep-layout{grid-template-columns:1fr}}
</style>

<div class="dep">
<section class="dep-hero">
    <div>
        <small>PLATFORM-023.5.4 · AXIOM 10.2.6.3</small>
        <h1>Dependency Graph PRO</h1>
        <p>Graphe interactif, conflits de versions, cycles, impact et ordre d’installation.</p>
    </div>
    <div class="dep-actions">
        <a class="dep-btn ghost" href="/public/studio/mises-a-jour">Centre de mises à jour</a>
        <a class="dep-btn ghost" href="/public/administration/plateforme/validation">Validation Center</a>
        <a class="dep-btn ghost" href="/public/administration/plateforme/packages">Package Manager</a>
    </div>
</section>

<div class="dep-grid">
<?php foreach ([
    'packages' => 'Packages',
    'relations' => 'Relations',
    'resolved' => 'Résolus',
    'warnings' => 'Vigilances',
    'incompatible' => 'Incompatibles',
    'cycles' => 'Cycles',
] as $key => $label): ?>
    <article class="dep-card dep-kpi">
        <small><?= $h($label) ?></small>
        <strong><?= (int) ($metrics[$key] ?? 0) ?></strong>
    </article>
<?php endforeach; ?>
</div>

<section class="dep-card">
    <div style="display:flex;justify-content:space-between;gap:12px;align-items:flex-start;flex-wrap:wrap">
        <div>
            <h2 style="margin:0">Graphe des dépendances</h2>
            <p style="margin:5px 0 0;color:#64748b">Cliquez sur un nœud pour ouvrir sa fiche. Utilisez les filtres pour isoler les relations.</p>
        </div>
        <div class="dep-graph-toolbar">
            <button class="dep-filter active" type="button" data-edge-filter="ALL">Toutes</button>
            <button class="dep-filter" type="button" data-edge-filter="REQUIRED">Obligatoires</button>
            <button class="dep-filter" type="button" data-edge-filter="OPTIONAL">Optionnelles</button>
            <button class="dep-filter" type="button" data-edge-filter="CONFLICT">Conflits</button>
            <button class="dep-filter" type="button" data-graph-reset>Réinitialiser</button>
        </div>
    </div>

    <div class="dep-canvas-wrap">
        <svg
            class="dep-canvas"
            id="dependency-graph-pro"
            viewBox="0 0 1200 620"
            role="img"
            aria-label="Graphe interactif des dépendances de packages"
            data-selected-key="<?= $h($selected['package_key'] ?? '') ?>"
        ></svg>
    </div>

    <div class="dep-legend">
        <span><i class="dep-dot required"></i>Dépendance obligatoire</span>
        <span><i class="dep-dot optional"></i>Dépendance optionnelle</span>
        <span><i class="dep-dot conflict"></i>Conflit</span>
    </div>
</section>

<?php if ($cycles !== []): ?>
<section class="dep-card">
    <h2>Cycles détectés</h2>
    <?php foreach ($cycles as $cycle): ?>
        <div class="dep-cycle"><?= $h(implode(' → ', $cycle)) ?></div>
    <?php endforeach; ?>
</section>
<?php endif; ?>

<section class="dep-layout">
<aside class="dep-card">
    <h2>Registre des packages</h2>
    <div class="dep-list">
    <?php foreach ($packages as $package): ?>
        <?php $decision = (string) ($package['dependency_decision'] ?? 'NON_ANALYSE'); ?>
        <a
            class="dep-package <?= $selected && (int) $selected['id'] === (int) $package['id'] ? 'active' : '' ?>"
            href="?package_id=<?= (int) $package['id'] ?>"
        >
            <div>
                <strong><?= $h($package['package_name']) ?></strong>
                <small>
                    <?= $h($package['version']) ?>
                    · <?= (int) $package['required_dependencies'] ?> obligatoire(s)
                    · <?= (int) $package['optional_dependencies'] ?> optionnelle(s)
                </small>
            </div>
            <span class="dep-badge <?= $badge($decision) ?>"><?= $h($decision) ?></span>
        </a>
    <?php endforeach; ?>

    <?php if ($packages === []): ?>
        <div class="dep-empty">Aucun package dans le registre.</div>
    <?php endif; ?>
    </div>
</aside>

<main class="dep-card">
<?php if ($selected): ?>
    <div style="display:flex;justify-content:space-between;gap:12px;align-items:flex-start;flex-wrap:wrap">
        <div>
            <span class="dep-badge info"><?= $h($selected['category']) ?></span>
            <h2 style="margin:8px 0 3px"><?= $h($selected['package_name']) ?></h2>
            <small><?= $h($selected['package_key']) ?> · <?= $h($selected['version']) ?></small>
        </div>
        <form method="post" action="/public/administration/plateforme/packages/dependances/analyser">
            <?= \App\Core\Csrf::field() ?>
            <input type="hidden" name="package_id" value="<?= (int) $selected['id'] ?>">
            <button class="dep-btn primary">Analyser maintenant</button>
        </form>
    </div>

    <?php $analysis = $selected['latest_analysis'] ?? null; ?>
    <?php if (is_array($analysis)): ?>
    <div class="dep-grid" style="margin-top:15px">
        <article class="dep-card dep-kpi">
            <small>Score</small>
            <strong><?= (int) $analysis['score'] ?>/100</strong>
        </article>
        <article class="dep-card dep-kpi">
            <small>Décision</small>
            <strong style="font-size:20px">
                <span class="dep-badge <?= $badge((string) $analysis['decision']) ?>">
                    <?= $h($analysis['decision']) ?>
                </span>
            </strong>
        </article>
        <article class="dep-card dep-kpi">
            <small>Résolues</small>
            <strong><?= (int) $analysis['resolved_count'] ?>/<?= (int) $analysis['required_count'] ?></strong>
        </article>
        <article class="dep-card dep-kpi">
            <small>Impact indirect</small>
            <strong><?= count((array) ($selected['impact_chain'] ?? [])) ?></strong>
        </article>
    </div>
    <?php endif; ?>

    <h3>Dépendances déclarées</h3>
    <div class="dep-table-wrap">
    <table class="dep-table">
        <thead>
            <tr><th>Type</th><th>Package</th><th>Version min.</th><th>Version max.</th><th>Source</th></tr>
        </thead>
        <tbody>
        <?php foreach ((array) $selected['dependencies'] as $dependency): ?>
            <tr>
                <td>
                    <span class="dep-badge <?= $dependency['dependency_type'] === 'CONFLICT' ? 'bad' : ($dependency['dependency_type'] === 'OPTIONAL' ? 'warn' : 'info') ?>">
                        <?= $h($dependency['dependency_type']) ?>
                    </span>
                </td>
                <td><strong><?= $h($dependency['dependency_key']) ?></strong></td>
                <td><?= $h($dependency['min_version'] ?? '—') ?></td>
                <td><?= $h($dependency['max_version'] ?? '—') ?></td>
                <td><?= $h($dependency['source']) ?></td>
            </tr>
        <?php endforeach; ?>
        <?php if (empty($selected['dependencies'])): ?>
            <tr><td colspan="5">Aucune dépendance déclarée dans le manifeste disponible.</td></tr>
        <?php endif; ?>
        </tbody>
    </table>
    </div>

    <h3>Plan d’installation calculé</h3>
    <div class="dep-plan">
    <?php foreach ((array) ($selected['plan']['steps'] ?? []) as $step): ?>
        <div class="dep-step">
            <div>
                <strong><?= $h($step['package_name']) ?></strong><br>
                <small><?= $h($step['version']) ?> · <?= $h($step['status']) ?></small>
            </div>
        </div>
    <?php endforeach; ?>
    <?php if (empty($selected['plan']['steps'])): ?>
        <div class="dep-empty">Aucun plan disponible.</div>
    <?php endif; ?>
    </div>

    <?php if (!empty($selected['plan']['issues'])): ?>
        <?php foreach ((array) $selected['plan']['issues'] as $issue): ?>
            <div class="dep-cycle"><?= $h($issue) ?></div>
        <?php endforeach; ?>
    <?php endif; ?>

    <h3>Chaîne d’impact</h3>
    <div class="dep-impact">
    <?php foreach ((array) ($selected['impact_chain'] ?? []) as $impact): ?>
        <div class="dep-impact-item" style="margin-left:<?= min(5, (int) $impact['depth']) * 18 ?>px">
            <strong><?= $h($impact['package_name']) ?></strong>
            <small>
                · profondeur <?= (int) $impact['depth'] ?>
                · <?= $h($impact['dependency_type']) ?>
                · <?= $h($impact['status']) ?>
            </small>
        </div>
    <?php endforeach; ?>
    <?php if (empty($selected['impact_chain'])): ?>
        <div class="dep-empty">Aucun package dépendant direct ou indirect.</div>
    <?php endif; ?>
    </div>

    <h3>Packages dépendants directs</h3>
    <div class="dep-table-wrap">
    <table class="dep-table">
        <thead><tr><th>Package</th><th>Version</th><th>Type</th><th>État</th></tr></thead>
        <tbody>
        <?php foreach ((array) $selected['dependents'] as $dependent): ?>
            <tr>
                <td><?= $h($dependent['package_name']) ?></td>
                <td><?= $h($dependent['version']) ?></td>
                <td><?= $h($dependent['dependency_type']) ?></td>
                <td><?= $h($dependent['package_status']) ?></td>
            </tr>
        <?php endforeach; ?>
        <?php if (empty($selected['dependents'])): ?>
            <tr><td colspan="4">Aucun package dépendant.</td></tr>
        <?php endif; ?>
        </tbody>
    </table>
    </div>
<?php else: ?>
    <div class="dep-empty">
        <h2>Sélectionnez un package</h2>
        <p>La fiche affichera les dépendances, conflits, impacts et l’ordre d’installation proposé.</p>
    </div>
<?php endif; ?>
</main>
</section>

<section class="dep-card">
    <small>Analyse générée le <?= $h($d['generated_at'] ?? '') ?></small>
</section>
</div>

<script>
window.AXIOM_DEPENDENCY_GRAPH = <?= json_encode(
    $graph,
    JSON_UNESCAPED_UNICODE
    | JSON_UNESCAPED_SLASHES
    | JSON_HEX_TAG
    | JSON_HEX_AMP
    | JSON_HEX_APOS
    | JSON_HEX_QUOT
) ?>;
</script>
<script src="/public/assets/js/axiom-dependency-graph-pro-10263.js" defer></script>
