/* BAN YARO — Widget-Vorschau (Home-Screen-Widget) */

window.Page_widget = (() => {

  let _container = null;
  let _appState  = null;
  let _refreshTimer = null;

  async function init(container, appState) {
    _container = container;
    _appState  = appState;
    await _render();
  }

  async function refresh() {
    await _render();
  }

  async function _render() {
    _container.innerHTML = `
      <div style="padding:var(--space-4)">
        <div style="text-align:center;color:var(--c-text-muted);padding:var(--space-8)">
          <div style="font-size:2rem">⏳</div>
          <div>Lade…</div>
        </div>
      </div>`;

    if (!_appState.activeDog) {
      _container.innerHTML = UI.emptyState({
        icon:   UI.icon('dog'),
        title:  'Kein Hund angelegt',
        text:   'Erstelle zuerst ein Hundeprofil.',
        action: `<button class="btn btn-primary" onclick="App.navigate('dog-profile')">Profil erstellen</button>`,
      });
      return;
    }

    let data;
    try {
      data = await API.widget.snapshot();
    } catch (e) {
      _container.innerHTML = '<p style="padding:2rem;color:red">Fehler beim Laden.</p>';
      return;
    }

    const dog   = data.dog;
    const photo = data.random_photo;
    const rem   = data.reminder;

    const photoHtml = photo
      ? `<div class="widget-photo-wrap">
           <img src="${_esc(photo.media_url)}" alt="${_esc(photo.titel || '')}" class="widget-photo">
           <div class="widget-photo-caption">
             ${_esc(photo.titel || '')}
             <span class="widget-photo-date">${_fmtDate(photo.datum)}</span>
           </div>
         </div>`
      : `<div class="widget-photo-wrap widget-photo-placeholder">
           <svg class="ph-icon" style="font-size:3rem" aria-hidden="true"><use href="/icons/phosphor.svg#image"></use></svg>
           <div style="color:var(--c-text-muted);font-size:var(--text-sm)">Noch keine Fotos im Tagebuch</div>
         </div>`;

    const reminderHtml = rem
      ? `<div class="widget-reminder">
           <svg class="ph-icon" aria-hidden="true"><use href="/icons/phosphor.svg#calendar-check"></use></svg>
           <div>
             <div style="font-weight:var(--weight-semibold);font-size:var(--text-sm)">${_esc(rem.bezeichnung)}</div>
             <div style="font-size:var(--text-xs);color:var(--c-text-muted)">${_fmtDate(rem.naechstes)}</div>
           </div>
         </div>`
      : data.overdue > 0
        ? `<div class="widget-reminder widget-reminder--overdue">
             <svg class="ph-icon" aria-hidden="true"><use href="/icons/phosphor.svg#warning"></use></svg>
             <div style="font-size:var(--text-sm)">${data.overdue} überfällige Erinnerung${data.overdue > 1 ? 'en' : ''}</div>
           </div>`
        : `<div class="widget-reminder widget-reminder--ok">
             <svg class="ph-icon" aria-hidden="true"><use href="/icons/phosphor.svg#check-circle"></use></svg>
             <div style="font-size:var(--text-sm)">Keine offenen Erinnerungen</div>
           </div>`;

    const dogAvatar = dog.foto_url
      ? `<img src="${_esc(dog.foto_url)}" class="widget-dog-av" alt="${_esc(dog.name)}">`
      : `<div class="widget-dog-av widget-dog-av--placeholder">🐕</div>`;

    _container.innerHTML = `
      <div style="padding:var(--space-4)">

        <div class="widget-card">
          <div class="widget-dog-row">
            ${dogAvatar}
            <div>
              <div style="font-weight:var(--weight-bold);font-size:var(--text-lg)">${_esc(dog.name)}</div>
              ${dog.rasse ? `<div style="font-size:var(--text-sm);color:var(--c-text-muted)">${_esc(dog.rasse)}</div>` : ''}
            </div>
            <button class="btn btn-secondary btn-sm" id="widget-refresh-btn" style="margin-left:auto"
                    title="Neues Zufallsbild">
              <svg class="ph-icon" aria-hidden="true"><use href="/icons/phosphor.svg#arrows-clockwise"></use></svg>
            </button>
          </div>

          ${reminderHtml}
          ${photoHtml}
        </div>

        <div style="margin-top:var(--space-4);padding:var(--space-3) var(--space-4);
                    background:var(--c-surface);border-radius:var(--radius-md);
                    border:1px solid var(--c-border)">
          <div style="font-size:var(--text-sm);font-weight:var(--weight-semibold);
                      margin-bottom:var(--space-2)">
            <svg class="ph-icon" aria-hidden="true"><use href="/icons/phosphor.svg#device-mobile"></use></svg>
            Als Home-Screen-Widget nutzen
          </div>
          <p style="font-size:var(--text-xs);color:var(--c-text-secondary);margin-bottom:var(--space-3)">
            Füge diese Seite zum Home-Screen hinzu und öffne sie mit einem Tipp.
          </p>
          <div style="display:flex;flex-direction:column;gap:var(--space-2)">
            <div style="font-size:var(--text-xs);color:var(--c-text-muted)">
              <strong>iOS Safari:</strong> Teilen-Symbol → „Zum Home-Bildschirm"
            </div>
            <div style="font-size:var(--text-xs);color:var(--c-text-muted)">
              <strong>Android Chrome:</strong> Menü (⋮) → „Zum Startbildschirm hinzufügen"
            </div>
          </div>
        </div>
      </div>`;

    _container.querySelector('#widget-refresh-btn')?.addEventListener('click', () => _render());
  }

  function _esc(str) {
    if (!str) return '';
    return String(str).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
  }

  function _fmtDate(d) {
    if (!d) return '';
    try {
      const [y, m, day] = d.split('-');
      return `${parseInt(day)}.${parseInt(m)}.${y}`;
    } catch { return d; }
  }

  return { init, refresh };

})();
