<?php
declare(strict_types=1);

require_once __DIR__ . '/../_dashboard.php';
dashboard_render_start('Link in Bio', 'bio');

if ($dashboardUser && !$dashboardUser['is_company']):
    $initial = ['page' => $dashboardPage, 'links' => $dashboardLinks, 'account' => $dashboardAccount];
?>
<header class="page-heading">
  <span class="welcome">Link in Bio</span>
  <h1>Vaše stránka s odkazy</h1>
  <p>Obsah, vzhled i kontakt upravíte na jednom místě. Změny ihned uvidíte v náhledu.</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áklad stránky</h2><p>Vyberte adresu a představte se jednou větou.</p></div></div>
      <div class="field-grid">
        <label class="field"><span>Vaše veřejná adresa</span><div class="input-prefix"><span>influenz.cz/@</span><input id="bio-slug" maxlength="60" placeholder="marketa"></div></label>
        <label class="field"><span>Jméno na stránce</span><input id="bio-headline" maxlength="120" placeholder="Markéta Nováková"></label>
        <label class="field full"><span>Krátké představení</span><textarea id="bio-intro" maxlength="1000" placeholder="Napište, čemu se věnujete a co u vás lidé najdou."></textarea><small class="field-hint"><span id="intro-count">0</span>/1000 znaků</small></label>
        <div class="field full"><span>Profilová fotografie</span><div class="avatar-upload-control"><?php if ($dashboardAvatar !== ''): ?><img id="avatar-current-image" src="<?= dashboard_h($dashboardAvatar) ?>" alt="Aktuální profilová fotografie"><?php else: ?><span id="avatar-current-image" class="avatar-upload-fallback"><i class="ph ph-user"></i></span><?php endif; ?><div><strong id="avatar-upload-title"><?= $dashboardAvatar !== '' ? 'Aktuální profilová fotografie' : 'Zatím nemáte profilovou fotografii' ?></strong><small class="field-hint">JPG, PNG nebo WebP, alespoň 320 × 320 px.</small><label for="bio-avatar-file" class="upload-change-button"><i class="ph ph-upload-simple"></i><?= $dashboardAvatar !== '' ? 'Nahrát jinou fotku' : 'Nahrát fotografii' ?></label></div><input id="bio-avatar-file" class="visually-hidden" type="file" accept="image/png,image/jpeg,image/webp"><input id="bio-avatar" type="hidden"></div></div>
        <label class="field"><span>Lokace</span><input id="bio-location" maxlength="90" placeholder="Praha, Česko"></label>
      </div>
    </section>

    <section class="section-card">
      <div class="quick-head section-heading"><div class="section-heading"><span class="section-number">2</span><div><h2>Odkazy</h2><p>Přidejte odkazy a seřaďte je tak, jak se mají zobrazit.</p></div></div><button class="btn btn-soft" id="add-link" type="button"><i class="ph ph-plus"></i>Přidat odkaz</button></div>
      <div id="link-list" class="link-editor-list"></div>
      <div id="empty-links" class="empty-state"><span class="round-icon"><i class="ph ph-link"></i></span><strong>Zatím tu není žádný odkaz</strong><p>Přidejte web, sociální síť, e-shop nebo nabídku spolupráce.</p><button class="btn btn-soft" id="add-first-link" type="button">Přidat první odkaz</button></div>
    </section>

    <section class="section-card">
      <div class="section-heading"><span class="section-number">3</span><div><h2>Vzhled</h2><p>Vyberte barvy své stránky. Výsledek uvidíte hned v náhledu.</p></div></div>
      <div class="field-grid color-fields">
        <label class="field color-field"><span>Barva tlačítek</span><span class="color-control"><input id="bio-accent" type="color" value="#f36b4f" aria-label="Vybrat barvu tlačítek"><output id="accent-output">#f36b4f</output><i class="ph ph-caret-down"></i></span></label>
        <label class="field color-field"><span>Barva pozadí</span><span class="color-control"><input id="bio-bg" type="color" value="#f7efe8" aria-label="Vybrat barvu pozadí"><output id="bg-output">#f7efe8</output><i class="ph ph-caret-down"></i></span></label>
      </div>
      <button id="reset-design" class="text-button" type="button"><i class="ph ph-arrow-counter-clockwise"></i>Obnovit původní barvy</button>
    </section>

    <section class="section-card">
      <div class="section-heading"><span class="section-number">4</span><div><h2>Kontaktní formulář</h2><p>Umožněte značkám poslat vám poptávku přímo ze stránky.</p></div></div>
      <label class="switch-row contact-switch"><span><strong>Zobrazovat kontaktní formulář</strong><small>Vedle vašich odkazů se objeví tlačítko pro novou poptávku.</small></span><input id="bio-contact-enabled" type="checkbox"><i></i></label>
      <div class="field-grid contact-fields" id="contact-settings" hidden>
        <label class="field"><span>Nadpis formuláře</span><input id="bio-contact-label" maxlength="60" placeholder="Napište mi"><small class="field-hint">Tento text uvidí návštěvníci nad formulářem.</small></label>
        <label class="field"><span>Kam posílat upozornění?</span><input id="bio-email" type="email" placeholder="spoluprace@email.cz"><small class="field-hint">E-mail na veřejné stránce nezobrazujeme.</small></label>
      </div>
    </section>

    <section class="section-card publish-card">
      <div><h2>Zveřejnění</h2><p>Rozpracovanou stránku můžete uložit jako neveřejnou.</p></div>
      <label class="switch-row"><span><strong>Veřejná stránka</strong><small id="publish-state">Stránku uvidíte jen vy.</small></span><input id="bio-published" type="checkbox"><i></i></label>
      <div class="editor-actions">
        <button id="open-public" class="btn btn-neutral" type="button"><i class="ph ph-arrow-square-out"></i>Otevřít stránku</button>
        <button id="copy-public" class="btn btn-neutral" type="button"><i class="ph ph-copy"></i>Kopírovat odkaz</button>
        <button id="save-bio" class="btn btn-primary" type="button"><i class="ph ph-floppy-disk"></i>Uložit změny</button>
      </div>
      <div id="bio-notice" class="notice" role="status" aria-live="polite"></div>
    </section>
  </div>

  <aside class="preview-sticky">
    <section class="ui-card preview-card">
      <div class="card-title"><span class="round-icon"><i class="ph ph-device-mobile"></i></span><div><h2>Živý náhled</h2><p>Takto stránku uvidí návštěvníci.</p></div></div>
      <div class="bio-device"><div class="bio-device-speaker"></div><div class="bio-phone bio-live-preview" id="bio-preview">
        <div id="preview-avatar-wrap"></div>
        <strong id="preview-name"><?= dashboard_h($dashboardName) ?></strong>
        <small id="preview-handle"></small>
        <p id="preview-intro" class="preview-description"></p>
        <div id="preview-links"></div>
        <button id="preview-contact" class="preview-contact" type="button" tabindex="-1">Napište mi</button>
        <span class="preview-powered">Powered by <b>Influenz</b></span>
      </div></div>
      <p class="preview-note"><i class="ph ph-info"></i>Náhled je orientační. Veřejná stránka se přizpůsobí telefonu návštěvníka.</p>
    </section>
  </aside>
</div>

<template id="link-row-template">
  <article class="link-editor-row">
    <div class="link-fields">
      <input data-link="id" type="hidden">
      <label class="field"><span>Název</span><input data-link="title" maxlength="90" placeholder="Např. Můj Instagram"></label>
      <label class="field"><span>Webová adresa</span><input data-link="url" type="url" placeholder="https://..."></label>
      <div class="link-options"><label class="field compact"><span>Typ</span><select data-link="type"><option value="social">Sociální síť</option><option value="web">Web</option><option value="shop">Obchod</option><option value="custom">Jiné</option></select></label><label class="visibility-control"><input data-link="active" type="checkbox"><span>Viditelný</span></label></div>
    </div>
    <div class="link-actions"><button data-up class="mini-button" type="button" aria-label="Posunout nahoru"><i class="ph ph-arrow-up"></i></button><button data-down class="mini-button" type="button" aria-label="Posunout dolů"><i class="ph ph-arrow-down"></i></button><button data-remove class="mini-button danger" type="button" aria-label="Odstranit odkaz"><i class="ph ph-trash"></i></button></div>
  </article>
</template>

<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 links = Array.isArray(initial.links) ? initial.links.map(link => ({...link})) : [];
const csrf = document.querySelector('meta[name="profile-csrf"]').content;
const $ = id => document.getElementById(id);
const esc = value => String(value ?? '').replace(/[&<>"']/g, char => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[char]));
let dirty = false;
let avatarObjectUrl = '';

Object.entries({
  'bio-slug': page.slug || '',
  'bio-headline': page.headline || initial.account?.full_name || '',
  'bio-intro': page.intro || initial.account?.bio || '',
  'bio-avatar': page.avatar_url || '',
  'bio-location': (page.audience_regions || [])[0] || '',
  'bio-accent': page.accent_color || '#f36b4f',
  'bio-bg': page.bg_color || '#f7efe8',
  'bio-email': page.public_email || ''
}).forEach(([id, value]) => { $(id).value = value; });
$('bio-published').checked = !!page.is_published;
$('bio-contact-enabled').checked = ['form', 'both'].includes(page.primary_cta_mode || '');
$('bio-contact-label').value = ['form', 'both'].includes(page.primary_cta_mode || '') && page.primary_cta_label ? page.primary_cta_label : 'Napište mi';

function markDirty() { dirty = true; }
function normalizeUrl(value) {
  const clean = String(value || '').trim();
  return !clean || /^https?:\/\//i.test(clean) ? clean : 'https://' + clean.replace(/^\/+/, '');
}
function contrastText(hex) {
  const channels = [1, 3, 5].map(index => {
    const value = parseInt(hex.slice(index, index + 2), 16) / 255;
    return value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4;
  });
  return 0.2126 * channels[0] + 0.7152 * channels[1] + 0.0722 * channels[2] > 0.5 ? '#101735' : '#ffffff';
}
function syncLinkFromRow(link, input) {
  const key = input.dataset.link;
  if (key === 'type') link.link_type = input.value;
  else if (key === 'active') link.is_active = input.checked;
  else link[key] = input.value;
  markDirty();
  renderPreview();
}
function renderLinks() {
  const root = $('link-list');
  root.innerHTML = '';
  links.forEach((link, index) => {
    const row = $('link-row-template').content.firstElementChild.cloneNode(true);
    row.querySelector('[data-link="id"]').value = link.id || 0;
    row.querySelector('[data-link="title"]').value = link.title || '';
    row.querySelector('[data-link="url"]').value = link.url || '';
    row.querySelector('[data-link="type"]').value = link.link_type || 'custom';
    row.querySelector('[data-link="active"]').checked = link.is_active !== false;
    row.querySelectorAll('[data-link]').forEach(input => input.addEventListener(input.type === 'checkbox' ? 'change' : 'input', () => syncLinkFromRow(link, input)));
    row.querySelector('[data-up]').disabled = index === 0;
    row.querySelector('[data-down]').disabled = index === links.length - 1;
    row.querySelector('[data-up]').onclick = () => { if (index > 0) { [links[index - 1], links[index]] = [links[index], links[index - 1]]; markDirty(); renderLinks(); } };
    row.querySelector('[data-down]').onclick = () => { if (index < links.length - 1) { [links[index + 1], links[index]] = [links[index], links[index + 1]]; markDirty(); renderLinks(); } };
    row.querySelector('[data-remove]').onclick = () => {
      if (confirm('Opravdu chcete tento odkaz odstranit?')) { links.splice(index, 1); markDirty(); renderLinks(); }
    };
    root.appendChild(row);
  });
  $('empty-links').hidden = links.length > 0;
  renderPreview();
}
function renderAvatar() {
  const url = avatarObjectUrl || $('bio-avatar').value;
  $('preview-avatar-wrap').innerHTML = url ? '<img class="bio-preview-avatar" src="' + esc(url) + '" alt="">' : '<span class="bio-preview-avatar bio-preview-fallback">' + esc(($('bio-headline').value || <?= json_encode($dashboardName, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT) ?>).trim().slice(0, 2).toUpperCase()) + '</span>';
  const current = $('avatar-current-image');
  if (url && current) {
    if (current.tagName === 'IMG') current.src = url;
    else current.outerHTML = '<img id="avatar-current-image" src="' + esc(url) + '" alt="Aktuální profilová fotografie">';
    $('avatar-upload-title').textContent = 'Aktuální profilová fotografie';
  }
}
function renderPreview() {
  const preview = $('bio-preview');
  preview.dataset.theme = 'portrait';
  preview.style.setProperty('--preview-accent', $('bio-accent').value || '#f36b4f');
  preview.style.setProperty('--preview-bg', $('bio-bg').value || '#f7efe8');
  preview.style.color = contrastText($('bio-bg').value) === '#ffffff' ? '#ffffff' : '#101735';
  $('preview-contact').style.color = contrastText($('bio-accent').value);
  $('preview-name').textContent = $('bio-headline').value || <?= json_encode($dashboardName, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT) ?>;
  $('preview-handle').textContent = '@' + ($('bio-slug').value || 'vas-profil');
  $('preview-intro').textContent = $('bio-intro').value;
  $('intro-count').textContent = $('bio-intro').value.length;
  $('accent-output').textContent = $('bio-accent').value;
  $('bg-output').textContent = $('bio-bg').value;
  $('preview-links').innerHTML = links.filter(link => link.is_active !== false && link.title && link.url).slice(0, 6).map(link => '<div class="bio-link"><span>' + esc(link.title) + '</span><i class="ph ph-caret-right"></i></div>').join('');
  $('contact-settings').hidden = !$('bio-contact-enabled').checked;
  $('preview-links').hidden = false;
  $('preview-contact').hidden = !$('bio-contact-enabled').checked;
  $('preview-contact').textContent = $('bio-contact-label').value.trim() || 'Napište mi';
  $('publish-state').textContent = $('bio-published').checked ? 'Po uložení ji uvidí každý s odkazem.' : 'Stránku uvidíte jen vy.';
  renderAvatar();
}
function buildPayload() {
  const active = links.filter(link => link.is_active !== false && link.title && link.url);
  const selected = active[0] || null;
  return {
    slug: $('bio-slug').value.trim(),
    headline: $('bio-headline').value.trim(),
    intro: $('bio-intro').value.trim(),
    avatar_url: $('bio-avatar').value,
    accent_color: $('bio-accent').value,
    bg_color: $('bio-bg').value,
    theme_preset: 'portrait',
    public_email: $('bio-contact-enabled').checked ? $('bio-email').value.trim() : (page.public_email || ''),
    public_phone: page.public_phone || '',
    public_whatsapp: page.public_whatsapp || '',
    collaboration_status: page.collaboration_status || 'open',
    featured_offer: page.featured_offer || '',
    show_location: !!$('bio-location').value.trim(),
    location_label: $('bio-location').value.trim(),
    audience_regions: $('bio-location').value.trim() ? [$('bio-location').value.trim(), ...(Array.isArray(page.audience_regions) ? page.audience_regions.slice(1) : [])] : (Array.isArray(page.audience_regions) ? page.audience_regions.slice(1) : []),
    preferred_categories: page.preferred_categories || [],
    preferred_collab_types: page.preferred_collab_types || [],
    is_published: $('bio-published').checked,
    primary_cta_mode: $('bio-contact-enabled').checked ? (active.length > 0 ? 'both' : 'form') : 'link',
    contact_cta_label: $('bio-contact-label').value.trim(),
    primary_cta_url: selected?.url || '',
    primary_cta_label: selected?.title || '',
    revision: Number(page.revision || 0),
    links: links.filter(link => link.title || link.url).map((link, index) => ({
      id: Number(link.id || 0),
      title: String(link.title || '').trim(),
      url: normalizeUrl(link.url),
      link_type: link.link_type || 'custom',
      platform: link.platform || '',
      brand_name: link.brand_name || '',
      product_name: link.product_name || '',
      is_featured: !!link.is_featured,
      is_active: link.is_active !== false,
      position: index + 1
    }))
  };
}
function showNotice(message, type = 'success') {
  const node = $('bio-notice');
  node.textContent = message;
  node.className = 'notice show ' + type;
  node.scrollIntoView({behavior: 'smooth', block: 'nearest'});
}
function addLink() {
  if (links.length >= 24) { showNotice('Můžete přidat maximálně 24 odkazů.', 'error'); return; }
  links.push({id: 0, title: '', url: '', link_type: 'custom', is_active: true, is_featured: false});
  markDirty();
  renderLinks();
  const rows = document.querySelectorAll('.link-editor-row');
  rows[rows.length - 1]?.querySelector('[data-link="title"]')?.focus();
}

$('add-link').onclick = addLink;
$('add-first-link').onclick = addLink;
$('reset-design').onclick = () => { $('bio-accent').value = '#f36b4f'; $('bio-bg').value = '#f7efe8'; markDirty(); renderPreview(); };
['bio-slug','bio-headline','bio-intro','bio-location','bio-accent','bio-bg','bio-contact-enabled','bio-contact-label','bio-email','bio-published'].forEach(id => $(id).addEventListener($(id).type === 'checkbox' || $(id).tagName === 'SELECT' ? 'change' : 'input', () => { markDirty(); renderPreview(); }));

$('bio-avatar-file').addEventListener('change', async () => {
  const file = $('bio-avatar-file').files[0];
  if (!file) return;
  if (avatarObjectUrl) URL.revokeObjectURL(avatarObjectUrl);
  avatarObjectUrl = URL.createObjectURL(file);
  renderAvatar();
  const body = new FormData();
  body.append('avatar', file);
  try {
    const response = await fetch('/profile/api/upload-avatar.php', {method: 'POST', credentials: 'include', headers: {'X-Profile-CSRF': csrf}, body});
    const data = await response.json();
    if (!response.ok) throw new Error(data.error || 'Fotku se nepodařilo nahrát.');
    $('bio-avatar').value = data.url || data.avatar_url || '';
    avatarObjectUrl = '';
    markDirty();
    renderAvatar();
    showNotice('Fotografie je připravená. Pro dokončení klikněte na Uložit změny.');
  } catch (error) {
    avatarObjectUrl = '';
    renderAvatar();
    showNotice(error.message, 'error');
  }
});

$('save-bio').onclick = async () => {
  const button = $('save-bio');
  button.disabled = true;
  button.innerHTML = '<i class="ph ph-spinner-gap spinner"></i>Ukládám…';
  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(buildPayload())});
    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);
    page.is_published = !!data.page?.is_published;
    page.slug = data.slug || $('bio-slug').value.trim();
    if (Array.isArray(data.links)) {
      links.splice(0, links.length, ...data.links.map(link => ({...link})));
      renderLinks();
    }
    dirty = false;
    showNotice('Změny jsou uložené.');
  } catch (error) {
    showNotice(error.message, 'error');
  } finally {
    button.disabled = false;
    button.innerHTML = '<i class="ph ph-floppy-disk"></i>Uložit změny';
  }
};

$('open-public').onclick = () => {
  if (!page.is_published || !page.slug) { showNotice('Nejdřív stránku uložte a zveřejněte.', 'error'); return; }
  window.open('/@' + encodeURIComponent(page.slug), '_blank', 'noopener');
};
$('copy-public').onclick = () => {
  if (!page.is_published || !page.slug) { showNotice('Nejdřív stránku uložte a zveřejněte.', 'error'); return; }
  dashboardCopy('/@' + encodeURIComponent(page.slug), $('copy-public'));
};
window.addEventListener('beforeunload', event => { if (dirty) { event.preventDefault(); event.returnValue = ''; } });
renderLinks();
</script>
<?php
endif;
dashboard_render_end();
