<?php

declare(strict_types=1);

require_once __DIR__ . '/bootstrap.php';

$status = $profileRepo->schemaStatus();
$user = profile_current_user($profileAuth);
$slug = isset($_GET['slug']) ? strtolower(trim((string)$_GET['slug'])) : '';
$errorMessage = '';
$profile = null;

if (!$status['ok']) {
    $errorMessage = 'Profilový modul ještě nemá nasazenou databázovou migraci.';
} elseif ($slug === '') {
    if ($user && !$user['is_company']) {
        header('Location: /profile/edit');
        exit;
    }
    http_response_code(404);
    $errorMessage = 'Tahle profilová stránka neexistuje.';
} else {
    try {
        $profile = $profileRepo->getPublicProfileBySlug($slug);
    } catch (Throwable $e) {
        http_response_code(500);
        $errorMessage = 'Profil se nepodařilo načíst.';
    }

    if (!$profile && $errorMessage === '') {
        http_response_code(404);
        $errorMessage = 'Tahle profilová stránka neexistuje nebo ještě není publikovaná.';
    }

    if ($profile) {
        try {
            $profileRepo->recordView(
                (int)$profile['account_id'],
                $_SERVER['HTTP_REFERER'] ?? null,
                $_SERVER['HTTP_USER_AGENT'] ?? null,
                $_SERVER['REMOTE_ADDR'] ?? null
            );
        } catch (Throwable $e) {
        }
    }
}

function profile_h(string $value): string
{
    return htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
}

function profile_initials(string $value): string
{
    $value = trim($value);
    if ($value === '') {
        return 'IN';
    }
    $parts = preg_split('/\s+/', $value) ?: [];
    $initials = '';
    foreach ($parts as $part) {
        $initials .= mb_substr($part, 0, 1, 'UTF-8');
        if (mb_strlen($initials, 'UTF-8') >= 2) {
            break;
        }
    }
    return mb_strtoupper($initials !== '' ? $initials : mb_substr($value, 0, 2, 'UTF-8'), 'UTF-8');
}

function link_icon_class(array $link): string
{
    $platform = strtolower((string)($link['platform'] ?? ''));
    return match (true) {
        $platform === 'instagram' => 'ph-instagram-logo',
        $platform === 'tiktok' => 'ph-tiktok-logo',
        $platform === 'youtube' => 'ph-youtube-logo',
        $platform === 'facebook' => 'ph-facebook-logo',
        $platform === 'x' => 'ph-x-logo',
        $platform === 'linkedin' => 'ph-linkedin-logo',
        $platform === 'spotify' => 'ph-spotify-logo',
        $platform === 'pinterest' => 'ph-pinterest-logo',
        ($link['link_type'] ?? '') === 'shop' => 'ph-shopping-bag-open',
        ($link['link_type'] ?? '') === 'web' => 'ph-globe-hemisphere-west',
        default => 'ph-arrow-square-out',
    };
}

function ordered_links(array $links): array
{
    $featured = [];
    $regular = [];
    foreach ($links as $link) {
        if (!empty($link['is_featured'])) {
            $featured[] = $link;
        } else {
            $regular[] = $link;
        }
    }
    return array_merge($featured, $regular);
}

function profile_location_label(array $profile): string
{
    if (!empty($profile['audience_regions'][0])) {
        return (string)$profile['audience_regions'][0];
    }

    $parts = array_values(array_filter([
        (string)($profile['city'] ?? ''),
        (string)($profile['location'] ?? ''),
    ]));

    return implode(', ', $parts);
}

$preset = $profile ? (string)($profile['theme_preset'] ?? 'portrait') : 'portrait';
$themes = [
    'portrait' => ['bg' => 'linear-gradient(180deg, #f8efe8 0%, #efe7de 100%)', 'text' => '#1a1a1a', 'card_bg' => 'rgba(255,255,255,0.4)', 'card_border' => 'rgba(255,255,255,0.5)', 'text_muted' => 'rgba(26,26,26,0.6)', 'button' => '#ffffff', 'button_text' => '#0f1222'],
    'editorial' => ['bg' => 'linear-gradient(180deg, #f7f7f3 0%, #efefe8 100%)', 'text' => '#1a1a1a', 'card_bg' => 'rgba(255,255,255,0.5)', 'card_border' => 'rgba(255,255,255,0.6)', 'text_muted' => 'rgba(26,26,26,0.6)', 'button' => '#101010', 'button_text' => '#ffffff'],
    'spotlight' => ['bg' => 'linear-gradient(180deg, #fff7f1 0%, #f4efff 100%)', 'text' => '#1a1a1a', 'card_bg' => 'rgba(255,255,255,0.4)', 'card_border' => 'rgba(255,255,255,0.5)', 'text_muted' => 'rgba(26,26,26,0.6)', 'button' => '#14142a', 'button_text' => '#ffffff'],
    'midnight' => ['bg' => 'linear-gradient(180deg, #11152a 0%, #0b0d16 100%)', 'text' => '#ffffff', 'card_bg' => 'rgba(255,255,255,0.07)', 'card_border' => 'rgba(255,255,255,0.08)', 'text_muted' => 'rgba(255,255,255,0.6)', 'button' => '#ffffff', 'button_text' => '#0f1222'],
];
$theme = $themes[$preset] ?? $themes['portrait'];
$orderedLinks = $profile ? ordered_links($profile['links']) : [];
$locationLabel = $profile ? profile_location_label($profile) : '';
$customBg = ($profile && preg_match('/^#[0-9a-f]{6}$/i', (string)($profile['bg_color'] ?? '')))
    ? strtolower($profile['bg_color'])
    : '';

// When a custom bg_color is set, auto-pick dark vs light theme variables based on luminance
if ($customBg !== '') {
    $r = hexdec(substr($customBg, 1, 2));
    $g = hexdec(substr($customBg, 3, 2));
    $b = hexdec(substr($customBg, 5, 2));
    // Perceived luminance (sRGB)
    $lum = (0.299 * $r + 0.587 * $g + 0.114 * $b) / 255;
    if ($lum < 0.45) {
        // Dark custom bg — use dark (midnight-style) variables
        $theme['text']       = '#ffffff';
        $theme['text_muted'] = 'rgba(255,255,255,0.6)';
        $theme['card_bg']    = 'rgba(255,255,255,0.09)';
        $theme['card_border']= 'rgba(255,255,255,0.12)';
        $theme['button']     = '#ffffff';
        $theme['button_text']= '#0f1222';
    } else {
        // Light custom bg — use light variables
        $theme['text']       = '#1a1a1a';
        $theme['text_muted'] = 'rgba(26,26,26,0.6)';
        $theme['card_bg']    = 'rgba(255,255,255,0.45)';
        $theme['card_border']= 'rgba(255,255,255,0.6)';
        $theme['button']     = '#ffffff';
        $theme['button_text']= '#0f1222';
    }
}
?>
<!DOCTYPE html>
<html lang="cs">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title><?= $profile ? profile_h($profile['headline']) . ' | Influenz' : 'Influenz profil' ?></title>
  <meta name="description" content="<?= $profile ? profile_h(mb_substr($profile['intro'] !== '' ? $profile['intro'] : 'Profil tvůrce na Influenz.', 0, 155, 'UTF-8')) : 'Profil tvůrce na Influenz.' ?>">
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800;900&display=swap" rel="stylesheet">
  <script src="https://unpkg.com/@phosphor-icons/web"></script>
  <style>
    :root {
      --accent: <?= profile_h($profile['accent_color'] ?? '#f36b4f') ?>;
      --button: <?= profile_h($theme['button']) ?>;
      --button-text: <?= profile_h($theme['button_text']) ?>;
      --text: <?= profile_h($theme['text']) ?>;
      --text-muted: <?= profile_h($theme['text_muted']) ?>;
      --card-bg: <?= profile_h($theme['card_bg']) ?>;
      --card-border: <?= profile_h($theme['card_border']) ?>;
    }
    * { box-sizing: border-box; }
    body {
      margin: 0;
      min-height: 100vh;
      font-family: 'Inter', sans-serif;
      color: var(--text);
      background: <?= profile_h($customBg ?: $theme['bg']) ?>;
    }
    .bg-blur {
      position: fixed;
      inset: 0;
      width: 100vw;
      height: 100vh;
      object-fit: cover;
      z-index: -2;
      filter: blur(80px) saturate(1.5);
      opacity: 0.6;
      transform: scale(1.2);
    }
    .bg-overlay {
      position: fixed;
      inset: 0;
      background: <?= profile_h($customBg ? $customBg : $theme['bg']) ?>;
      opacity: 0.85;
      z-index: -1;
    }
    a { color: inherit; }
    .page-shell {
      width: min(100%, 540px);
      min-height: 100vh;
      margin: 0 auto;
      padding: 0 0 64px;
      display: flex;
      flex-direction: column;
    }
    /* Hero avatar image */
    .hero-img {
      width: calc(100% - 32px);
      margin: 16px auto 0;
      aspect-ratio: 1 / 0.95;
      object-fit: cover;
      object-position: center top;
      display: block;
      border-radius: 32px;
      -webkit-mask-image: linear-gradient(to bottom, black 60%, transparent 100%);
      mask-image: linear-gradient(to bottom, black 60%, transparent 100%);
    }
    .hero-fallback {
      width: calc(100% - 32px);
      margin: 16px auto 0;
      aspect-ratio: 1 / 0.95;
      border-radius: 32px;
      background: radial-gradient(circle at 60% 30%, color-mix(in srgb, var(--accent) 40%, transparent), transparent 70%), #0f1525;
      display: flex;
      align-items: flex-end;
      justify-content: center;
      padding-bottom: 80px;
      -webkit-mask-image: linear-gradient(to bottom, black 60%, transparent 100%);
      mask-image: linear-gradient(to bottom, black 60%, transparent 100%);
    }
    .hero-fallback-initials {
      font-size: 5rem;
      font-weight: 900;
      opacity: 0.18;
      letter-spacing: -0.05em;
    }
    .identity {
      text-align: center;
      position: relative;
      z-index: 10;
      margin: -60px 16px 16px;
    }
    h1 {
      margin: 0;
      font-size: clamp(2rem, 7vw, 2.7rem);
      line-height: 1.08;
      font-weight: 800;
      letter-spacing: -0.04em;
    }
    .handle {
      margin-top: 6px;
      color: var(--text-muted);
      font-size: 0.95rem;
      font-weight: 500;
    }
    .location {
      display: inline-flex;
      align-items: center;
      justify-content: center;
      gap: 6px;
      margin-top: 10px;
      padding: 6px 12px;
      border-radius: 999px;
      background: var(--card-bg);
      border: 1px solid var(--card-border);
      color: var(--text);
      font-size: 0.82rem;
      font-weight: 600;
    }
    .hero-cta {
      display: flex;
      align-items: center;
      gap: 10px;
      margin: 0 16px 24px;
    }
    .button-primary,
    .button-secondary {
      text-decoration: none;
      display: inline-flex;
      align-items: center;
      justify-content: center;
      border: 0;
    }
    .button-primary {
      flex: 1;
      min-height: 56px;
      padding: 0 18px;
      border-radius: 999px;
      background: var(--button);
      color: var(--button-text);
      font-weight: 800;
      font-size: 1rem;
    }
    .button-secondary {
      width: 56px;
      height: 56px;
      border-radius: 999px;
      background: var(--card-bg);
      border: 1px solid var(--card-border);
      color: var(--text);
      font-size: 1.25rem;
    }
    .glass-card {
      border-radius: 24px;
      padding: 18px;
      background: linear-gradient(135deg, var(--card-bg), color-mix(in srgb, var(--accent) 10%, var(--card-bg)));
      border: 1px solid var(--card-border);
      backdrop-filter: blur(16px);
      box-shadow: 0 8px 32px rgba(0,0,0,0.18);
      margin: 0 16px 16px;
    }
    .bio-card {
      font-size: 0.93rem;
      line-height: 1.65;
      color: var(--text);
    }
    .bio-title {
      font-size: 0.72rem;
      font-weight: 700;
      text-transform: uppercase;
      letter-spacing: 0.1em;
      color: var(--text-muted);
      margin: 0 0 10px;
    }
    .bio-text {
      margin: 0;
    }
    .chip-row {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
      margin-top: 14px;
    }
    .chip {
      display: inline-flex;
      align-items: center;
      padding: 8px 11px;
      border-radius: 999px;
      background: var(--card-bg);
      border: 1px solid var(--card-border);
      color: var(--text);
      font-size: 0.76rem;
      font-weight: 700;
    }
    .tiles-grid {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 12px;
      margin: 0 16px 32px;
    }
    .tile-link {
      min-height: 142px;
      border-radius: 22px;
      padding: 16px;
      background: linear-gradient(180deg, var(--card-bg), color-mix(in srgb, var(--accent) 16%, var(--card-bg)));
      border: 1px solid var(--card-border);
      backdrop-filter: blur(16px);
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      text-decoration: none;
      transition: transform 150ms ease;
    }
    .tile-link:hover { transform: translateY(-2px); }
    .tile-link.featured { grid-column: 1 / -1; min-height: 142px; }
    .tile-icon {
      width: 38px;
      height: 38px;
      border-radius: 12px;
      display: inline-flex;
      align-items: center;
      justify-content: center;
      background: rgba(255,255,255,0.18);
      font-size: 1rem;
      color: var(--text);
      flex-shrink: 0;
    }
    .tile-title {
      margin-top: auto;
      font-size: 0.98rem;
      line-height: 1.24;
      font-weight: 800;
      color: var(--text);
    }
    @media (max-width: 500px) {
      .tiles-grid {
        grid-template-columns: 1fr;
      }
      .tile-link {
        min-height: 0;
        flex-direction: row;
        align-items: center;
        justify-content: flex-start;
        gap: 14px;
        padding: 14px 16px;
      }
      .tile-link.featured {
        grid-column: unset;
        min-height: 0;
      }
      .tile-title {
        margin-top: 0;
        font-size: 0.95rem;
      }
    }
    .badge-footer {
      display: flex;
      flex-direction: column;
      align-items: center;
      gap: 8px;
      margin-top: 12px;
    }
    .badge-avatar {
      width: 48px;
      height: 48px;
      border-radius: 999px;
      object-fit: cover;
    }
    .badge-name {
      font-weight: 700;
      font-size: 1rem;
      color: var(--text);
    }
    .badge-link {
      color: var(--text-muted);
      font-size: 0.9rem;
      text-decoration: none;
    }
    .formbox {
      margin-top: 32px;
    }
    .formbox h2 {
      margin: 0 0 12px;
      font-size: 1.45rem;
      font-weight: 800;
    }
    .formbox-grid {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 12px;
    }
    .formbox label {
      display: grid;
      gap: 8px;
      font-size: 0.92rem;
      font-weight: 700;
    }
    .formbox input,
    .formbox textarea {
      width: 100%;
      border-radius: 16px;
      padding: 14px;
      background: rgba(255,255,255,0.1);
      border: 1px solid rgba(255,255,255,0.12);
      color: white;
      outline: none;
      font: inherit;
    }
    .formbox textarea {
      min-height: 132px;
      resize: vertical;
    }
    .hidden-honeypot { display: none; }
    .form-feedback {
      display: none;
      margin-top: 12px;
      padding: 12px 14px;
      border-radius: 14px;
      font-size: 0.9rem;
      font-weight: 700;
    }
    .empty {
      min-height: 100vh;
      display: grid;
      place-items: center;
      padding: 24px;
    }
    .empty-card {
      width: min(100%, 520px);
      text-align: center;
      padding: 28px;
      border-radius: 28px;
      background: rgba(255,255,255,0.08);
      border: 1px solid rgba(255,255,255,0.1);
      backdrop-filter: blur(18px);
    }
    @media (max-width: 640px) {
      .formbox-grid { grid-template-columns: 1fr; }
    }
  </style>
</head>
<body>
<?php if (!$profile): ?>
  <div class="empty">
    <div class="empty-card">
      <h1 style="font-size:2rem;margin-bottom:14px;">Link in bio pro tvůrce</h1>
      <p style="margin:0;color:rgba(255,255,255,0.75);line-height:1.7;"><?= profile_h($errorMessage) ?></p>
      <?php if ($user && !$user['is_company'] && $status['ok']): ?>
        <a class="button-primary" href="/profile/edit" style="margin-top:22px;">Otevřít editor profilu</a>
      <?php endif; ?>
    </div>
  </div>
<?php else: ?>
  <?php if ($profile['avatar_url'] !== ''): ?>
    <img class="bg-blur" src="<?= profile_h($profile['avatar_url']) ?>" alt="" aria-hidden="true">
  <?php endif; ?>
  <div class="bg-overlay"></div>

  <main class="page-shell">
    <?php if ($profile['avatar_url'] !== ''): ?>
      <img class="hero-img" src="<?= profile_h($profile['avatar_url']) ?>" alt="<?= profile_h($profile['headline']) ?>">
    <?php else: ?>
      <div class="hero-fallback"><div class="hero-fallback-initials"><?= profile_h(profile_initials($profile['headline'])) ?></div></div>
    <?php endif; ?>

    <div class="identity">
      <h1><?= profile_h($profile['headline']) ?></h1>
      <?php
        $handle = $profile['instagram'] !== '' ? '@' . $profile['instagram']
          : ($profile['tiktok'] !== '' ? '@' . $profile['tiktok']
          : ($profile['twitter'] !== '' ? '@' . $profile['twitter'] : ''));
      ?>
      <?php if ($handle !== ''): ?>
        <div class="handle"><?= profile_h($handle) ?></div>
      <?php endif; ?>
      <?php if (!empty($profile['show_location']) && $locationLabel !== ''): ?>
        <div class="location"><i class="ph ph-map-pin"></i><?= profile_h($locationLabel) ?></div>
      <?php endif; ?>
    </div>

    <div class="hero-cta">
      <?php if ($profile['primary_cta_mode'] === 'form'): ?>
        <a class="button-primary" href="#contact-formbox">Napsat pro spolupráci</a>
      <?php elseif (in_array($profile['primary_cta_mode'], ['link', 'both'], true) && $profile['primary_cta_url'] !== ''): ?>
        <a class="button-primary" href="<?= profile_h($profile['primary_cta_url']) ?>" target="_blank" rel="nofollow noopener">
          <?= profile_h($profile['primary_cta_label'] !== '' ? $profile['primary_cta_label'] : 'Otevřít odkaz') ?>
        </a>
      <?php endif; ?>
      <?php if (in_array($profile['primary_cta_mode'], ['form', 'both'], true)): ?>
        <a class="button-secondary" href="#contact-formbox" aria-label="Napsat pro spolupráci"><i class="ph ph-envelope"></i></a>
      <?php endif; ?>
    </div>

    <div class="glass-card bio-card">
      <p class="bio-title">O mně</p>
      <p class="bio-text"><?= nl2br(profile_h($profile['intro'] !== '' ? $profile['intro'] : 'Profil tvůrce na Influenz.')) ?></p>
    </div>

    <?php if ($orderedLinks !== []): ?>
      <div class="tiles-grid">
        <?php foreach ($orderedLinks as $link): ?>
          <a class="tile-link<?= !empty($link['is_featured']) ? ' featured' : '' ?>"
             href="<?= profile_h($link['url']) ?>"
             data-track="/profile/api/click.php?slug=<?= rawurlencode($profile['slug']) ?>&id=<?= (int)$link['id'] ?>"
             target="_blank" rel="nofollow noopener">
            <div class="tile-icon"><i class="ph <?= profile_h(link_icon_class($link)) ?>"></i></div>
            <div class="tile-title"><?= profile_h($link['title']) ?></div>
          </a>
        <?php endforeach; ?>
      </div>
    <?php endif; ?>

    <div class="badge-footer">
      <a href="https://influenz.cz" class="badge-link">Powered by Influenz</a>
    </div>

    <script>
      document.querySelectorAll('a[data-track]').forEach(function(el) {
        el.addEventListener('click', function() {
          if (navigator.sendBeacon) { navigator.sendBeacon(el.dataset.track); }
          else { fetch(el.dataset.track, { method: 'POST', keepalive: true }).catch(function(){}); }
        });
      });
    </script>

    <?php if (in_array($profile['primary_cta_mode'], ['form', 'both'], true)): ?>
      <section class="glass-card formbox" id="contact-formbox">
        <h2>Napište mi</h2>
        <form id="contact-form">
          <div class="hidden-honeypot"><input type="text" id="website" name="website" autocomplete="off" tabindex="-1"></div>
          <div class="formbox-grid">
            <label>Jméno
              <input type="text" id="contact-name" name="name" placeholder="Jak se jmenujete" required>
            </label>
            <label>E-mail
              <input type="email" id="contact-email" name="email" placeholder="vas@email.cz" required>
            </label>
          </div>
          <label style="margin-top:12px;">Zpráva
            <textarea id="contact-message" name="message" placeholder="Co přesně nabízíte, jaký je termín a jaký je orientační rozpočet?" required></textarea>
          </label>
          <button type="submit" class="button-primary" id="contact-submit" style="margin-top:14px;">Odeslat zprávu</button>
          <div class="form-feedback" id="form-feedback"></div>
        </form>
      </section>
      <script>
        const contactForm = document.getElementById('contact-form');
        const feedback = document.getElementById('form-feedback');
        const submitButton = document.getElementById('contact-submit');

        function showFeedback(message, type) {
          feedback.textContent = message;
          feedback.style.display = 'block';
          feedback.style.background = type === 'success' ? 'rgba(34,197,94,0.18)' : 'rgba(239,68,68,0.18)';
          feedback.style.color = type === 'success' ? '#86efac' : '#fca5a5';
        }

        contactForm.addEventListener('submit', async (event) => {
          event.preventDefault();
          submitButton.disabled = true;
          submitButton.style.opacity = '0.7';
          feedback.style.display = 'none';

          const payload = {
            slug: <?= json_encode($profile['slug'], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>,
            name: document.getElementById('contact-name').value.trim(),
            email: document.getElementById('contact-email').value.trim(),
            message: document.getElementById('contact-message').value.trim(),
            website: document.getElementById('website').value.trim()
          };

          try {
            const response = await fetch('/profile/api/contact.php', {
              method: 'POST',
              headers: { 'Content-Type': 'application/json' },
              body: JSON.stringify(payload),
            });
            const data = await response.json();
            if (!response.ok) throw new Error(data.error || 'Zprávu se nepodařilo odeslat.');
            contactForm.reset();
            showFeedback('Zpráva odeslána.', 'success');
          } catch (error) {
            showFeedback(error.message || 'Chyba při odeslání.', 'error');
          } finally {
            submitButton.disabled = false;
            submitButton.style.opacity = '1';
          }
        });
      </script>
    <?php endif; ?>
  </main>
<?php endif; ?>
</body>
</html>
