<script lang="ts">
  import { enhance } from '$app/forms';
  import { untrack } from 'svelte';
  import type { PageData, ActionData } from './$types';
  import { analyzeCopy } from '$lib/seo';

  let { data, form }: { data: PageData; form: ActionData } = $props();

  let values = $state<Record<string, string>>(untrack(() => ({ ...data.copy })));
  let primaryKw = $state(untrack(() => data.seo.primaryKeywords.join(', ')));
  let iframeKey = $state(0);
  let showInfo = $state(false);

  function reloadPreview() {
    iframeKey += 1;
  }

  $effect(() => {
    if (form?.success || form?.seoSaved) reloadPreview();
  });

  const keywordList = $derived(
    primaryKw
      .split(',')
      .map((s) => s.trim())
      .filter(Boolean)
  );

  const sections = $derived.by(() => {
    const bySection = new Map<string, typeof data.slots>();
    for (const slot of data.slots) {
      const list = bySection.get(slot.section) ?? [];
      list.push(slot);
      bySection.set(slot.section, list);
    }
    return [...bySection.entries()];
  });

  function scoreClass(prefix: 'seo' | 'geo', n: number) {
    if (n >= 75) return `${prefix}-good`;
    if (n >= 50) return `${prefix}-warn`;
    return `${prefix}-bad`;
  }

  function analysisOf(id: string) {
    return analyzeCopy(values[id] ?? '', keywordList);
  }
</script>

<svelte:head><title>Testi & SEO/GEO — Admin</title></svelte:head>

<header class="page-head">
  <p class="kicker">Contenuti</p>
  <h1>Testi, SEO & GEO</h1>
  <p>
    Modifica ogni copy della landing page. Per ciascun blocco ottieni un punteggio SEO (ottimizzazione motori di ricerca) e GEO (ottimizzazione per motori generativi) in tempo reale con suggerimenti mirati.
  </p>
</header>

<div class="info-box">
  <button type="button" class="info-toggle" onclick={() => (showInfo = !showInfo)}>
    <span class="material-symbols-outlined" aria-hidden="true">help</span>
    <strong>Cosa sono SEO e GEO? Come leggere i voti?</strong>
    <span class="material-symbols-outlined chev" aria-hidden="true">{showInfo ? 'expand_less' : 'expand_more'}</span>
  </button>
  {#if showInfo}
    <div class="info-body">
      <div class="info-col">
        <h3>SEO — essere trovati su Google</h3>
        <p>
          SEO vuol dire "farsi trovare dai motori di ricerca tipo Google". Quando qualcuno cerca
          <em>"dogsitter Sassari"</em>, i testi del tuo sito aiutano Google a capire se mostrarti.
          Un testo SEO buono è chiaro, contiene le parole giuste, non è né troppo corto né troppo lungo.
        </p>
      </div>
      <div class="info-col">
        <h3>GEO — essere citati dalle AI</h3>
        <p>
          GEO (Generative Engine Optimization) è la versione moderna: serve a farsi citare da
          ChatGPT, Gemini o Perplexity quando qualcuno chiede loro consiglio.
          Funziona quando scrivi in prima persona, citi luoghi e numeri concreti, e rispondi a
          domande precise.
        </p>
      </div>
      <div class="info-col">
        <h3>Come leggere i voti</h3>
        <ul>
          <li><span class="dot green"></span><strong>75–100 verde</strong> — il testo funziona bene.</li>
          <li><span class="dot amber"></span><strong>50–74 giallo</strong> — va migliorato ma non è grave.</li>
          <li><span class="dot red"></span><strong>0–49 rosso</strong> — qualcosa non va, leggi i consigli sotto al testo.</li>
        </ul>
      </div>
    </div>
  {/if}
</div>

<div class="preview-pane">
  <header>
    <div>
      <strong>Anteprima live della landing</strong>
      <small>Si aggiorna da sola ad ogni salvataggio. Per un aggiornamento manuale, usa il pulsante.</small>
    </div>
    <div style="display:flex;gap:8px;">
      <button type="button" class="btn btn-ghost btn-sm" onclick={reloadPreview}>
        <span class="material-symbols-outlined" aria-hidden="true">refresh</span>
        Aggiorna
      </button>
      <a href="/" target="_blank" class="btn btn-ghost btn-sm">
        <span class="material-symbols-outlined" aria-hidden="true">open_in_new</span>
        Apri in una nuova scheda
      </a>
    </div>
  </header>
  {#key iframeKey}
    <iframe title="Anteprima landing page" src="/?v={iframeKey}"></iframe>
  {/key}
</div>

{#if form?.success}
  <div class="alert-row">Salvato — {form.count} modifiche applicate. Anteprima aggiornata.</div>
{/if}
{#if form?.seoSaved}
  <div class="alert-row">Meta SEO & GEO aggiornati.</div>
{/if}
{#if form?.error}
  <div class="alert-row err">{form.error}</div>
{/if}

<div class="card">
  <h2>Meta pagina · SEO & GEO</h2>
  <p>Impostazioni di indicizzazione globali: titolo, description, keyword primarie, segnali geografici.</p>
  <form method="POST" action="?/saveSeo" use:enhance style="margin-top:14px;">
    <div class="grid-2">
      <div class="field">
        <label for="title">Title tag</label>
        <input id="title" name="title" type="text" value={data.seo.title} />
        <small>Consigliato 50–60 caratteri.</small>
      </div>
      <div class="field">
        <label for="ogImage">Open Graph image (path)</label>
        <input id="ogImage" name="ogImage" type="text" value={data.seo.ogImage} />
      </div>
    </div>
    <div class="field">
      <label for="description">Meta description</label>
      <textarea id="description" name="description">{data.seo.description}</textarea>
      <small>Consigliato 120–160 caratteri.</small>
    </div>
    <div class="field">
      <label for="keywords">Meta keywords</label>
      <input id="keywords" name="keywords" type="text" value={data.seo.keywords} />
    </div>
    <div class="field">
      <label for="primaryKeywords">Keyword primarie (analizzate sul copy)</label>
      <input id="primaryKeywords" name="primaryKeywords" type="text" bind:value={primaryKw} />
      <small>Separate da virgola. Usate per controllare la presenza in ogni copy.</small>
    </div>
    <div class="grid-2">
      <div class="field">
        <label for="geoRegion">Geo region (ISO 3166-2)</label>
        <input id="geoRegion" name="geoRegion" type="text" value={data.seo.geoRegion} />
      </div>
      <div class="field">
        <label for="geoPlacename">Geo placename</label>
        <input id="geoPlacename" name="geoPlacename" type="text" value={data.seo.geoPlacename} />
      </div>
    </div>
    <button type="submit" class="btn">
      <span class="material-symbols-outlined" aria-hidden="true">save</span>
      Salva meta
    </button>
  </form>
</div>

<form method="POST" action="?/saveCopy" use:enhance>
  {#each sections as [sectionName, slots]}
    <div class="section-divider">
      <h2>{sectionName}</h2>
      <span class="count">{slots.length}</span>
    </div>
    <div class="slot-grid">
      {#each slots as slot}
        {@const a = analysisOf(slot.id)}
        <div class="slot-card">
          <header>
            <div>
              <div class="slot-label">{slot.label}</div>
              <div class="slot-id">{slot.id}</div>
            </div>
            <div class="score-row">
              <span class="score-chip {scoreClass('seo', a.seoScore)}">SEO {a.seoScore}</span>
              <span class="score-chip {scoreClass('geo', a.geoScore)}">GEO {a.geoScore}</span>
            </div>
          </header>
          {#if slot.id === 'footer.powered'}
            <select name="slot:{slot.id}" bind:value={values[slot.id]}>
              <option value="Powered by">Powered by</option>
              <option value="Built by">Built by</option>
              <option value="In collab with">In collab with</option>
            </select>
          {:else if slot.kind === 'multiline'}
            <textarea name="slot:{slot.id}" bind:value={values[slot.id]} rows="3"></textarea>
          {:else}
            <input name="slot:{slot.id}" type="text" bind:value={values[slot.id]} />
          {/if}
          <small style="display:flex;gap:14px;color:var(--text-muted);font-size:11px;margin-top:6px;flex-wrap:wrap;">
            <span>{a.length} car.</span>
            <span>{a.words} parole</span>
            <span>Leggibilità {a.readability}</span>
            {#if a.keywordMatches.length}<span>Keyword match: {a.keywordMatches.join(', ')}</span>{/if}
          </small>
          {#if a.seoTips.length || a.geoTips.length}
            <ul class="tip-list">
              {#each a.seoTips as tip}<li><strong style="color:var(--accent-dark);">SEO:</strong> {tip}</li>{/each}
              {#each a.geoTips as tip}<li><strong style="color:var(--accent);">GEO:</strong> {tip}</li>{/each}
            </ul>
          {/if}
        </div>
      {/each}
    </div>
  {/each}
  <div style="position:sticky;bottom:0;padding:14px 0;background:linear-gradient(to top, var(--panel-muted) 60%, rgba(251,249,244,0));margin-top:24px;">
    <button type="submit" class="btn">
      <span class="material-symbols-outlined" aria-hidden="true">save</span>
      Salva tutte le modifiche
    </button>
  </div>
</form>

<style>
  .info-box {
    background: rgba(0, 29, 54, 0.035);
    border: 1px solid var(--border);
    border-radius: 14px;
    margin-bottom: 18px;
    overflow: hidden;
  }
  .info-toggle {
    display: flex;
    align-items: center;
    gap: 12px;
    width: 100%;
    padding: 14px 18px;
    background: transparent;
    border: none;
    cursor: pointer;
    font-family: inherit;
    font-size: 14px;
    color: var(--accent-dark);
    text-align: left;
  }
  .info-toggle .chev { margin-left: auto; }
  .info-toggle:hover { background: rgba(0, 29, 54, 0.05); }
  .info-body {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 18px;
    padding: 6px 18px 18px;
    border-top: 1px dashed var(--border);
  }
  .info-col h3 { font-size: 13px; color: var(--accent-dark); margin-bottom: 6px; font-family: 'Manrope', sans-serif; font-weight: 700; }
  .info-col p { font-size: 13px; color: var(--text); line-height: 1.6; margin: 0; }
  .info-col ul { list-style: none; padding: 0; margin: 0; display: flex; flex-direction: column; gap: 6px; }
  .info-col li { font-size: 13px; color: var(--text); line-height: 1.5; display: flex; align-items: center; gap: 8px; }
  .dot { width: 10px; height: 10px; border-radius: 50%; flex-shrink: 0; }
  .dot.green { background: var(--ok); }
  .dot.amber { background: var(--warn); }
  .dot.red { background: var(--danger); }

  .preview-pane {
    background: var(--panel);
    border: 1px solid var(--border);
    border-radius: 14px;
    margin-bottom: 18px;
    overflow: hidden;
  }
  .preview-pane header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 14px;
    padding: 12px 16px;
    background: var(--panel-muted);
    border-bottom: 1px solid var(--border);
  }
  .preview-pane header strong { color: var(--accent-dark); font-size: 14px; display: block; }
  .preview-pane header small { color: var(--text-muted); font-size: 12px; display: block; margin-top: 2px; }
  .preview-pane iframe {
    width: 100%;
    height: 520px;
    border: none;
    background: #fff;
    display: block;
  }

  @media (max-width: 900px) {
    .info-body { grid-template-columns: 1fr; }
    .preview-pane iframe { height: 400px; }
  }
</style>
