<?php
use App\Core\{Auth, Csrf};
use function App\Core\{e, url};

$profile = $profile ?? null;
$viewer = Auth::user();
$viewerId = Auth::id();
$stats = $stats ?? [];
$relationship = $relationship ?? ['state' => 'guest', 'friendship' => null];
$state = (string) ($relationship['state'] ?? 'guest');
$friendshipId = $relationship['friendship']['id'] ?? null;
$packages = $packages ?? [];
$mods = $mods ?? [];
$musicTracks = $musicTracks ?? [];
$communityPosts = $communityPosts ?? [];
$activeStory = $activeStory ?? null;
$socialLinks = $socialLinks ?? [];
$accessDenied = (bool) ($accessDenied ?? false);
$accessReason = (string) (($accessReason ?? '') ?: 'Bu profile erisim sinirli.');
$canMessage = (bool) ($canMessage ?? false);
$messagePermission = $messagePermission ?? ['allowed' => false, 'reason' => 'Mesaj gonderilemez.'];
$messageDisabledLabel = trim((string) ($messagePermission['reason'] ?? '')) ?: 'Mesaj kapali.';
$isFollowing = (bool) ($isFollowing ?? false);
$viewerHasActiveSubscription = (bool) ($viewerHasActiveSubscription ?? false);
$isOwnProfile = (bool) ($isOwnProfile ?? ($profile && $viewer && (int) $profile['id'] === (int) $viewer['id']));
$displayName = (string) ($profile['display_name'] ?? $profile['nickname'] ?? $profile['username'] ?? $nickname ?? 'Profil');
$handle = (string) ($profile['nickname'] ?? $profile['username'] ?? $nickname ?? 'profil');
$role = (string) ($profile['role'] ?? 'user');
$about = (string) (($profile['about'] ?? '') ?: 'Bu profil henuz hakkinda metni eklememis.');
$avatar = (string) ($profile['avatar'] ?? '');
$cover = (string) ($profile['cover_image'] ?? '');
$createdAt = (string) ($profile['created_at'] ?? '');
$isCreatorProfile = $profile && (in_array($role, ['creator', 'admin'], true) || $packages !== [] || (int) ($stats['mod_count'] ?? 0) > 0 || (int) ($stats['music_count'] ?? 0) > 0);
$firstPackage = $packages[0] ?? null;
$messageUrl = $profile ? url('/studyo/mesajlar') . '?user_id=' . (int) $profile['id'] : '#';
$formatNumber = static fn (mixed $value): string => number_format((int) $value, 0, ',', '.');
$mediaUrl = static function (string $path): string {
    $path = trim($path);
    if ($path === '') {
        return '';
    }

    if (preg_match('~^https?://~i', $path)) {
        return $path;
    }

    return url('/' . ltrim($path, '/'));
};
$initial = strtoupper(substr($displayName, 0, 1) ?: 'Z');
$roleBadges = ['user'];
if (in_array($role, ['creator', 'moderator', 'admin'], true) && !in_array($role, $roleBadges, true)) {
    $roleBadges[] = $role;
}
$hasActiveStory = is_array($activeStory) && (int) ($activeStory['id'] ?? 0) > 0;
?>
<section class="profile-page profile-v13" data-profile-page data-csrf="<?= e(Csrf::token()) ?>">
    <?php if (!$profile): ?>
        <div class="container profile-lock-card">
            <span class="profile-lock-icon">!</span>
            <div>
                <p class="eyebrow">Profil</p>
                <h1>Profil yuklenemedi</h1>
                <p>Bu kullanici yayinda degil veya su anda goruntulenemiyor.</p>
            </div>
        </div>
    <?php else: ?>
        <div class="container profile-hero">
            <div class="profile-cover-hero<?= $cover !== '' ? ' has-cover' : '' ?>" <?= $cover !== '' ? 'style="background-image: linear-gradient(180deg, rgba(12,12,12,.04), rgba(12,12,12,.86)), url(' . e($mediaUrl($cover)) . ')"' : '' ?>></div>

            <div class="profile-info-card">
                <?php if ($hasActiveStory): ?>
                    <button
                        class="avatar profile-avatar-xl profile-story-ring"
                        type="button"
                        data-story-open
                        data-story-id="<?= (int) ($activeStory['id'] ?? 0) ?>"
                        data-user-id="<?= (int) ($profile['id'] ?? 0) ?>"
                        aria-label="<?= e($displayName) ?> story"
                    >
                        <?php if ($avatar !== ''): ?><img src="<?= e($mediaUrl($avatar)) ?>" alt="<?= e($displayName) ?>"><?php else: ?><?= e($initial) ?><?php endif; ?>
                    </button>
                <?php else: ?>
                    <span class="avatar profile-avatar-xl">
                        <?php if ($avatar !== ''): ?><img src="<?= e($mediaUrl($avatar)) ?>" alt="<?= e($displayName) ?>"><?php else: ?><?= e($initial) ?><?php endif; ?>
                    </span>
                <?php endif; ?>

                <div class="profile-identity">
                    <div class="profile-title-row">
                        <div>
                            <h1><?= e($displayName) ?></h1>
                            <p>@<?= e($handle) ?></p>
                        </div>
                        <div class="profile-badges" aria-label="Profil rozetleri">
                            <?php foreach ($roleBadges as $badge): ?>
                                <span class="profile-badge profile-badge-<?= e($badge) ?>"><?= e($badge) ?></span>
                            <?php endforeach; ?>
                        </div>
                    </div>

                    <?php if (!$accessDenied): ?>
                        <p class="profile-about-lead"><?= nl2br(e($about)) ?></p>
                        <?php if ($socialLinks !== []): ?>
                            <div class="profile-socials">
                                <?php foreach ($socialLinks as $link): ?>
                                    <a href="<?= e((string) $link['url']) ?>" rel="nofollow noopener" target="_blank"><?= e((string) $link['label']) ?></a>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                    <?php endif; ?>
                </div>

                <div
                    class="profile-actions"
                    data-profile-actions
                    data-user-id="<?= (int) $profile['id'] ?>"
                    data-state="<?= e($state) ?>"
                    data-friendship-id="<?= e((string) $friendshipId) ?>"
                    data-can-message="<?= $canMessage ? '1' : '0' ?>"
                    data-message-privacy="<?= e((string) ($profile['message_privacy'] ?? 'everyone')) ?>"
                    data-message-url="<?= e($messageUrl) ?>"
                >
                    <?php if ($isOwnProfile): ?>
                        <a class="pill primary" href="<?= url('/studyo/profilim') ?>">Studio'da Duzenle</a>
                    <?php elseif (!$viewer): ?>
                        <a class="pill primary" href="<?= url('/giris-yap') ?>">Giris Yap</a>
                        <a class="pill" href="<?= url('/kayit') ?>">Kayit Ol</a>
                        <button class="pill" type="button" data-auth-required data-auth-title="Giris gerekli" data-auth-message="Takip etmek icin giris yapmalisin.">Takip Et</button>
                    <?php else: ?>
                        <button class="pill primary" type="button" data-profile-action="request" <?= $state === 'none' ? '' : 'hidden' ?>>Arkadas Ekle</button>
                        <button class="pill primary" type="button" data-profile-action="accept" <?= $state === 'pending_received' ? '' : 'hidden' ?>>Istegi Kabul Et</button>
                        <button class="pill" type="button" data-profile-action="message" <?= $canMessage ? '' : 'hidden' ?>>Mesaj Gonder</button>
                        <button class="pill" type="button" disabled data-profile-state="message-disabled" <?= (!$canMessage && !in_array($state, ['blocked_by_me', 'blocked_me'], true)) ? '' : 'hidden' ?>><?= e($messageDisabledLabel) ?></button>
                        <button class="pill" type="button" disabled data-profile-state="pending" <?= $state === 'pending_sent' ? '' : 'hidden' ?>>Arkadaslik Istegi Gonderildi</button>
                        <button class="pill" type="button" disabled data-profile-state="friends" <?= $state === 'friends' ? '' : 'hidden' ?>>Arkadasiniz</button>
                        <button class="pill" type="button" data-profile-action="remove" <?= $state === 'friends' ? '' : 'hidden' ?>>Arkadasliktan Cikar</button>
                        <button class="pill" type="button" data-profile-action="block" <?= in_array($state, ['blocked_by_me', 'blocked_me'], true) ? 'hidden' : '' ?>>Engelle</button>
                        <button class="pill" type="button" data-profile-action="unblock" <?= $state === 'blocked_by_me' ? '' : 'hidden' ?>>Engeli Kaldir</button>
                        <button class="pill" type="button" disabled data-profile-state="blocked-me" <?= $state === 'blocked_me' ? '' : 'hidden' ?>>Etkilesim Engelli</button>
                        <?php if (!in_array($state, ['blocked_by_me', 'blocked_me'], true)): ?>
                            <button class="pill<?= $isFollowing ? ' is-active' : '' ?>" type="button" data-profile-follow-action="<?= $isFollowing ? 'unfollow' : 'follow' ?>" data-user-id="<?= (int) $profile['id'] ?>"><?= $isFollowing ? 'Takip Ediliyor' : 'Takip Et' ?></button>
                        <?php endif; ?>
                    <?php endif; ?>

                    <?php if (!$isOwnProfile && $isCreatorProfile && $firstPackage): ?>
                        <?php if ($viewerHasActiveSubscription): ?>
                            <button class="pill premium-locked-pill" type="button" disabled>Abonesin</button>
                        <?php elseif (!$viewer): ?>
                            <a class="pill primary" href="<?= url('/giris-yap') ?>" data-auth-required data-auth-title="Giris gerekli" data-auth-message="Abone olmak icin giris yapmalisin.">Abone Ol</a>
                        <?php else: ?>
                            <a class="pill primary" href="<?= url('/checkout/' . (int) $firstPackage['id']) ?>?period=monthly">Abone Ol</a>
                        <?php endif; ?>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <?php if ($accessDenied): ?>
            <div class="container profile-lock-card">
                <span class="profile-lock-icon">LOCK</span>
                <div>
                    <p class="eyebrow">Gizli Profil</p>
                    <h2>Bu profil kilitli</h2>
                    <p><?= e($accessReason) ?></p>
                    <?php if (!$viewer): ?><a class="pill primary" href="<?= url('/giris-yap') ?>">Giris Yap</a><?php endif; ?>
                </div>
            </div>
        <?php else: ?>
            <div class="container profile-stats-grid" aria-label="Profil istatistikleri">
                <span><strong><?= e($formatNumber($stats['mod_count'] ?? 0)) ?></strong>Mod</span>
                <span><strong><?= e($formatNumber($stats['music_count'] ?? 0)) ?></strong>Muzik</span>
                <span><strong><?= e($formatNumber($stats['total_downloads'] ?? 0)) ?></strong>Indirme</span>
                <span><strong><?= e($formatNumber($stats['total_plays'] ?? 0)) ?></strong>Dinlenme</span>
                <span><strong><?= e($formatNumber($stats['total_views'] ?? 0)) ?></strong>Goruntu</span>
                <span><strong><?= e($formatNumber($stats['subscriber_count'] ?? 0)) ?></strong>Abone</span>
            </div>

            <div class="container profile-tabs" data-profile-tabs>
                <div class="profile-tab-list" role="tablist" aria-label="Profil sekmeleri">
                    <button class="is-active" type="button" role="tab" aria-selected="true" data-profile-tab-target="mods">Modlar</button>
                    <button type="button" role="tab" aria-selected="false" data-profile-tab-target="music">Muzikler</button>
                    <button type="button" role="tab" aria-selected="false" data-profile-tab-target="community">Topluluk</button>
                    <button type="button" role="tab" aria-selected="false" data-profile-tab-target="support">Abonelik / Destek</button>
                    <button type="button" role="tab" aria-selected="false" data-profile-tab-target="about">Hakkinda</button>
                </div>

                <section class="profile-tab-panel is-active" data-profile-tab-panel="mods">
                    <?php if ($mods === []): ?>
                        <div class="empty-state profile-empty"><strong>Mod yok</strong><p>Bu kullanicinin yayinda mod kaydi henuz yok.</p></div>
                    <?php else: ?>
                        <div class="grid mods">
                            <?php foreach ($mods as $mod): ?>
                                <?php require BASE_PATH . '/app/Views/partials/mod-card.php'; ?>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </section>

                <section class="profile-tab-panel" data-profile-tab-panel="music" hidden>
                    <?php if ($musicTracks === []): ?>
                        <div class="empty-state profile-empty"><strong>Muzik yok</strong><p>Bu kullanicinin yayinda muzik kaydi henuz yok.</p></div>
                    <?php else: ?>
                        <div class="grid music-grid">
                            <?php foreach ($musicTracks as $track): ?>
                                <?php require BASE_PATH . '/app/Views/partials/music-card.php'; ?>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </section>

                <section class="profile-tab-panel" data-profile-tab-panel="community" hidden>
                    <div class="profile-community-feed">
                        <?php if ($isOwnProfile): ?>
                            <?php require BASE_PATH . '/app/Views/partials/community-composer.php'; ?>
                        <?php endif; ?>

                        <?php if ($communityPosts === []): ?>
                            <div class="empty-state profile-empty">
                                <strong>Henuz topluluk gonderisi yok.</strong>
                                <p>Creator duyurulari ve takipci guncellemeleri burada gorunecek.</p>
                            </div>
                        <?php else: ?>
                            <?php foreach ($communityPosts as $post): ?>
                                <?php require BASE_PATH . '/app/Views/partials/community-post-card.php'; ?>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                </section>

                <section class="profile-tab-panel" data-profile-tab-panel="support" hidden>
                    <?php if (!$isCreatorProfile): ?>
                        <div class="empty-state profile-empty"><strong>Destek paketi yok</strong><p>Bu profil creator destek paketleri yayinlamiyor.</p></div>
                    <?php elseif ($packages === []): ?>
                        <div class="empty-state profile-empty"><strong>Aktif paket yok</strong><p>Bu creator henuz aktif destek paketi yayinlamamis.</p></div>
                    <?php else: ?>
                        <div class="grid package-grid">
                            <?php foreach ($packages as $package): ?>
                                <?php
                                $creator = $profile;
                                $viewerHasActive = (bool) ($package['viewer_is_subscribed'] ?? false);
                                $viewerIsGuest = !$viewer;
                                require BASE_PATH . '/app/Views/partials/package-card.php';
                                ?>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </section>

                <section class="profile-tab-panel" data-profile-tab-panel="about" hidden>
                    <div class="profile-about-grid">
                        <article>
                            <p class="eyebrow">Hakkinda</p>
                            <h2><?= e($displayName) ?></h2>
                            <p><?= nl2br(e($about)) ?></p>
                        </article>
                        <article>
                            <p class="eyebrow">Baglantilar</p>
                            <?php if ($socialLinks === []): ?>
                                <p class="muted">Sosyal medya linki eklenmemis.</p>
                            <?php else: ?>
                                <div class="profile-socials">
                                    <?php foreach ($socialLinks as $link): ?>
                                        <a href="<?= e((string) $link['url']) ?>" rel="nofollow noopener" target="_blank"><?= e((string) $link['label']) ?></a>
                                    <?php endforeach; ?>
                                </div>
                            <?php endif; ?>
                        </article>
                        <article>
                            <p class="eyebrow">Profil Ozeti</p>
                            <dl class="profile-summary-list">
                                <div><dt>Takma ad</dt><dd>@<?= e($handle) ?></dd></div>
                                <div><dt>Rol</dt><dd><?= e($role) ?></dd></div>
                                <?php if ($createdAt !== ''): ?><div><dt>Katilma</dt><dd><?= e(date('d.m.Y', strtotime($createdAt))) ?></dd></div><?php endif; ?>
                                <div><dt>Toplam icerik</dt><dd><?= e($formatNumber(((int) ($stats['mod_count'] ?? 0)) + ((int) ($stats['music_count'] ?? 0)))) ?></dd></div>
                            </dl>
                        </article>
                    </div>
                </section>
            </div>
        <?php endif; ?>
    <?php endif; ?>
</section>
<?php require BASE_PATH . '/app/Views/partials/story-viewer.php'; ?>
