<?php

declare(strict_types=1);

require_once __DIR__ . '/bootstrap.php';

$user = profile_current_user($profileAuth);
$status = $profileRepo->schemaStatus();
?>
<!DOCTYPE html>
<html lang="cs">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Editor profilu | Influenz</title>
  <meta name="robots" content="noindex,nofollow">
  <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: #f36b4f;
      --ink: #121217;
      --muted: #66606b;
      --line: rgba(18,18,23,0.08);
      --line-strong: rgba(18,18,23,0.14);
      --bg: radial-gradient(circle at top left, rgba(243,107,79,0.18), transparent 24%), radial-gradient(circle at top right, rgba(88,101,242,0.12), transparent 22%), linear-gradient(180deg, #f7efe8 0%, #f5f4f8 100%);
      --card: rgba(255,255,255,0.82);
      --shadow: 0 28px 80px rgba(18,18,23,0.10);
    }
    * { box-sizing: border-box; }
    html { scroll-behavior: smooth; }
    body {
      margin: 0;
      min-height: 100vh;
      font-family: 'Inter', sans-serif;
      color: var(--ink);
      background: var(--bg);
    }
    a { color: inherit; }
    button, input, textarea, select { font: inherit; }
    .shell {
      width: min(1360px, calc(100% - 28px));
      margin: 0 auto;
      padding: 18px 0 120px;
    }
    .topbar {
      display: flex;
      align-items: center;
      justify-content: space-between;
      gap: 16px;
      margin-bottom: 18px;
    }
    .brand {
      display: inline-flex;
      align-items: center;
      gap: 12px;
      text-decoration: none;
    }
    .brand-wordmark {
      font-size: 1.72rem;
      line-height: 1;
      font-weight: 900;
      letter-spacing: -0.06em;
      color: #0f172a;
    }
    .brand-wordmark span { color: var(--accent); }
    .brand-copy {
      color: var(--muted);
      font-size: 0.95rem;
      font-weight: 700;
    }
    .top-actions {
      display: flex;
      gap: 10px;
      flex-wrap: wrap;
      align-items: center;
    }
    .ghost,
    .primary,
    .soft-button {
      appearance: none;
      border: 0;
      border-radius: 18px;
      min-height: 46px;
      padding: 0 16px;
      display: inline-flex;
      align-items: center;
      justify-content: center;
      gap: 8px;
      cursor: pointer;
      font-weight: 800;
      transition: transform 150ms ease, box-shadow 150ms ease, border-color 150ms ease, background 150ms ease;
      text-decoration: none;
    }
    .ghost:hover,
    .primary:hover,
    .soft-button:hover { transform: translateY(-1px); }
    .ghost,
    .soft-button {
      background: rgba(255,255,255,0.78);
      border: 1px solid var(--line);
      color: var(--ink);
    }
    .primary {
      background: linear-gradient(135deg, var(--accent), #ff8a51);
      color: #fff;
      box-shadow: 0 20px 36px rgba(243,107,79,0.24);
    }
    .layout {
      display: grid;
      grid-template-columns: minmax(0, 1.06fr) minmax(390px, 0.94fr);
      gap: 18px;
      align-items: start;
    }
    .stack { display: grid; gap: 18px; }
    .card,
    .section-card,
    .preview-shell,
    .setup-card,
    .modal-card {
      background: var(--card);
      border: 1px solid rgba(255,255,255,0.56);
      border-radius: 28px;
      box-shadow: var(--shadow);
      backdrop-filter: blur(18px);
    }
    .panel { padding: 24px; }
    .section-card,
    .preview-shell,
    .setup-card,
    .modal-card { padding: 22px; }
    .eyebrow {
      display: inline-flex;
      align-items: center;
      gap: 9px;
      padding: 10px 14px;
      border-radius: 999px;
      background: rgba(255,255,255,0.76);
      border: 1px solid var(--line);
      color: var(--muted);
      font-size: 0.8rem;
      font-weight: 800;
      text-transform: uppercase;
      letter-spacing: 0.08em;
    }
    .eyebrow-dot {
      width: 8px;
      height: 8px;
      border-radius: 999px;
      background: var(--accent);
      box-shadow: 0 0 0 6px rgba(243,107,79,0.12);
    }
    h1, h2, h3 { margin: 0; }
    h1 {
      margin-top: 12px;
      font-size: clamp(2.4rem, 5vw, 3.5rem);
      line-height: 0.96;
      letter-spacing: -0.05em;
      font-weight: 900;
    }
    .lede {
      margin: 12px 0 0;
      max-width: 62ch;
      color: var(--muted);
      line-height: 1.75;
    }
    .section-title {
      font-size: 0.84rem;
      letter-spacing: 0.08em;
      text-transform: uppercase;
      color: var(--muted);
      font-weight: 800;
      margin-bottom: 6px;
    }
    .section-subtitle {
      color: var(--muted);
      line-height: 1.65;
      margin-bottom: 16px;
    }
    .fields { display: grid; gap: 14px; }
    .split { display: grid; grid-template-columns: 1fr 1fr; gap: 14px; }
    label {
      display: grid;
      gap: 8px;
      font-size: 0.92rem;
      font-weight: 800;
    }
    .label-note {
      font-size: 0.82rem;
      font-weight: 600;
      color: var(--muted);
    }
    input[type='text'],
    input[type='email'],
    input[type='url'],
    textarea,
    select {
      width: 100%;
      border: 1px solid var(--line);
      border-radius: 18px;
      background: rgba(255,255,255,0.94);
      color: var(--ink);
      padding: 14px 15px;
      outline: none;
      transition: border-color 150ms ease, box-shadow 150ms ease;
    }
    textarea {
      min-height: 128px;
      resize: vertical;
    }
    input[type='text']:focus,
    input[type='email']:focus,
    input[type='url']:focus,
    textarea:focus,
    select:focus {
      border-color: color-mix(in srgb, var(--accent) 40%, var(--line));
      box-shadow: 0 0 0 4px rgba(243,107,79,0.12);
    }
    .toggle {
      display: flex;
      align-items: center;
      gap: 10px;
      min-height: 52px;
      padding: 12px 14px;
      border-radius: 18px;
      background: rgba(255,255,255,0.76);
      border: 1px solid var(--line);
      font-weight: 800;
    }
    .preset-grid {
      display: grid;
      grid-template-columns: repeat(4, 1fr);
      gap: 12px;
    }
    .preset-card {
      padding: 12px;
      border-radius: 20px;
      border: 1px solid var(--line);
      background: rgba(255,255,255,0.78);
      cursor: pointer;
      transition: border-color 150ms ease, transform 150ms ease, box-shadow 150ms ease;
      text-align: left;
    }
    .preset-card:hover { transform: translateY(-1px); }
    .preset-card.active {
      border-color: color-mix(in srgb, var(--accent) 42%, var(--line));
      box-shadow: 0 16px 32px rgba(18,18,23,0.08);
    }
    .preset-swatch {
      height: 116px;
      border-radius: 16px;
      margin-bottom: 10px;
      border: 1px solid rgba(255,255,255,0.45);
      position: relative;
      overflow: hidden;
    }
    .preset-swatch::after {
      content: '';
      position: absolute;
      left: 10px;
      right: 10px;
      bottom: 10px;
      height: 28px;
      border-radius: 14px;
      background: rgba(255,255,255,0.58);
    }
    .accent-field {
      display: flex;
      align-items: center;
      gap: 12px;
      min-height: 56px;
      padding: 10px 12px;
      border-radius: 18px;
      background: rgba(255,255,255,0.94);
      border: 1px solid var(--line);
    }
    .accent-field:focus-within {
      border-color: color-mix(in srgb, var(--accent) 40%, var(--line));
      box-shadow: 0 0 0 4px rgba(243,107,79,0.12);
    }
    .accent-swatch {
      width: 34px;
      height: 34px;
      flex: 0 0 34px;
      border: 0;
      border-radius: 12px;
      background: var(--accent);
      box-shadow: inset 0 0 0 1px rgba(0,0,0,0.08);
      cursor: pointer;
    }
    .accent-hex {
      border: 0 !important;
      background: transparent !important;
      padding: 0 !important;
      min-height: auto !important;
      box-shadow: none !important;
      font-weight: 700;
      letter-spacing: 0.02em;
    }
    .upload-card {
      display: grid;
      grid-template-columns: 132px 1fr;
      gap: 18px;
      align-items: center;
      padding: 16px;
      border-radius: 24px;
      border: 1px dashed var(--line-strong);
      background: rgba(255,255,255,0.72);
    }
    .avatar-preview {
      width: 132px;
      height: 154px;
      border-radius: 22px;
      overflow: hidden;
      display: grid;
      place-items: center;
      background: linear-gradient(180deg, rgba(243,107,79,0.28), rgba(17,17,17,0.18));
      color: white;
      font-size: 2.6rem;
      font-weight: 800;
      letter-spacing: -0.06em;
    }
    .avatar-preview img { width: 100%; height: 100%; object-fit: cover; }
    .hidden-input { display: none; }
    .tag-editor {
      display: grid;
      gap: 10px;
      padding: 14px;
      border-radius: 20px;
      background: rgba(255,255,255,0.78);
      border: 1px solid var(--line);
    }
    .tag-list {
      display: flex;
      flex-wrap: wrap;
      gap: 10px;
      min-height: 28px;
    }
    .tag {
      display: inline-flex;
      align-items: center;
      gap: 8px;
      padding: 9px 12px;
      border-radius: 999px;
      background: rgba(255,255,255,0.95);
      border: 1px solid var(--line);
      font-weight: 800;
      font-size: 0.88rem;
    }
    .tag button {
      appearance: none;
      border: 0;
      background: transparent;
      padding: 0;
      cursor: pointer;
      color: var(--muted);
      font-size: 1rem;
    }
    .tag-input-row {
      display: flex;
      gap: 10px;
    }
    .tag-input-row input { flex: 1; }
    .link-builder-header {
      display: flex;
      align-items: end;
      justify-content: space-between;
      gap: 14px;
      margin-bottom: 16px;
      flex-wrap: wrap;
    }
    .link-list { display: grid; gap: 14px; }
    .link-card {
      display: grid;
      gap: 14px;
      padding: 16px;
      border-radius: 24px;
      background: rgba(255,255,255,0.78);
      border: 1px solid var(--line);
    }
    .link-card-top {
      display: flex;
      align-items: center;
      justify-content: space-between;
      gap: 12px;
    }
    .link-kind {
      display: inline-flex;
      align-items: center;
      gap: 10px;
      font-weight: 800;
      font-size: 1rem;
    }
    .icon-circle {
      width: 42px;
      height: 42px;
      border-radius: 15px;
      display: inline-flex;
      align-items: center;
      justify-content: center;
      background: color-mix(in srgb, var(--accent) 12%, white);
      border: 1px solid var(--line);
      font-size: 1.1rem;
      flex: 0 0 42px;
    }
    .link-card-actions {
      display: flex;
      gap: 10px;
      flex-wrap: wrap;
      justify-content: flex-end;
    }
    .empty-links {
      padding: 18px;
      border-radius: 22px;
      border: 1px dashed var(--line-strong);
      color: var(--muted);
      text-align: center;
      background: rgba(255,255,255,0.56);
    }
    .preview-shell {
      position: sticky;
      top: 18px;
      background: rgba(255,255,255,0.72);
    }
    .preview-top {
      display: flex;
      align-items: center;
      justify-content: space-between;
      gap: 12px;
      margin-bottom: 14px;
    }
    .preview-device {
      border-radius: 36px;
      padding: 12px;
      background: #0b101d;
      box-shadow: inset 0 0 0 1px rgba(255,255,255,0.06), 0 24px 52px rgba(15,18,29,0.2);
    }
    .preview-screen {
      position: relative;
      min-height: 760px;
      border-radius: 30px;
      overflow: hidden;
      background: linear-gradient(180deg, #f7efe8, #efe7de);
      color: #fff;
    }
    .preview-bg-fallback,
    .preview-bg-avatar,
    .preview-bg-overlay {
      position: absolute;
      inset: 0;
      width: 100%;
      height: 100%;
    }
    .preview-bg-fallback { z-index: 0; background: #0b101d; }
    .preview-bg-avatar {
      z-index: 1;
      object-fit: cover;
      object-position: center top;
      display: none;
    }
    .preview-bg-overlay {
      z-index: 2;
      background: linear-gradient(180deg, rgba(11,16,29,0) 0%, rgba(11,16,29,0.2) 16%, rgba(11,16,29,0.6) 42%, rgba(11,16,29,0.94) 100%);
    }
    .preview-content {
      position: relative;
      z-index: 3;
      min-height: 760px;
      padding: 250px 14px 18px;
      display: flex;
      flex-direction: column;
      justify-content: flex-end;
      gap: 16px;
    }
    .preview-identity { text-align: center; }
    .preview-title {
      font-size: 2rem;
      font-weight: 800;
      line-height: 1.08;
      letter-spacing: -0.04em;
    }
    .preview-handle {
      margin-top: 4px;
      color: rgba(255,255,255,0.72);
      font-size: 0.92rem;
      font-weight: 500;
    }
    .preview-location {
      display: none;
      align-items: center;
      justify-content: center;
      gap: 6px;
      margin-top: 10px;
      color: rgba(255,255,255,0.85);
      font-size: 0.82rem;
      font-weight: 600;
    }
    .preview-cta-row {
      display: flex;
      align-items: center;
      gap: 10px;
    }
    .preview-btn-primary {
      flex: 1;
      min-height: 50px;
      padding: 0 18px;
      border-radius: 999px;
      background: #fff;
      color: #0b101d;
      display: flex;
      align-items: center;
      justify-content: center;
      font-weight: 800;
      font-size: 0.92rem;
      text-align: center;
    }
    .preview-btn-secondary {
      width: 50px;
      height: 50px;
      flex: 0 0 50px;
      border-radius: 999px;
      background: rgba(255,255,255,0.15);
      border: 1px solid rgba(255,255,255,0.1);
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 1.2rem;
    }
    .preview-bio {
      border-radius: 20px;
      padding: 16px;
      background: rgba(255,255,255,0.07);
      border: 1px solid rgba(255,255,255,0.08);
      backdrop-filter: blur(12px);
      font-size: 0.86rem;
      line-height: 1.58;
      color: rgba(255,255,255,0.9);
    }
    .preview-tags {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
      margin-top: 12px;
    }
    .preview-chip {
      display: inline-flex;
      align-items: center;
      gap: 6px;
      padding: 8px 11px;
      border-radius: 999px;
      background: rgba(255,255,255,0.1);
      border: 1px solid rgba(255,255,255,0.12);
      color: rgba(255,255,255,0.84);
      font-size: 0.76rem;
      font-weight: 700;
    }
    .preview-link-block {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 10px;
    }
    .preview-link-card {
      position: relative;
      border-radius: 18px;
      min-height: 140px;
      padding: 14px;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      background: rgba(255,255,255,0.09);
      border: 1px solid rgba(255,255,255,0.1);
      overflow: hidden;
    }
    .preview-link-card.featured {
      grid-column: 1 / -1;
      min-height: 120px;
    }
    .preview-link-icon {
      width: 34px;
      height: 34px;
      border-radius: 12px;
      background: rgba(255,255,255,0.18);
      display: inline-flex;
      align-items: center;
      justify-content: center;
      font-size: 1rem;
    }
    .preview-link-title {
      margin-top: auto;
      font-size: 0.95rem;
      font-weight: 800;
      line-height: 1.2;
    }
    .notice {
      display: none;
      padding: 16px 18px;
      border-radius: 20px;
      font-weight: 700;
      border: 1px solid transparent;
    }
    .notice.show { display: block; }
    .notice.success {
      background: rgba(34,197,94,0.1);
      color: #166534;
      border-color: rgba(34,197,94,0.18);
    }
    .notice.error {
      background: rgba(239,68,68,0.1);
      color: #991b1b;
      border-color: rgba(239,68,68,0.18);
    }
    .modal,
    .setup-overlay {
      position: fixed;
      inset: 0;
      background: rgba(10,12,20,0.42);
      backdrop-filter: blur(12px);
      padding: 24px;
      display: none;
      align-items: center;
      justify-content: center;
      z-index: 90;
    }
    .modal.show,
    .setup-overlay.show { display: flex; }
    .setup-card,
    .modal-card { width: min(100%, 880px); }
    .setup-grid,
    .add-grid {
      display: grid;
      grid-template-columns: repeat(2, 1fr);
      gap: 14px;
      margin-top: 18px;
    }
    .setup-option,
    .add-card {
      display: grid;
      gap: 16px;
      padding: 18px;
      border-radius: 24px;
      background: rgba(255,255,255,0.76);
      border: 1px solid var(--line);
      text-align: left;
    }
    .add-card { cursor: pointer; }
    .floating-save {
      position: fixed;
      left: 50%;
      bottom: 18px;
      transform: translateX(-50%) translateY(18px);
      width: min(760px, calc(100% - 24px));
      padding: 14px 16px;
      border-radius: 22px;
      background: rgba(18,18,23,0.94);
      color: white;
      display: flex;
      align-items: center;
      justify-content: space-between;
      gap: 14px;
      box-shadow: 0 24px 54px rgba(18,18,23,0.28);
      opacity: 0;
      pointer-events: none;
      transition: opacity 160ms ease, transform 160ms ease;
      z-index: 80;
    }
    .floating-save.show {
      opacity: 1;
      pointer-events: auto;
      transform: translateX(-50%) translateY(0);
    }
    .floating-save-copy {
      display: flex;
      align-items: center;
      gap: 12px;
      color: rgba(255,255,255,0.78);
      font-size: 0.94rem;
      font-weight: 700;
    }
    .save-state {
      width: 11px;
      height: 11px;
      border-radius: 999px;
      background: #fbbf24;
      box-shadow: 0 0 0 7px rgba(251,191,36,0.14);
      flex: 0 0 11px;
    }
    @media (max-width: 1120px) {
      .layout { grid-template-columns: 1fr; }
      .preview-shell { position: static; }
      .floating-save { flex-direction: column; align-items: stretch; }
      .topbar { align-items: flex-start; }
    }
    @media (max-width: 720px) {
      .shell { width: min(100%, calc(100% - 18px)); }
      .panel, .section-card, .preview-shell, .setup-card, .modal-card { padding: 18px; border-radius: 24px; }
      .split,
      .preset-grid,
      .setup-grid,
      .add-grid,
      .preview-link-block { grid-template-columns: 1fr; }
      .upload-card { grid-template-columns: 1fr; }
      .topbar { flex-direction: column; align-items: flex-start; }
      .top-actions { justify-content: flex-start; }
    }
  </style>
</head>
<body>
<?php if (!$status['ok']): ?>
  <div class="shell">
    <section class="card panel" style="max-width:760px;margin:14vh auto 0;">
      <span class="eyebrow"><span class="eyebrow-dot"></span>Profil</span>
      <h1>Chybí databázová migrace</h1>
      <p class="lede">Nejdřív je potřeba nasadit aktuální migraci pro nový profilový modul. Dokud se nespustí, editor se správně neotevře.</p>
    </section>
  </div>
<?php elseif (!$user): ?>
  <div class="shell">
    <section class="card panel" style="max-width:760px;margin:14vh auto 0;">
      <span class="eyebrow"><span class="eyebrow-dot"></span>Profil</span>
      <h1>Přihlaste se jako influencer</h1>
      <p class="lede">Editor profilu je dostupný po přihlášení. Jakmile budete přihlášení jako influencer, otevře se vám onboarding a následně celý editor.</p>
      <a class="primary" href="/login.php" style="margin-top:18px;">Přihlásit se</a>
    </section>
  </div>
<?php elseif ($user['is_company']): ?>
  <div class="shell">
    <section class="card panel" style="max-width:760px;margin:14vh auto 0;">
      <span class="eyebrow"><span class="eyebrow-dot"></span>Profil</span>
      <h1>Tenhle editor je jen pro tvůrce</h1>
      <p class="lede">Právě jste přihlášený jako firma. Pro správu veřejného profilu je potřeba influencer účet.</p>
      <a class="ghost" href="/vysledky" style="margin-top:18px;">Zpět do aplikace</a>
    </section>
  </div>
<?php else: ?>
  <main class="shell">
    <div class="topbar">
      <a class="brand" href="/"><span class="brand-wordmark">influ<span>enz.</span></span><span class="brand-copy">editor veřejného profilu</span></a>
      <div class="top-actions">
        <a class="ghost" href="/influencer-dashboard.php">Dashboard</a>
        <button class="ghost" type="button" id="copy-url">Kopírovat URL</button>
        <a class="ghost" href="#" id="open-live">Otevřít veřejný profil</a>
      </div>
    </div>

    <div class="layout" id="editor-shell" style="display:none;">
      <div class="stack">
        <section class="card panel" style="padding:18px;">
          <h2 style="font-size:1.8rem;margin:0 0 10px;">Váš veřejný profil</h2>
          <p class="lede" style="margin:0;font-size:0.95rem;">Upravte URL, headline, bio, avatar a odkazy, které budete sdílet se značkami.</p>
        </section>

        <section class="section-card">
          <div class="section-title">Základ profilu</div>
          <div class="section-subtitle">Tady nastavíte URL, headline, bio, lokaci a základní otevřenost spolupracím. Tohle je první vrstva celého profilu.</div>
          <div class="fields">
            <div class="split">
              <label>
                URL profilu
                <input id="slug" type="text" placeholder="např. marketa-fit">
                <span class="label-note">Profil poběží na adrese `/profile/tvůj-slug`.</span>
              </label>
              <label>
                Headline
                <input id="headline" type="text" placeholder="Např. Beauty creator, UGC a affiliate content pro CZ/SK značky">
              </label>
            </div>
            <label>
              Bio
              <textarea id="intro" placeholder="Krátce napište, co tvoříte, co vám sedí a proč se vám mají ozvat."></textarea>
            </label>
            <div class="split">
              <label>
                Město / země
                <input id="location_label" type="text" placeholder="Např. Praha, Česko">
              </label>
              <label>
                Zobrazení lokace
                <span class="toggle"><input id="show_location" type="checkbox" style="width:18px;height:18px;accent-color:var(--accent);"> Zobrazit lokaci na profilu</span>
              </label>
            </div>

          </div>
        </section>

        <section class="section-card">
          <div class="section-title">Avatar</div>
          <div class="section-subtitle">Nahrajte portrét jako soubor. Pokud chcete, můžete ho kdykoli změnit.</div>
          <div class="upload-card">
            <div class="avatar-preview" id="avatar-preview">IN</div>
            <div class="stack" style="gap:12px;">
              <div>
                <h3 style="font-size:1.15rem;">Portrét profilu</h3>
                <p class="section-subtitle" style="margin:6px 0 0;">Doporučený je výrazný portrét nebo cover, který funguje i na mobilu.</p>
              </div>
              <div class="top-actions">
                <label class="primary" for="avatar-file" style="cursor:pointer;"><i class="ph ph-upload-simple"></i>Nahrát soubor</label>
                <button class="ghost" type="button" id="remove-avatar">Odebrat fotku</button>
              </div>
              <span class="label-note" id="avatar-status">Povolené formáty: JPG, PNG, WEBP, GIF. Max. 5 MB.</span>
              <input id="avatar-url" type="hidden">
              <input id="avatar-file" class="hidden-input" type="file" accept="image/png,image/jpeg,image/webp,image/gif">
            </div>
          </div>
        </section>

        <section class="section-card">
          <div class="section-title">Vzhled stránky</div>
          <div class="section-subtitle">Default je připravený elegantní portrétní layout. Kdykoli ho můžete přepnout na jiný styl a doladit akcent.</div>
          <div class="fields">
            <div class="preset-grid">
              <button class="preset-card active" type="button" data-preset="portrait">
                <div class="preset-swatch" style="background:linear-gradient(180deg,#f6efe8,#efe7de);"></div>
                <strong>Portrét</strong>
                <div class="label-note">Elegantní, čistý, hlavně pro osobní brand.</div>
              </button>
              <button class="preset-card" type="button" data-preset="editorial">
                <div class="preset-swatch" style="background:linear-gradient(180deg,#f7f7f3,#efefe8);"></div>
                <strong>Editorial</strong>
                <div class="label-note">Čistý magazínový styl bez zbytečného šumu.</div>
              </button>
              <button class="preset-card" type="button" data-preset="spotlight">
                <div class="preset-swatch" style="background:linear-gradient(180deg,#fff6ef,#f3eeff);"></div>
                <strong>Spotlight</strong>
                <div class="label-note">Výraznější layout s jemnou energií a barvou.</div>
              </button>
              <button class="preset-card" type="button" data-preset="midnight">
                <div class="preset-swatch" style="background:linear-gradient(180deg,#12162b,#090b16);"></div>
                <strong>Midnight</strong>
                <div class="label-note">Temnější luxusní vzhled pro fashion a premium.</div>
              </button>
            </div>
            <div class="split">
              <label>
                Barva akcentu
                <div class="accent-field">
                  <button class="accent-swatch" type="button" id="accent-swatch" aria-label="Vybrat barvu"></button>
                  <input id="accent_hex" class="accent-hex" type="text" value="#f36b4f" maxlength="7" placeholder="#f36b4f">
                  <input id="accent_color" class="hidden-input" type="color" value="#f36b4f">
                </div>
              </label>
              <label>
                Barva pozadí
                <div class="accent-field">
                  <button class="accent-swatch" type="button" id="bg-swatch" aria-label="Vybrat barvu pozadí"></button>
                  <input id="bg_hex" class="accent-hex" type="text" value="" maxlength="7" placeholder="Výchozí téma">
                  <input id="bg_color" class="hidden-input" type="color" value="#11152a">
                </div>
                <span class="label-note" style="margin-top:4px;">Nechte prázdné pro výchozí barevné téma.</span>
              </label>
              <label>
                Publikace
                <span class="toggle"><input id="is_published" type="checkbox" style="width:18px;height:18px;accent-color:var(--accent);"> Profil je veřejně viditelný</span>
              </label>
            </div>
            <input id="theme_preset" type="hidden" value="portrait">
          </div>
        </section>

        <section class="section-card">
          <div class="section-title">Kontakt</div>
          <div class="section-subtitle">Nastavte, jak se vám budou značky moci ozvat — přes formulář, e-mail nebo odkaz.</div>
          <div class="fields">
            <label>
              Primární CTA
              <select id="primary_cta_mode">
                <option value="link">Odkaz</option>
                <option value="form">Kontaktní formulář</option>
                <option value="both">Odkaz + formulář</option>
              </select>
            </label>
            <label id="primary-cta-link-container" style="display:none;">
              Odkaz
              <select id="primary_cta_picker">
                <option value="">Nejdřív přidejte odkaz</option>
              </select>
            </label>
            <div class="split">
              <label>
                Kontaktní e-mail
                <input id="public_email" type="email" placeholder="spoluprace@email.cz">
              </label>
              <label>
                Telefon
                <input id="public_phone" type="text" placeholder="+420 ...">
              </label>
            </div>
            <label>
              WhatsApp
              <input id="public_whatsapp" type="text" placeholder="+420 ...">
            </label>
          </div>
        </section>

        <section class="section-card">
          <div class="link-builder-header">
            <div>
              <div class="section-title">Odkazy a sekce</div>
              <div class="section-subtitle" style="margin-bottom:0;">Přidejte odkazy podle typu. Každý blok má vlastní ikonku a může být i zvýrazněný.</div>
            </div>
            <button class="primary" type="button" id="open-add-link"><i class="ph ph-plus"></i>Nový link / sekce</button>
          </div>
          <div id="links-list" class="link-list"></div>
          <div class="empty-links" id="empty-links">Zatím tu není žádný odkaz. Přidejte sociální sítě, shop, web nebo vlastní tlačítko.</div>
        </section>

        <div class="notice" id="notice"></div>
      </div>

      <aside class="preview-shell">
        <div class="preview-top">
          <div>
            <div class="section-title" style="margin-bottom:4px;">Živý náhled</div>
            <div class="label-note">Takhle bude vypadat váš profil.</div>
          </div>
        </div>
        <div class="preview-device">
          <div class="preview-screen" id="preview-screen">
            <div class="preview-bg-fallback" id="preview-bg-fallback"></div>
            <img class="preview-bg-avatar" id="preview-bg-avatar" src="" alt="">
            <div class="preview-bg-overlay"></div>
            <div class="preview-content">
              <div class="preview-identity">
                <div class="preview-title" id="preview-headline">Váš headline</div>
                <div class="preview-handle" id="preview-handle">@handle</div>
                <div class="preview-location" id="preview-location"></div>
              </div>
              <div class="preview-cta-row" id="preview-cta"></div>
              <div class="preview-bio" id="preview-intro">
                <div id="preview-intro-copy">Sem se propsalo bio a value proposition.</div>
                <div class="preview-tags" id="preview-tags"></div>
              </div>
              <div class="preview-link-block" id="preview-link-groups"></div>
            </div>
          </div>
        </div>
      </aside>
    </div>
  </main>

  <div class="setup-overlay" id="setup-overlay">
    <div class="setup-card">
      <div>
        <span class="eyebrow"><span class="eyebrow-dot"></span>Začínáme</span>
        <h1>Jak chcete profil založit?</h1>
        <p class="lede">Při první tvorbě si můžete profil nechat předvyplnit z Linktree, nebo začít od čistého stolu a vše si postavit ručně.</p>
      </div>
      <div class="setup-grid">
        <div class="setup-option">
          <div class="icon-circle"><i class="ph ph-sparkle"></i></div>
          <div>
            <h2>Vytvořit nový</h2>
            <p class="section-subtitle" style="margin:6px 0 0;">Otevřeme editor s předvyplněným jménem, bio a daty z vašeho účtu. Pak si jen doladíte vzhled, CTA a odkazy.</p>
          </div>
          <button class="primary" type="button" id="start-new">Vytvořit nový profil</button>
        </div>
        <div class="setup-option">
          <div class="icon-circle"><i class="ph ph-link"></i></div>
          <div>
            <h2>Načíst profil z Linktree</h2>
            <p class="section-subtitle" style="margin:6px 0 0;">Vložte URL svého Linktree. Zkusím stáhnout headline, obrázek a odkazy a rovnou je přenesu do editoru.</p>
          </div>
          <label>
            URL z Linktree
            <input id="linktree-url" type="url" placeholder="https://linktr.ee/...">
          </label>
          <button class="primary" type="button" id="import-linktree">Načíst z Linktree</button>
          <span class="label-note" id="linktree-status"></span>
        </div>
      </div>
    </div>
  </div>

  <div class="modal" id="add-link-modal">
    <div class="modal-card">
      <div style="display:flex;align-items:start;justify-content:space-between;gap:12px;">
        <div>
          <div class="section-title">Nový link / sekce</div>
          <h2 style="font-size:2rem;">Co chcete přidat?</h2>
          <p class="section-subtitle" style="margin:8px 0 0;">Vyberte typ bloku. Editor vám podle toho rovnou předchystá správná pole i ikonku.</p>
        </div>
        <button class="ghost" type="button" id="close-add-link">Zavřít</button>
      </div>
      <div class="add-grid">
        <button class="add-card" type="button" data-add-type="social">
          <div class="icon-circle"><i class="ph ph-instagram-logo"></i></div>
          <strong>Sociální sítě</strong>
          <span class="label-note">Instagram, TikTok, YouTube, Spotify a další.</span>
        </button>
        <button class="add-card" type="button" data-add-type="shop">
          <div class="icon-circle"><i class="ph ph-shopping-bag-open"></i></div>
          <strong>Obchody</strong>
          <span class="label-note">Shop, affiliate landing page nebo produktový drop.</span>
        </button>
        <button class="add-card" type="button" data-add-type="web">
          <div class="icon-circle"><i class="ph ph-globe-hemisphere-west"></i></div>
          <strong>Web</strong>
          <span class="label-note">Web, newsletter, media kit nebo Notion.</span>
        </button>
        <button class="add-card" type="button" data-add-type="custom">
          <div class="icon-circle"><i class="ph ph-squares-four"></i></div>
          <strong>Jiné</strong>
          <span class="label-note">Vlastní tlačítko, booking, formulář nebo cokoliv dalšího.</span>
        </button>
      </div>
    </div>
  </div>

  <template id="link-template">
    <div class="link-card">
      <div class="link-card-top">
        <div class="link-kind">
          <span class="icon-circle"><i class="ph ph-link" data-link-icon></i></span>
          <div>
            <div data-link-kind-title>Nový odkaz</div>
            <div class="label-note" data-link-kind-copy>Vyplňte název a URL.</div>
          </div>
        </div>
        <div class="link-card-actions">
          <label class="toggle" style="padding:10px 12px;min-height:auto;">
            <input data-field="is_featured" type="checkbox" style="width:18px;height:18px;accent-color:var(--accent);">
            Zvýraznit
          </label>
          <button class="ghost" type="button" data-remove-link>Smazat</button>
        </div>
      </div>
      <div class="fields">
        <input data-field="link_type" type="hidden" value="custom">
        <div class="split">
          <label>
            Nadpis tlačítka
            <input data-field="title" type="text" placeholder="Např. Můj shop nebo Instagram">
          </label>
          <label>
            URL
            <input data-field="url" type="url" placeholder="https://...">
          </label>
        </div>
        <label data-platform-wrap>
          Platforma
          <select data-field="platform">
            <option value="instagram">Instagram</option>
            <option value="tiktok">TikTok</option>
            <option value="youtube">YouTube</option>
            <option value="facebook">Facebook</option>
            <option value="x">X / Twitter</option>
            <option value="linkedin">LinkedIn</option>
            <option value="spotify">Spotify</option>
            <option value="pinterest">Pinterest</option>
            <option value="other">Jiné</option>
          </select>
        </label>
      </div>
    </div>
  </template>

  <div class="floating-save" id="floating-save">
    <div class="floating-save-copy">
      <span class="save-state"></span>
      <span id="save-copy">Máte neuložené změny.</span>
    </div>
    <div class="top-actions" style="margin-left:auto;">
      <button class="ghost" type="button" id="save-copy-url" style="display:none;">Kopírovat URL</button>
      <button class="primary" type="button" id="save-profile">Uložit změny</button>
    </div>
  </div>

  <script>
    const state = { account: null, exists: false, loaded: false, dirty: false, themePreset: 'portrait' };

    const els = {
      editorShell: document.getElementById('editor-shell'),
      setupOverlay: document.getElementById('setup-overlay'),
      linktreeUrl: document.getElementById('linktree-url'),
      linktreeStatus: document.getElementById('linktree-status'),
      startNew: document.getElementById('start-new'),
      importLinktree: document.getElementById('import-linktree'),
      reimportLinktree: document.getElementById('reimport-linktree'),
      slug: document.getElementById('slug'),
      headline: document.getElementById('headline'),
      intro: document.getElementById('intro'),
      locationLabel: document.getElementById('location_label'),
      showLocation: document.getElementById('show_location'),
      accentColor: document.getElementById('accent_color'),
      accentHex: document.getElementById('accent_hex'),
      accentSwatch: document.getElementById('accent-swatch'),
      bgColor: document.getElementById('bg_color'),
      bgHex: document.getElementById('bg_hex'),
      bgSwatch: document.getElementById('bg-swatch'),
      themePreset: document.getElementById('theme_preset'),
      publicEmail: document.getElementById('public_email'),
      publicPhone: document.getElementById('public_phone'),
      publicWhatsapp: document.getElementById('public_whatsapp'),
      isPublished: document.getElementById('is_published'),
      primaryCtaMode: document.getElementById('primary_cta_mode'),
      primaryCtaLinkContainer: document.getElementById('primary-cta-link-container'),
      primaryCtaPicker: document.getElementById('primary_cta_picker'),
      avatarUrl: document.getElementById('avatar-url'),
      avatarFile: document.getElementById('avatar-file'),
      avatarStatus: document.getElementById('avatar-status'),
      avatarPreview: document.getElementById('avatar-preview'),
      removeAvatar: document.getElementById('remove-avatar'),
      linksList: document.getElementById('links-list'),
      emptyLinks: document.getElementById('empty-links'),
      addLinkModal: document.getElementById('add-link-modal'),
      openAddLink: document.getElementById('open-add-link'),
      closeAddLink: document.getElementById('close-add-link'),
      linkTemplate: document.getElementById('link-template'),
      notice: document.getElementById('notice'),
      openLive: document.getElementById('open-live'),
      copyUrl: document.getElementById('copy-url'),
      floatingSave: document.getElementById('floating-save'),
      saveProfile: document.getElementById('save-profile'),
      saveCopyUrl: document.getElementById('save-copy-url'),
      saveCopy: document.getElementById('save-copy'),
      previewScreen: document.getElementById('preview-screen'),
      previewBgFallback: document.getElementById('preview-bg-fallback'),
      previewBgAvatar: document.getElementById('preview-bg-avatar'),
      previewHeadline: document.getElementById('preview-headline'),
      previewHandle: document.getElementById('preview-handle'),
      previewLocation: document.getElementById('preview-location'),
      previewIntro: document.getElementById('preview-intro'),
      previewIntroCopy: document.getElementById('preview-intro-copy'),
      previewTags: document.getElementById('preview-tags'),
      previewCta: document.getElementById('preview-cta'),
      previewLinkGroups: document.getElementById('preview-link-groups'),
      presetCards: [...document.querySelectorAll('[data-preset]')],
      addCards: [...document.querySelectorAll('[data-add-type]')],
    };

    const presets = {
      portrait: { bg: 'linear-gradient(180deg, #f7efe8, #efe7de)', button: '#ffffff', buttonText: '#0f1222' },
      editorial: { bg: 'linear-gradient(180deg, #f7f7f3, #efefe8)', button: '#101010', buttonText: '#ffffff' },
      spotlight: { bg: 'linear-gradient(180deg, #fff6ef, #f1edff)', button: '#14142a', buttonText: '#ffffff' },
      midnight: { bg: 'linear-gradient(180deg, #11152a, #0b0d16)', button: '#ffffff', buttonText: '#0f1222' },
    };

    const linkTypeMeta = {
      social: { label: 'Sociální síť', copy: 'Profil nebo obsahová platforma', icon: 'ph-instagram-logo' },
      shop: { label: 'Obchod', copy: 'Produkt, landing page nebo affiliate shop', icon: 'ph-shopping-bag-open' },
      web: { label: 'Web', copy: 'Web, newsletter, media kit nebo Notion', icon: 'ph-globe-hemisphere-west' },
      custom: { label: 'Jiné', copy: 'Vlastní tlačítko, booking nebo formulář', icon: 'ph-squares-four' },
    };

    const platformIcons = {
      instagram: 'ph-instagram-logo',
      tiktok: 'ph-tiktok-logo',
      youtube: 'ph-youtube-logo',
      facebook: 'ph-facebook-logo',
      x: 'ph-x-logo',
      linkedin: 'ph-linkedin-logo',
      spotify: 'ph-spotify-logo',
      pinterest: 'ph-pinterest-logo',
      other: 'ph-link-simple',
    };

    function escapeHtml(value) {
      return String(value || '')
        .replaceAll('&', '&amp;')
        .replaceAll('<', '&lt;')
        .replaceAll('>', '&gt;')
        .replaceAll('"', '&quot;')
        .replaceAll("'", '&#39;');
    }

    function normalizeUrl(value) {
      const trimmed = String(value || '').trim();
      if (!trimmed) return '';
      return /^https?:\/\//i.test(trimmed) ? trimmed : `https://${trimmed.replace(/^\/+/, '')}`;
    }

    function initials(value) {
      const text = String(value || '').trim();
      if (!text) return 'IN';
      const bits = text.split(/\s+/).filter(Boolean).slice(0, 2).map(part => part[0]).join('');
      return (bits || text.slice(0, 2)).toUpperCase();
    }

    function slugify(value) {
      return String(value || '')
        .normalize('NFD')
        .replace(/[\u0300-\u036f]/g, '')
        .toLowerCase()
        .replace(/[^a-z0-9._-]+/g, '-')
        .replace(/^-+|-+$/g, '')
        .slice(0, 60);
    }

    function showNotice(message, type = 'success') {
      if (!message) {
        els.notice.className = 'notice';
        els.notice.textContent = '';
        return;
      }
      els.notice.className = `notice show ${type}`;
      els.notice.textContent = message;
    }

    function syncAccentUi(rawValue) {
      const normalized = /^#[0-9a-f]{6}$/i.test(String(rawValue || '').trim()) ? String(rawValue).trim().toLowerCase() : '#f36b4f';
      document.documentElement.style.setProperty('--accent', normalized);
      els.accentColor.value = normalized;
      els.accentHex.value = normalized;
      els.accentSwatch.style.background = normalized;
      return normalized;
    }

    function syncBgUi(rawValue) {
      const valid = /^#[0-9a-f]{6}$/i.test(String(rawValue || '').trim());
      const color = valid ? String(rawValue).trim().toLowerCase() : '';
      els.bgHex.value = color;
      els.bgSwatch.style.background = color || 'linear-gradient(135deg,#11152a,#f6efe8)';
      els.bgColor.value = color || '#11152a';
      return color;
    }

    function markDirty() {
      if (!state.loaded) return;
      state.dirty = true;
      els.floatingSave.classList.add('show');
      els.saveCopy.textContent = 'Máte neuložené změny.';
      syncPublicUrl();
      renderPreview();
    }

    function markSaved() {
      state.dirty = false;
      els.floatingSave.classList.remove('show');
      syncPublicUrl();
    }

    function syncPublicUrl() {
      const slug = slugify(els.slug.value);
      els.openLive.href = slug ? `/profile/${slug}` : '#';
      els.saveCopyUrl.style.display = slug ? 'inline-flex' : 'none';
    }

    function createTagEditor(root) {
      const list = root.querySelector('[data-tag-list]');
      const input = root.querySelector('[data-tag-input]');
      const add = root.querySelector('[data-tag-add]');
      let tags = [];

      function render() {
        list.innerHTML = tags.map((tag, index) => `<span class="tag">${escapeHtml(tag)}<button type="button" data-index="${index}"><i class="ph ph-x"></i></button></span>`).join('');
        list.querySelectorAll('button').forEach((button) => {
          button.addEventListener('click', () => {
            tags.splice(Number(button.dataset.index), 1);
            render();
            markDirty();
          });
        });
      }

      function addTag(raw) {
        const value = String(raw || '').trim();
        if (!value) return;
        if (tags.some(tag => tag.toLowerCase() === value.toLowerCase())) {
          input.value = '';
          return;
        }
        tags.push(value);
        input.value = '';
        render();
        markDirty();
      }

      add.addEventListener('click', () => addTag(input.value));
      input.addEventListener('keydown', (event) => {
        if (event.key === 'Enter' || event.key === ',') {
          event.preventDefault();
          addTag(input.value.replace(/,$/, ''));
        }
      });

      return {
        set(nextTags) {
          tags = Array.isArray(nextTags) ? nextTags.filter(Boolean).map(tag => String(tag).trim()).filter(Boolean) : [];
          render();
        },
        get() {
          return [...tags];
        },
      };
    }



    function defaultLinkForType(type) {
      return {
        link_type: type,
        platform: type === 'social' ? 'instagram' : '',
        title: type === 'social' ? 'Instagram' : type === 'shop' ? 'Můj shop' : type === 'web' ? 'Můj web' : 'Vlastní odkaz',
        url: '',
        is_featured: false,
      };
    }

    function platformLabel(platform) {
      const map = {
        instagram: 'Instagram',
        tiktok: 'TikTok',
        youtube: 'YouTube',
        facebook: 'Facebook',
        x: 'X / Twitter',
        linkedin: 'LinkedIn',
        spotify: 'Spotify',
        pinterest: 'Pinterest',
        other: 'Jiné',
      };
      return map[platform] || 'Jiné';
    }

    function currentLinks() {
      return [...els.linksList.children].map((card) => {
        const payload = {};
        card.querySelectorAll('[data-field]').forEach((field) => {
          payload[field.dataset.field] = field.type === 'checkbox' ? field.checked : field.value.trim();
        });
        payload.url = normalizeUrl(payload.url);
        return payload;
      }).filter((link) => link.title && link.url);
    }

    function refreshCtaPicker() {
      const current = els.primaryCtaPicker.value;
      const links = currentLinks();
      if (!links.length) {
        els.primaryCtaPicker.innerHTML = '<option value="">Nejdřív přidejte odkaz</option>';
        return;
      }
      els.primaryCtaPicker.innerHTML = links.map((link) => `<option value="${escapeHtml(link.url)}">${escapeHtml(link.title)}</option>`).join('');
      if (links.some(link => link.url === current)) {
        els.primaryCtaPicker.value = current;
      }
    }

    function updateLinkCardVisual(card) {
      const type = card.querySelector('[data-field="link_type"]').value;
      const platform = card.querySelector('[data-field="platform"]').value;
      const meta = linkTypeMeta[type] || linkTypeMeta.custom;
      const icon = type === 'social' ? (platformIcons[platform] || 'ph-link-simple') : meta.icon;
      card.querySelector('[data-link-icon]').className = `ph ${icon}`;
      card.querySelector('[data-link-kind-title]').textContent = meta.label;
      card.querySelector('[data-link-kind-copy]').textContent = type === 'social' ? `Platforma: ${platformLabel(platform)}` : meta.copy;
      card.querySelector('[data-platform-wrap]').style.display = type === 'social' ? 'grid' : 'none';
    }

    function refreshLinksUi() {
      els.emptyLinks.style.display = els.linksList.children.length ? 'none' : 'block';
      refreshCtaPicker();
      renderPreview();
    }

    function createLinkCard(data = {}) {
      const card = els.linkTemplate.content.firstElementChild.cloneNode(true);
      card.querySelectorAll('[data-field]').forEach((field) => {
        const key = field.dataset.field;
        if (field.type === 'checkbox') {
          field.checked = Boolean(data[key]);
        } else if (data[key] !== undefined) {
          field.value = data[key];
        }
        field.addEventListener('input', () => {
          updateLinkCardVisual(card);
          markDirty();
          refreshLinksUi();
        });
        field.addEventListener('change', () => {
          updateLinkCardVisual(card);
          markDirty();
          refreshLinksUi();
        });
      });
      card.querySelector('[data-remove-link]').addEventListener('click', () => {
        card.remove();
        markDirty();
        refreshLinksUi();
      });
      updateLinkCardVisual(card);
      return card;
    }

    function setLinks(links) {
      els.linksList.innerHTML = '';
      (Array.isArray(links) ? links : []).forEach((link) => {
        els.linksList.appendChild(createLinkCard(link));
      });
      refreshLinksUi();
    }

    function orderedPreviewLinks(links) {
      const featured = [];
      const regular = [];
      links.forEach((link) => {
        if (link.is_featured) {
          featured.push(link);
        } else {
          regular.push(link);
        }
      });
      return [...featured, ...regular];
    }

    function renderPreview() {
      const preset = presets[state.themePreset] || presets.portrait;
      const customBg = /^#[0-9a-f]{6}$/i.test(els.bgHex?.value?.trim() || '') ? els.bgHex.value.trim() : '';
      const headline = els.headline.value.trim() || state.account?.full_name || 'Váš headline';
      const intro = els.intro.value.trim() || state.account?.bio || 'Sem se propsalo bio a value proposition.';
      const accent = syncAccentUi(els.accentColor.value || els.accentHex.value || '#f36b4f');
      const avatarUrl = els.avatarUrl.value.trim();
      const ctaMode = els.primaryCtaMode.value;
      const links = currentLinks();
      const ctaLink = links.find(link => link.url === els.primaryCtaPicker.value) || links[0] || null;
      const handle = state.account?.instagram ? `@${state.account.instagram}` : state.account?.tiktok ? `@${state.account.tiktok}` : state.account?.twitter ? `@${state.account.twitter}` : '@handle';
      const locationText = els.locationLabel.value.trim();

      els.previewScreen.style.background = customBg || preset.bg;
      els.previewBgFallback.style.background = `radial-gradient(circle at top left, color-mix(in srgb, ${accent} 30%, transparent), transparent 60%), #0b101d`;
      if (avatarUrl) {
        els.previewBgAvatar.src = avatarUrl;
        els.previewBgAvatar.style.display = 'block';
      } else {
        els.previewBgAvatar.removeAttribute('src');
        els.previewBgAvatar.style.display = 'none';
      }

      els.previewHeadline.textContent = headline;
      els.previewHandle.textContent = handle;

      if (els.showLocation.checked && locationText) {
        els.previewLocation.style.display = 'inline-flex';
        els.previewLocation.innerHTML = `<i class="ph ph-map-pin"></i><span>${escapeHtml(locationText)}</span>`;
      } else {
        els.previewLocation.style.display = 'none';
        els.previewLocation.innerHTML = '';
      }

      els.previewIntroCopy.textContent = intro;
      els.previewTags.innerHTML = '';

      const ctas = [];
      if (ctaMode === 'form') {
        ctas.push('<div class="preview-btn-primary">Napsat pro spolupráci</div>');
      } else if ((ctaMode === 'link' || ctaMode === 'both') && ctaLink) {
        ctas.push(`<div class="preview-btn-primary" style="background:${preset.button};color:${preset.buttonText};">${escapeHtml(ctaLink.title)}</div>`);
      } else if (!ctaLink && ctaMode !== 'form') {
        ctas.push('<div class="preview-btn-primary">Ukázkový odkaz</div>');
      }
      if (ctaMode === 'form' || ctaMode === 'both') {
        ctas.push('<div class="preview-btn-secondary"><i class="ph ph-envelope"></i></div>');
      }
      els.previewCta.innerHTML = ctas.join('');

      els.previewLinkGroups.innerHTML = orderedPreviewLinks(links).map((link) => {
        const icon = link.link_type === 'social' ? (platformIcons[link.platform] || 'ph-link-simple') : (linkTypeMeta[link.link_type]?.icon || 'ph-link-simple');
        return `
          <div class="preview-link-card${link.is_featured ? ' featured' : ''}" style="background:linear-gradient(180deg, rgba(255,255,255,0.08), color-mix(in srgb, ${accent} 18%, rgba(255,255,255,0.08)));">
            <div class="preview-link-icon"><i class="ph ${icon}"></i></div>
            <div class="preview-link-title">${escapeHtml(link.title)}</div>
          </div>
        `;
      }).join('');
    }

    function setAvatar(url) {
      els.avatarUrl.value = url || '';
      if (url) {
        els.avatarPreview.innerHTML = `<img src="${url}" alt="avatar">`;
      } else {
        els.avatarPreview.textContent = initials(els.headline.value.trim() || state.account?.full_name || 'IN');
      }
      renderPreview();
    }

    async function uploadAvatar(file) {
      const formData = new FormData();
      formData.append('avatar', file);
      if (els.avatarStatus) els.avatarStatus.textContent = 'Nahrávám avatar…';
      const response = await fetch('/profile/api/upload-avatar.php', {
        method: 'POST',
        credentials: 'include',
        body: formData,
      });
      const data = await response.json();
      if (!response.ok) {
        throw new Error(data.error || 'Avatar se nepodařilo nahrát.');
      }
      setAvatar(data.url);
      if (els.avatarFile) els.avatarFile.value = '';
      if (state.loaded && slugify(els.slug.value) && els.headline.value.trim()) {
        await saveProfile({ successMessage: 'Avatar je nahraný a uložený.' });
      } else {
        if (els.avatarStatus) els.avatarStatus.textContent = 'Avatar je nahraný. Uložte profil.';
        markDirty();
      }
    }

    function showSetup(show) {
      els.setupOverlay.classList.toggle('show', show);
      els.editorShell.style.display = show ? 'none' : 'grid';
    }

    function populateForm(data) {
      state.account = data.account || {};
      state.exists = Boolean(data.exists);
      const page = data.page || {};
      els.slug.value = page.slug || '';
      els.headline.value = page.headline || data.account.full_name || '';
      els.intro.value = page.intro || data.account.bio || '';
      els.locationLabel.value = (page.audience_regions && page.audience_regions[0]) || [data.account.primary_city, data.account.primary_location].filter(Boolean).join(', ');
      els.showLocation.checked = Boolean(page.show_location);


      syncAccentUi(page.accent_color || '#f36b4f');
      syncBgUi(page.bg_color || '');
      els.publicEmail.value = page.public_email || data.account.contact_email || data.account.email || '';
      els.publicPhone.value = page.public_phone || '';
      els.publicWhatsapp.value = page.public_whatsapp || '';
      els.isPublished.checked = Boolean(page.is_published);
      els.primaryCtaMode.value = page.primary_cta_mode || 'link';
      setLinks(data.links || []);
      setAvatar(page.avatar_url || '');
      applyPreset(page.theme_preset || 'portrait', false);
      state.loaded = true;
      refreshCtaPicker();
      if (page.primary_cta_url) {
        els.primaryCtaPicker.value = page.primary_cta_url;
      }
      syncPublicUrl();
      renderPreview();
      const mode = els.primaryCtaMode.value;
      els.primaryCtaLinkContainer.style.display = (mode === 'link' || mode === 'both') ? 'grid' : 'none';
    }

    function collectPayload() {
      return {
        slug: slugify(els.slug.value),
        headline: els.headline.value.trim(),
        intro: els.intro.value.trim(),
        location_label: els.locationLabel.value.trim(),
        show_location: els.showLocation.checked,
        preferred_categories: [],
        preferred_collab_types: [],
        audience_regions: els.locationLabel.value.trim() ? [els.locationLabel.value.trim()] : [],


        avatar_url: els.avatarUrl.value.trim(),
        accent_color: els.accentColor.value,
        bg_color: /^#[0-9a-f]{6}$/i.test(els.bgHex.value.trim()) ? els.bgHex.value.trim().toLowerCase() : '',
        theme_preset: els.themePreset.value,
        public_email: els.publicEmail.value.trim(),
        public_phone: els.publicPhone.value.trim(),
        public_whatsapp: els.publicWhatsapp.value.trim(),
        is_published: els.isPublished.checked,
        primary_cta_mode: els.primaryCtaMode.value,
        primary_cta_url: els.primaryCtaPicker.value || '',
        primary_cta_label: (currentLinks().find(link => link.url === (els.primaryCtaPicker.value || '')) || {}).title || '',
        links: currentLinks(),
      };
    }

    async function saveProfile(options = {}) {
      const payload = collectPayload();
      if (!payload.slug) {
        showNotice('Vyplňte prosím URL profilu.', 'error');
        return false;
      }
      if (!payload.headline) {
        showNotice('Vyplňte headline profilu.', 'error');
        return false;
      }

      els.saveProfile.disabled = true;
      els.saveCopy.textContent = 'Ukládám změny…';
      try {
        const response = await fetch('/profile/api/save.php', {
          method: 'POST',
          credentials: 'include',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(payload),
        });
        const data = await response.json();
        if (!response.ok) {
          throw new Error(data.error || 'Profil se nepodařilo uložit.');
        }
        els.slug.value = data.slug;
        state.exists = true;
        markSaved();
        syncPublicUrl();
        els.avatarStatus.textContent = els.avatarUrl.value ? 'Avatar je uložený.' : 'Povolené formáty: JPG, PNG, WEBP, GIF. Max. 5 MB.';
        showNotice(options.successMessage || 'Profil je uložený.', 'success');
        return true;
      } catch (error) {
        showNotice(error.message || 'Profil se nepodařilo uložit.', 'error');
        els.saveCopy.textContent = 'Uložení selhalo.';
        return false;
      } finally {
        els.saveProfile.disabled = false;
      }
    }

    async function importLinktreeToEditor(url) {
      els.linktreeStatus.textContent = 'Načítám Linktree…';
      const response = await fetch('/profile/api/import-linktree.php', {
        method: 'POST',
        credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ url }),
      });
      const data = await response.json();
      if (!response.ok) {
        throw new Error(data.error || 'Linktree profil se nepodařilo načíst.');
      }
      const imported = data.profile || {};
      if (imported.slug) els.slug.value = imported.slug;
      if (imported.headline) els.headline.value = imported.headline;
      if (imported.intro) els.intro.value = imported.intro;
      if (imported.avatar_url) setAvatar(imported.avatar_url);
      if (Array.isArray(imported.links)) setLinks(imported.links);
      els.linktreeStatus.textContent = 'Linktree je načtené. Všechno můžete ještě upravit.';
      showSetup(false);
      state.loaded = true;
      markDirty();
      showNotice('Profil jsem předvyplnil z Linktree. Před publikací si ho ještě zkontrolujte.', 'success');
    }

    async function loadProfile() {
      const response = await fetch('/profile/api/load.php', { credentials: 'include' });
      const data = await response.json();
      if (!response.ok) {
        throw new Error(data.error || 'Profil se nepodařilo načíst.');
      }
      populateForm(data);
      showSetup(!data.exists);
      markSaved();
    }

    function copyPublicUrl() {
      const slug = slugify(els.slug.value);
      if (!slug) return;
      const url = `${window.location.origin}/profile/${slug}`;
      navigator.clipboard.writeText(url).then(() => {
        showNotice('Veřejná URL profilu je ve schránce.', 'success');
      }).catch(() => {
        showNotice(url, 'success');
      });
    }

    function applyPreset(preset, mark = true) {
      state.themePreset = preset;
      els.themePreset.value = preset;
      els.presetCards.forEach((card) => card.classList.toggle('active', card.dataset.preset === preset));
      if (mark) {
        markDirty();
      } else {
        renderPreview();
      }
    }

    if (els.startNew) els.startNew.addEventListener('click', () => {
      showSetup(false);
      state.loaded = true;
      renderPreview();
    });

    if (els.importLinktree) els.importLinktree.addEventListener('click', async () => {
      const url = els.linktreeUrl?.value.trim() || '';
      if (!url) {
        if (els.linktreeStatus) els.linktreeStatus.textContent = 'Nejdřív vložte URL.';
        return;
      }
      try {
        await importLinktreeToEditor(url);
      } catch (error) {
        if (els.linktreeStatus) els.linktreeStatus.textContent = error.message || 'Linktree se nepodařilo načíst.';
      }
    });

    if (els.reimportLinktree) els.reimportLinktree.addEventListener('click', () => {
      if (els.linktreeStatus) els.linktreeStatus.textContent = '';
      showSetup(true);
    });

    if (els.openAddLink) els.openAddLink.addEventListener('click', () => els.addLinkModal.classList.add('show'));
    if (els.closeAddLink) els.closeAddLink.addEventListener('click', () => els.addLinkModal.classList.remove('show'));
    if (els.addLinkModal) els.addLinkModal.addEventListener('click', (event) => {
      if (event.target === els.addLinkModal) {
        els.addLinkModal.classList.remove('show');
      }
    });

    if (els.addCards) els.addCards.forEach((button) => {
      if (button) button.addEventListener('click', () => {
        if (els.addLinkModal) els.addLinkModal.classList.remove('show');
        if (els.linksList) els.linksList.appendChild(createLinkCard(defaultLinkForType(button.dataset.addType)));
        refreshLinksUi();
        markDirty();
      });
    });

    if (els.avatarFile) els.avatarFile.addEventListener('change', async () => {
      const file = els.avatarFile.files?.[0];
      if (!file) return;
      try {
        await uploadAvatar(file);
      } catch (error) {
        els.avatarStatus.textContent = error.message || 'Avatar se nepodařilo nahrát.';
        showNotice(error.message || 'Avatar se nepodařilo nahrát.', 'error');
      }
    });

    if (els.removeAvatar) els.removeAvatar.addEventListener('click', () => {
      setAvatar('');
      if (els.avatarStatus) els.avatarStatus.textContent = 'Avatar byl odebraný. Uložte změny.';
      markDirty();
    });

    if (els.accentSwatch) els.accentSwatch.addEventListener('click', () => els.accentColor.click());
    if (els.accentColor) els.accentColor.addEventListener('input', () => {
      syncAccentUi(els.accentColor.value);
      markDirty();
    });
    if (els.accentHex) els.accentHex.addEventListener('input', () => {
      if (/^#[0-9a-f]{6}$/i.test(els.accentHex.value.trim())) {
        syncAccentUi(els.accentHex.value.trim());
        markDirty();
      }
    });
    if (els.accentHex) els.accentHex.addEventListener('blur', () => {
      syncAccentUi(els.accentHex.value.trim());
      renderPreview();
    });

    if (els.bgSwatch) els.bgSwatch.addEventListener('click', () => els.bgColor.click());
    if (els.bgColor) els.bgColor.addEventListener('input', () => {
      syncBgUi(els.bgColor.value);
      markDirty();
    });
    if (els.bgHex) els.bgHex.addEventListener('input', () => {
      if (els.bgHex.value.trim() === '') { syncBgUi(''); markDirty(); return; }
      if (/^#[0-9a-f]{6}$/i.test(els.bgHex.value.trim())) {
        syncBgUi(els.bgHex.value.trim());
        markDirty();
      }
    });
    if (els.bgHex) els.bgHex.addEventListener('blur', () => {
      syncBgUi(els.bgHex.value.trim());
      renderPreview();
    });

    if (els.presetCards) els.presetCards.forEach((card) => {
      if (card) card.addEventListener('click', () => applyPreset(card.dataset.preset));
    });
    if (els.saveProfile) els.saveProfile.addEventListener('click', () => { saveProfile(); });
    if (els.copyUrl) els.copyUrl.addEventListener('click', copyPublicUrl);
    if (els.saveCopyUrl) els.saveCopyUrl.addEventListener('click', copyPublicUrl);

    [
      els.slug,
      els.headline,
      els.intro,
      els.locationLabel,
      els.showLocation,
      els.publicEmail,
      els.publicPhone,
      els.publicWhatsapp,
      els.isPublished,
      els.primaryCtaPicker,
    ].forEach((field) => {
      if (!field) return;
      field.addEventListener('input', markDirty);
      field.addEventListener('change', markDirty);
    });

    if (els.slug) els.slug.addEventListener('blur', () => {
      els.slug.value = slugify(els.slug.value);
      renderPreview();
      syncPublicUrl();
    });

    if (els.primaryCtaMode) els.primaryCtaMode.addEventListener('change', () => {
      const mode = els.primaryCtaMode.value;
      if (els.primaryCtaLinkContainer) {
        els.primaryCtaLinkContainer.style.display = (mode === 'link' || mode === 'both') ? 'grid' : 'none';
      }
      renderPreview();
      markDirty();
    });

    loadProfile().catch((error) => {
      showNotice(error.message || 'Profil se nepodařilo načíst.', 'error');
    });
  </script>
<?php endif; ?>
</body>
</html>
