<?php
declare(strict_types=1);

require_once __DIR__ . '/../_dashboard.php';
dashboard_render_start('Můj profil', 'profile');

if ($dashboardUser && !$dashboardUser['is_company']):
    $initial = ['page' => $dashboardPage, 'links' => $dashboardLinks];
?>
<header class="page-heading"><span class="welcome">Váš profil na Influenz</span><h1>Můj profil</h1><p>Upravte informace, podle kterých vás značky poznají a osloví.</p></header>
<div class="editor-shell">
  <div class="editor-stack">
    <section class="section-card"><div class="section-heading"><span class="section-number">1</span><div><h2>Základní informace</h2><p>Tyto informace uvidí značky na vašem profilu.</p></div></div><div class="field-grid" style="margin-top:20px"><label class="field"><span>Jméno na profilu</span><input id="profile-headline" maxlength="120" placeholder="Např. Markéta Nováková"></label><label class="field"><span>Odkud jste?</span><input id="profile-location" maxlength="90" placeholder="Praha, Česko"></label><label class="field full"><span>Něco o vás</span><textarea id="profile-intro" maxlength="1000" placeholder="Představte sebe a svou tvorbu."></textarea></label></div></section>
    <section class="section-card"><div class="section-heading"><span class="section-number">2</span><div><h2>Zaměření</h2><p>Pomozte značkám najít pro vás vhodnou spolupráci.</p></div></div><div class="field-grid" style="margin-top:20px"><label class="field"><span>Témata</span><input id="profile-categories" placeholder="Beauty, fitness, cestování"><small class="field-hint">Více témat oddělte čárkou.</small></label><label class="field"><span>Typy spolupráce</span><input id="profile-collabs" placeholder="UGC, reels, affiliate"><small class="field-hint">Více typů oddělte čárkou.</small></label><label class="field full"><span>Co nabízíte značkám?</span><input id="profile-offer" maxlength="220" placeholder="Např. UGC videa pro beauty značky"></label></div></section>
    <section class="section-card"><div class="section-heading"><span class="section-number">3</span><div><h2>Kontakt pro spolupráce</h2><p>Na tento e-mail vám přijde upozornění na novou poptávku. Veřejně ho nezobrazujeme.</p></div></div><div class="field-grid" style="margin-top:20px"><label class="field full"><span>Kontaktní e-mail</span><input id="profile-email" type="email"></label></div><div class="editor-actions" style="margin-top:20px"><button class="btn btn-primary" id="save-profile" type="button">Uložit změny</button></div><div id="profile-notice" class="notice" role="status" aria-live="polite"></div></section>
  </div>
  <aside class="preview-sticky"><section class="ui-card"><div class="card-title"><span class="round-icon coral"><i class="ph ph-eye"></i></span><div><h2>Náhled profilu</h2><p>Jak vás uvidí značky.</p></div></div><div class="profile-preview"><div class="profile-cover"></div><div class="profile-preview-body"><?php if ($dashboardAvatar !== ''): ?><img class="profile-preview-avatar" src="<?= dashboard_h($dashboardAvatar) ?>" alt="Profilová fotka"><?php endif; ?><h3 id="profile-preview-name"><?= dashboard_h($dashboardName) ?></h3><p id="profile-preview-intro"></p></div></div><a class="btn btn-soft btn-full" href="/influencer/link-in-bio/">Upravit Link in Bio</a></section></aside>
</div>
<script>
const initial = <?= json_encode($initial, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT) ?>;
const page = initial.page || {};
const csrf = document.querySelector('meta[name="profile-csrf"]').content;
const $ = id => document.getElementById(id);
let dirty = false;
$('profile-headline').value = page.headline || '';
$('profile-location').value = (page.audience_regions || [])[0] || '';
$('profile-intro').value = page.intro || '';
$('profile-categories').value = (page.preferred_categories || []).join(', ');
$('profile-collabs').value = (page.preferred_collab_types || []).join(', ');
$('profile-offer').value = page.featured_offer || '';
$('profile-email').value = page.public_email || '';
function preview() {
  $('profile-preview-name').textContent = $('profile-headline').value || <?= json_encode($dashboardName, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT) ?>;
  $('profile-preview-intro').textContent = $('profile-intro').value || 'Doplňte krátké představení.';
}
['profile-headline','profile-location','profile-intro','profile-categories','profile-collabs','profile-offer','profile-email'].forEach(id => $(id).addEventListener('input', () => { dirty = true; preview(); }));
preview();
$('save-profile').onclick = async () => {
  const button = $('save-profile');
  const location = $('profile-location').value.trim();
  const existingRegions = Array.isArray(page.audience_regions) ? page.audience_regions.slice(1) : [];
  const payload = {
    ...page,
    headline: $('profile-headline').value.trim(),
    intro: $('profile-intro').value.trim(),
    location_label: location,
    show_location: location !== '',
    audience_regions: location ? [location, ...existingRegions] : existingRegions,
    preferred_categories: $('profile-categories').value.split(',').map(value => value.trim()).filter(Boolean),
    preferred_collab_types: $('profile-collabs').value.split(',').map(value => value.trim()).filter(Boolean),
    featured_offer: $('profile-offer').value.trim(),
    public_email: $('profile-email').value.trim(),
    revision: Number(page.revision || 0),
    links: initial.links || []
  };
  button.disabled = true;
  try {
    const response = await fetch('/profile/api/save.php', {method: 'POST', credentials: 'include', headers: {'Content-Type': 'application/json', 'X-Profile-CSRF': csrf}, body: JSON.stringify(payload)});
    const data = await response.json();
    if (!response.ok) throw new Error(data.error || 'Změny se nepodařilo uložit.');
    page.revision = Number(data.page?.revision || page.revision || 1);
    if (Array.isArray(data.links)) initial.links = data.links;
    dirty = false;
    $('profile-notice').textContent = 'Změny jsou uložené.';
    $('profile-notice').className = 'notice show success';
  } catch (error) {
    $('profile-notice').textContent = error.message;
    $('profile-notice').className = 'notice show error';
  } finally {
    button.disabled = false;
  }
};
window.addEventListener('beforeunload', event => { if (dirty) { event.preventDefault(); event.returnValue = ''; } });
</script>
<?php
endif;
dashboard_render_end();
