<?php
declare(strict_types=1);
// ==================================================
// Nuclear Fancy Pants Edition™ — NUCLEAR+++
// File: /templates/social/linkedin-picker.php
// Description: LinkedIn Organization Page picker - NUCLEAR+++
// Last Edited: 2026-04-14
// ==================================================

namespace AutoMarketerAI;

// No direct access
defined('ABSPATH') || exit;

// $pending_orgs passed from LinkedInChannel::render()
$orgs = $pending_orgs['orgs'] ?? [];

// Sign the full pending payload so we can pass it through the form
// without relying on DB persistence between requests.
$pending_payload = '';
$pending_sig     = '';
if (!empty($pending_orgs)) {
    $pending_payload = base64_encode((string) json_encode($pending_orgs, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
    $pending_sig     = LinkedInAuth::signPending($pending_payload);
}
?>
<div class="amai-fb-picker-area">

    <div class="amai-fb-picker-shell">

        <div class="amai-fb-picker-header">
            <h2 class="amai-fb-picker-heading">Which page should we post to?</h2>
            <p class="amai-fb-picker-sub">
                These are the LinkedIn Pages you admin.
                Pick the one you want AutoMarketer AI to handle.
            </p>
        </div>

        <?php if (empty($orgs)) : ?>
        <div class="amai-fb-picker-body">
            <div class="amai-fb-notice amai-fb-notice-warn">
                <div class="amai-fb-notice-body">
                    We couldn't find any LinkedIn Pages on your account. Make sure you're an admin on a LinkedIn Page, then try connecting again.
                    <a href="https://www.linkedin.com/company/setup/new/" target="_blank" rel="noopener noreferrer" class="amai-fb-notice-link">Create a LinkedIn Page →</a>
                </div>
            </div>
        </div>
        <div class="amai-fb-picker-footer">
            <a href="<?php echo esc_url(admin_url('admin.php?page=automarketer-ai-social&channel=linkedin')); ?>" class="amai-fb-back-link">← Start over</a>
        </div>
        <?php else : ?>

        <form method="post"
              action="<?php echo esc_url(admin_url('admin.php?page=automarketer-ai-social&channel=linkedin')); ?>"
              id="amai-li-picker-form">
            <?php wp_nonce_field('amai_li_select_org'); ?>
            <input type="hidden" name="amai_li_action"      value="select_org"/>
            <input type="hidden" name="organization_urn"    id="amai-selected-org-urn" value=""/>
            <input type="hidden" name="pending_payload"     value="<?php echo esc_attr($pending_payload); ?>"/>
            <input type="hidden" name="pending_sig"         value="<?php echo esc_attr($pending_sig); ?>"/>

            <div class="amai-fb-pages-list">
                <?php foreach ($orgs as $org) :
                    $org_urn      = esc_attr((string) ($org['organization_urn']  ?? ''));
                    $org_name     = esc_html((string) ($org['organization_name'] ?? ''));
                    $org_pic      = esc_url((string)  ($org['picture_url']       ?? ''));
                    $org_follows  = (int) ($org['followers'] ?? 0);
                    $follows_fmt  = number_format($org_follows);
                    $follows_label = $org_follows === 1 ? 'follower' : 'followers';
                    $initials     = strtoupper(substr((string) ($org['organization_name'] ?? 'L'), 0, 2));
                ?>
                <div class="amai-fb-page-card"
                     data-org-urn="<?php echo $org_urn; ?>"
                     role="button"
                     tabindex="0">
                    <div class="amai-fb-page-avatar">
                        <?php if ($org_pic !== '') : ?>
                            <img src="<?php echo $org_pic; ?>"
                                 alt="<?php echo $org_name; ?>"
                                 width="48"
                                 height="48"/>
                        <?php else : ?>
                            <div class="amai-fb-page-initials" style="background:#0A66C2;"><?php echo esc_html($initials); ?></div>
                        <?php endif; ?>
                    </div>
                    <div class="amai-fb-page-info">
                        <div class="amai-fb-page-name"><?php echo $org_name; ?></div>
                        <div class="amai-fb-page-meta">
                            <span><?php echo esc_html($follows_fmt . ' ' . $follows_label); ?></span>
                        </div>
                    </div>
                    <div class="amai-fb-page-check">
                        <div class="amai-fb-page-radio"></div>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>

            <div class="amai-fb-picker-footer">
                <a href="<?php echo esc_url(admin_url('admin.php?page=automarketer-ai-social&channel=linkedin')); ?>"
                   class="amai-fb-back-link">← Use a different account</a>
                <button type="submit"
                        class="amai-fb-select-btn"
                        id="amai-li-select-btn"
                        disabled>
                    Connect this page →
                </button>
            </div>
        </form>

        <?php endif; ?>

    </div>
</div>

<script>
(function () {
    var cards   = document.querySelectorAll('.amai-fb-page-card[data-org-urn]');
    var urnInput = document.getElementById('amai-selected-org-urn');
    var btn     = document.getElementById('amai-li-select-btn');

    if (!cards.length || !urnInput || !btn) { return; }

    // Auto-select when only one org
    if (cards.length === 1) {
        selectCard(cards[0]);
    }

    cards.forEach(function (card) {
        card.addEventListener('click', function () { selectCard(card); });
        card.addEventListener('keydown', function (e) {
            if (e.key === 'Enter' || e.key === ' ') {
                e.preventDefault();
                selectCard(card);
            }
        });
    });

    function selectCard(card) {
        cards.forEach(function (c) { c.classList.remove('is-selected'); });
        card.classList.add('is-selected');
        urnInput.value = card.getAttribute('data-org-urn') || '';
        btn.disabled   = false;
    }
}());
</script>