import { Component, inject, signal } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { ContentService, Article } from '../../core/services/content.service';
import { Router } from '@angular/router';

@Component({
  selector: 'app-info-hub',
  standalone: true,
  imports: [CommonModule, FormsModule],
  template: `
    <div class="ih-shell">
      

      <!-- ═══════════════════════════════ CONTENIDO PRINCIPAL ═══════════════════════════════ -->
      <main class="ih-content">
        
        <!-- Barra superior oscura -->
        <header class="ih-topbar">
          <h1 class="ih-topbar__title">INFO HUB</h1>
          
          <div class="ih-topbar__controls">
            <div class="ih-search">
              <input type="text" placeholder="Search..." class="wf-search__field" />
              <button class="wf-search__btn">
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                  <circle cx="11" cy="11" r="8"></circle>
                  <line x1="21" y1="21" x2="16.65" y2="16.65"></line>
                </svg>
              </button>
            </div>
            
            <button class="wf-btn-filter">
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <polygon points="22 3 2 3 10 12.46 10 19 14 21 14 12.46 22 3"></polygon>
              </svg>
              Filter
            </button>
          </div>
        </header>

        <!-- Filtros de categoría -->
        <div class="ih-category-filters">
          <button class="ih-category-btn ih-category-btn--active">All News</button>
          <button class="ih-category-btn">Company</button>
          <button class="ih-category-btn">Team</button>
          <button class="ih-category-btn">Events</button>
        </div>

        <!-- Grid de Contenido Principal -->
        <div class="ih-grid">
          
          <!-- Columna Izquierda: Noticias y Comunicados (Grid Interno) -->
          <div class="ih-news-section">
            <div class="ih-news-grid">
              
              @for (art of contentService.articles(); track art.id; let isFirst = $first) {
                @if (isFirst) {
                  <!-- ── Tarjeta Destacada (Grande, primera de la lista) ── -->
                  <article class="ih-card-featured">
                    <div class="ih-card-featured__body">
                      <div class="ih-card-featured__content">
                        <h3 class="ih-card-featured__title">{{ art.title }}</h3>
                        <p class="ih-card-featured__summary">{{ art.body }}</p>
                        
                        <div class="ih-card-author">
                          <div class="ih-card-author__badge">A</div>
                          <span class="ih-card-author__name">App</span>
                        </div>
                      </div>
                      
                      <!-- Imagen destacada a la derecha -->
                      <div class="ih-card-featured__image-wrap">
                        <div class="ih-card-featured__image" style="background-image: url('https://images.unsplash.com/photo-1522071820081-009f0129c71c?auto=format&fit=crop&w=400&q=80')"></div>
                        <div class="ih-card-featured__image-overlay">App</div>
                      </div>
                    </div>

                    <!-- Acciones en la base -->
                    <div class="ih-card-featured__actions">
                      <button (click)="contentService.likeArticle(art.id)" class="ih-btn-action-featured ih-btn-action-featured--like">
                        <span>👍 LIKE</span>
                      </button>
                      <button (click)="toggleComments(art.id)" class="ih-btn-action-featured">
                        <span>💬 COMMENT</span>
                      </button>
                      <button (click)="openShareModal(art)" class="ih-btn-action-featured">
                        <span>🔗 SHARE</span>
                      </button>
                    </div>

                    <!-- Comentarios expandidos en tarjeta destacada -->
                    @if (commentsExpanded(art.id)) {
                      <div class="ih-comments-section animate-fadeIn">
                        <h4 class="ih-comments-title">Comentarios ({{ art.comments.length }})</h4>
                        <div class="ih-comments-list">
                          @for (com of art.comments; track com) {
                            <div class="ih-comment-bubble">
                              <strong>Colaborador</strong>
                              <p>{{ com }}</p>
                            </div>
                          }
                        </div>
                        <div class="ih-comment-form">
                          <input type="text" placeholder="Escribe un comentario..." [(ngModel)]="newComments[art.id]" (keyup.enter)="submitComment(art.id)" class="ih-comment-input" />
                          <button (click)="submitComment(art.id)" class="ih-comment-btn">Enviar</button>
                        </div>
                      </div>
                    }
                  </article>
                } @else {
                  <!-- ── Tarjeta Pequeña Regular ── -->
                  <article class="ih-card-small">
                    <h3 class="ih-card-small__title">{{ art.title }}</h3>
                    <p class="ih-card-small__summary">{{ art.body }}</p>
                    
                    <div class="ih-card-author">
                      <div class="ih-card-author__badge">A</div>
                      <span class="ih-card-author__name">App</span>
                    </div>

                    <!-- Métricas interactivas naranja de la base -->
                    <div class="ih-card-small__metrics">
                      <button (click)="contentService.likeArticle(art.id)" class="ih-metric-btn ih-metric-btn--orange">
                        <span>👍 {{ art.likes }}</span>
                      </button>
                      
                      <button (click)="toggleComments(art.id)" class="ih-metric-btn">
                        <span>💬 {{ art.commentsCount }}</span>
                      </button>
                      
                      <button (click)="openShareModal(art)" class="ih-metric-btn">
                        <span>🔗 {{ art.shares }}</span>
                      </button>
                    </div>

                    <!-- Comentarios expandidos en tarjeta pequeña -->
                    @if (commentsExpanded(art.id)) {
                      <div class="ih-comments-section animate-fadeIn">
                        <div class="ih-comments-list">
                          @for (com of art.comments; track com) {
                            <div class="ih-comment-bubble">
                              <strong>Colaborador</strong>
                              <p>{{ com }}</p>
                            </div>
                          }
                        </div>
                        <div class="ih-comment-form">
                          <input type="text" placeholder="Escribe un comentario..." [(ngModel)]="newComments[art.id]" (keyup.enter)="submitComment(art.id)" class="ih-comment-input" />
                          <button (click)="submitComment(art.id)" class="ih-comment-btn">Enviar</button>
                        </div>
                      </div>
                    }
                  </article>
                }
              }

            </div>
          </div>

          <!-- Columna Derecha: Panel de Actividad de Empleados -->
          <div class="ih-activity-section">
            <div class="ih-card-activity">
              <h3 class="ih-card-activity__title">Panel de Actividad de Empleados</h3>
              
              <div class="ih-activity-list">
                <!-- Actividad 1 -->
                <div class="ih-activity-item">
                  <img src="https://images.unsplash.com/photo-1494790108377-be9c29b29330?auto=format&fit=crop&w=120&q=80" alt="Jess" class="ih-activity-avatar" />
                  <div class="ih-activity-body">
                    <p class="ih-activity-text"><strong>Jess Miller</strong> le dio me gusta al <strong>Anuncio de Nuevos Clientes</strong></p>
                    <span class="ih-activity-time">Hace 5m</span>
                  </div>
                </div>

                <!-- Actividad 2 -->
                <div class="ih-activity-item">
                  <img src="https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?auto=format&fit=crop&w=120&q=80" alt="Alex" class="ih-activity-avatar" />
                  <div class="ih-activity-body">
                    <p class="ih-activity-text"><strong>Alex Rivera</strong> comentó en <strong>Taller de Desarrollo Anual</strong></p>
                    <span class="ih-activity-time">Hace 15m</span>
                  </div>
                </div>

                <!-- Actividad 3 -->
                <div class="ih-activity-item">
                  <img src="https://images.unsplash.com/photo-1500648767791-00dcc994a43e?auto=format&fit=crop&w=120&q=80" alt="David" class="ih-activity-avatar" />
                  <div class="ih-activity-body">
                    <p class="ih-activity-text"><strong>David Chen</strong> compartió <strong>Resultados del Trimestre</strong></p>
                    <span class="ih-activity-time">Hace 15m</span>
                  </div>
                </div>

                <!-- Actividad 4 -->
                <div class="ih-activity-item">
                  <img src="https://images.unsplash.com/photo-1500648767791-00dcc994a43e?auto=format&fit=crop&w=120&q=80" alt="David" class="ih-activity-avatar" />
                  <div class="ih-activity-body">
                    <p class="ih-activity-text"><strong>David Chen</strong> compartió <strong>Resultados del Trimestre</strong></p>
                    <span class="ih-activity-time">Hace 15m</span>
                  </div>
                </div>

                <!-- Actividad 5 -->
                <div class="ih-activity-item">
                  <img src="https://images.unsplash.com/photo-1500648767791-00dcc994a43e?auto=format&fit=crop&w=120&q=80" alt="David" class="ih-activity-avatar" />
                  <div class="ih-activity-body">
                    <p class="ih-activity-text"><strong>David Chen</strong> compartió <strong>Resultados del Trimestre</strong></p>
                    <span class="ih-activity-time">Hace 15m</span>
                  </div>
                </div>
              </div>
            </div>
          </div>

        </div>

      </main>

      <!-- ═══════════════════════════════ MODAL COMPARTIR ═══════════════════════════════ -->
      @if (activeShareModal()) {
        <div class="fixed inset-0 bg-slate-900/60 backdrop-blur-md flex items-center justify-center z-50 animate-fadeIn" (click)="closeShareModal()">
          <div class="bg-white border border-slate-200 w-full max-w-lg p-6 rounded-3xl shadow-2xl flex flex-col gap-5 m-4" (click)="$event.stopPropagation()">
            <div class="flex justify-between items-center">
              <h3 class="text-lg font-black text-slate-900 uppercase tracking-tight">Compartir Publicación</h3>
              <button (click)="closeShareModal()" class="text-slate-400 hover:text-slate-700 text-lg">✕</button>
            </div>
            
            <p class="text-xs text-slate-500 font-light">Selecciona los canales donde deseas propagar este artículo:</p>
            
            <div class="bg-slate-50 p-4 border border-slate-100 rounded-2xl">
              <strong class="text-sm text-slate-800 block mb-1">{{ activeShareModal()?.title }}</strong>
              <p class="text-xs text-slate-500 line-clamp-3 leading-relaxed">{{ activeShareModal()?.body }}</p>
            </div>

            <div class="flex flex-col gap-3">
              <label class="flex items-center gap-3 p-3 border border-slate-150 rounded-2xl bg-white hover:bg-slate-50 cursor-pointer text-xs font-semibold text-slate-700 transition">
                <input type="checkbox" [(ngModel)]="shareLinkedIn" class="w-4 h-4 accent-indigo-600 rounded" />
                <span>🔗 Publicar en <strong>LinkedIn corporativo</strong></span>
              </label>
              <label class="flex items-center gap-3 p-3 border border-slate-150 rounded-2xl bg-white hover:bg-slate-50 cursor-pointer text-xs font-semibold text-slate-700 transition">
                <input type="checkbox" [(ngModel)]="shareX" class="w-4 h-4 accent-indigo-600 rounded" />
                <span>🔗 Publicar en <strong>X (Twitter) oficial</strong></span>
              </label>
              <label class="flex items-center gap-3 p-3 border border-slate-150 rounded-2xl bg-white hover:bg-slate-50 cursor-pointer text-xs font-semibold text-slate-700 transition">
                <input type="checkbox" [(ngModel)]="shareIntranet" class="w-4 h-4 accent-indigo-600 rounded" />
                <span>🔗 Publicar en la <strong>Intranet</strong></span>
              </label>
            </div>

            <div class="flex gap-4 mt-2 justify-end">
              <button (click)="closeShareModal()" class="px-5 py-2.5 rounded-full border border-slate-200 text-xs font-bold hover:bg-slate-50 transition text-slate-600">
                Cancelar
              </button>
              <button (click)="confirmShare()" class="px-5 py-2.5 rounded-full bg-slate-900 text-white font-bold text-xs uppercase tracking-wider transition">
                Compartir Ahora
              </button>
            </div>
          </div>
        </div>
      }

    </div>
  `,
  styles: [`
    :host {
      display: flex;
      flex-direction: column;
      flex: 1;
      min-height: 0;
      height: 100%;
    }

    /* ── LAYOUT PRINCIPAL ── */
    .ih-shell {
      display: flex;
      background: #f4f3ef; /* Light beige/grey background matching workflow */
      height: 100%;
      border-radius: 24px;
      overflow: hidden;
      border: 1px solid rgba(15, 13, 10, 0.08);
      box-shadow: 0 4px 20px rgba(0, 0, 0, 0.02);
      font-family: 'Outfit', 'Inter', system-ui, sans-serif;
      flex: 1;
      min-height: 0;
    }

    /* Content Area */
    .ih-content {
      flex-grow: 1;
      padding: 12px 16px;
      display: flex;
      flex-direction: column;
      gap: 12px;
      min-width: 0;
      height: 100%;
      overflow: hidden;
    }

    /* Topbar */
    .ih-topbar {
      background: #111625;
      border-radius: 16px;
      padding: 14px 24px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      flex-wrap: wrap;
      gap: 12px;
    }

    .ih-topbar__title {
      font-size: 18px;
      font-weight: 700;
      color: #ffffff;
      margin: 0;
    }

    .ih-topbar__controls {
      display: flex;
      align-items: center;
      gap: 12px;
    }

    .ih-search {
      position: relative;
      width: 180px;
    }

    .wf-search__field {
      width: 100%;
      background: rgba(255, 255, 255, 0.08);
      border: 1px solid rgba(255, 255, 255, 0.1);
      border-radius: 10px;
      padding: 6px 12px 6px 32px;
      font-size: 11px;
      color: #ffffff;
      outline: none;
    }

    .wf-search__btn {
      position: absolute;
      left: 10px;
      top: 50%;
      transform: translateY(-50%);
      background: transparent;
      border: none;
      color: rgba(255, 255, 255, 0.4);
      cursor: pointer;
      display: flex;
      align-items: center;
    }

    .wf-btn-filter {
      background: rgba(255, 255, 255, 0.08);
      border: 1px solid rgba(255, 255, 255, 0.1);
      border-radius: 10px;
      color: #ffffff;
      font-size: 11px;
      font-weight: 600;
      padding: 6px 14px;
      cursor: pointer;
      display: inline-flex;
      align-items: center;
      gap: 6px;
    }

    /* Category Filters */
    .ih-category-filters {
      display: flex;
      gap: 10px;
      flex-wrap: wrap;
    }

    .ih-category-btn {
      background: #e2e8f0;
      border: none;
      color: #475569;
      font-size: 11px;
      font-weight: 700;
      padding: 8px 16px;
      border-radius: 10px;
      cursor: pointer;
      transition: background 0.15s ease, color 0.15s ease;
    }

    .ih-category-btn:hover {
      background: #cbd5e1;
      color: #0f172a;
    }

    .ih-category-btn--active {
      background: #084d47; /* Teal-dark green */
      color: #ffffff !important;
    }

    /* Main Grid */
    .ih-grid {
      display: grid;
      grid-template-columns: 1fr;
      gap: 16px;
      flex: 1;
      overflow-y: auto;
      min-height: 0;
      padding: 4px; /* avoid box-shadow clipping */
    }

    @media (min-width: 1024px) {
      .ih-grid {
        grid-template-columns: 7fr 3fr;
      }
    }

    /* News Column layout */
    .ih-news-section {
      display: flex;
      flex-direction: column;
      gap: 20px;
    }

    .ih-news-grid {
      display: grid;
      grid-template-columns: 1fr;
      gap: 20px;
    }

    @media (min-width: 768px) {
      .ih-news-grid {
        grid-template-columns: 1fr 1fr;
      }
      .ih-card-featured {
        grid-column: 1 / -1;
      }
    }

    @media (min-width: 1200px) {
      .ih-news-grid {
        grid-template-columns: 1fr 1fr 1fr;
      }
      .ih-card-featured {
        grid-column: 1 / span 2;
      }
    }

    /* Featured Card */
    .ih-card-featured {
      background: #ffffff;
      border-radius: 20px;
      border: 1px solid #e2e8f0;
      box-shadow: 0 1px 3px rgba(0, 0, 0, 0.01);
      display: flex;
      flex-direction: column;
      overflow: hidden;
    }

    .ih-card-featured__body {
      display: flex;
      padding: 24px;
      gap: 20px;
      flex-wrap: wrap;
    }

    .ih-card-featured__content {
      flex: 1;
      min-width: 240px;
      display: flex;
      flex-direction: column;
      gap: 12px;
    }

    .ih-card-featured__title {
      font-size: 18px;
      font-weight: 800;
      color: #000000;
      margin: 0;
      letter-spacing: -0.01em;
      line-height: 1.25;
    }

    .ih-card-featured__summary {
      font-size: 12px;
      color: #64748b;
      line-height: 1.6;
      margin: 0;
    }

    .ih-card-featured__image-wrap {
      width: 140px;
      height: 100px;
      border-radius: 12px;
      overflow: hidden;
      position: relative;
      flex-shrink: 0;
    }

    .ih-card-featured__image {
      width: 100%;
      height: 100%;
      background-size: cover;
      background-position: center;
    }

    .ih-card-featured__image-overlay {
      position: absolute;
      bottom: 4px;
      right: 4px;
      background: rgba(0, 0, 0, 0.6);
      color: #facc15;
      font-size: 9px;
      font-weight: 800;
      padding: 2px 6px;
      border-radius: 4px;
    }

    .ih-card-featured__actions {
      background: #f8fafc;
      border-top: 1px solid #e2e8f0;
      display: flex;
      padding: 10px 24px;
      gap: 16px;
    }

    .ih-btn-action-featured {
      background: transparent;
      border: none;
      color: #64748b;
      font-size: 11px;
      font-weight: 700;
      cursor: pointer;
      display: inline-flex;
      align-items: center;
      gap: 6px;
      padding: 6px 12px;
      border-radius: 8px;
      transition: color 0.15s ease, background 0.15s ease;
    }

    .ih-btn-action-featured:hover {
      background: #e2e8f0;
      color: #0f172a;
    }

    .ih-btn-action-featured--like {
      background: #e07a3c;
      color: #ffffff !important;
    }

    .ih-btn-action-featured--like:hover {
      background: #d06d31;
    }

    /* Small Regular Card */
    .ih-card-small {
      background: #ffffff;
      border-radius: 20px;
      border: 1px solid #e2e8f0;
      padding: 20px;
      display: flex;
      flex-direction: column;
      gap: 12px;
      box-shadow: 0 1px 3px rgba(0, 0, 0, 0.01);
    }

    .ih-card-small__title {
      font-size: 14px;
      font-weight: 800;
      color: #000000;
      margin: 0;
      letter-spacing: -0.01em;
      line-height: 1.3;
    }

    .ih-card-small__summary {
      font-size: 11.5px;
      color: #64748b;
      line-height: 1.5;
      margin: 0;
      display: -webkit-box;
      -webkit-line-clamp: 3;
      -webkit-box-orient: vertical;
      overflow: hidden;
    }

    .ih-card-small__metrics {
      display: flex;
      gap: 8px;
      margin-top: auto;
    }

    .ih-metric-btn {
      background: #f1f5f9;
      border: none;
      color: #64748b;
      font-size: 10px;
      font-weight: 700;
      padding: 6px 10px;
      border-radius: 8px;
      cursor: pointer;
      display: inline-flex;
      align-items: center;
      gap: 4px;
    }

    .ih-metric-btn:hover {
      background: #e2e8f0;
      color: #0f172a;
    }

    .ih-metric-btn--orange {
      background: #e07a3c;
      color: #ffffff !important;
    }

    .ih-metric-btn--orange:hover {
      background: #d06d31;
    }

    /* Author Tag */
    .ih-card-author {
      display: flex;
      align-items: center;
      gap: 6px;
      margin-top: 4px;
    }

    .ih-card-author__badge {
      width: 16px;
      height: 16px;
      border-radius: 50%;
      background: #000000;
      color: #ffffff;
      font-size: 9px;
      font-weight: 900;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .ih-card-author__name {
      font-size: 11px;
      font-weight: 500;
      color: #64748b;
    }

    /* Activity Panel */
    .ih-card-activity {
      background: #ffffff;
      border-radius: 20px;
      border: 1px solid #e2e8f0;
      padding: 24px;
      display: flex;
      flex-direction: column;
      gap: 20px;
      box-shadow: 0 1px 3px rgba(0, 0, 0, 0.01);
    }

    .ih-card-activity__title {
      font-size: 15px;
      font-weight: 800;
      color: #000000;
      margin: 0;
      letter-spacing: -0.01em;
    }

    .ih-activity-list {
      display: flex;
      flex-direction: column;
      gap: 16px;
    }

    .ih-activity-item {
      display: flex;
      gap: 12px;
      align-items: flex-start;
      border-bottom: 1px solid #f1f5f9;
      padding-bottom: 12px;
    }

    .ih-activity-item:last-child {
      border-bottom: none;
      padding-bottom: 0;
    }

    .ih-activity-avatar {
      width: 32px;
      height: 32px;
      border-radius: 50%;
      object-fit: cover;
      flex-shrink: 0;
    }

    .ih-activity-body {
      display: flex;
      flex-direction: column;
      gap: 2px;
    }

    .ih-activity-text {
      font-size: 11.5px;
      color: #475569;
      margin: 0;
      line-height: 1.4;
    }

    .ih-activity-text strong {
      color: #0f172a;
    }

    .ih-activity-time {
      font-size: 10px;
      color: #94a3b8;
    }

    /* Comments Section */
    .ih-comments-section {
      background: #f8fafc;
      border-top: 1px solid #e2e8f0;
      padding: 16px 24px;
      display: flex;
      flex-direction: column;
      gap: 12px;
    }

    .ih-comments-title {
      font-size: 11px;
      font-weight: 700;
      color: #64748b;
      text-transform: uppercase;
      letter-spacing: 0.02em;
    }

    .ih-comments-list {
      display: flex;
      flex-direction: column;
      gap: 8px;
      max-h: 160px;
      overflow-y: auto;
    }

    .ih-comment-bubble {
      background: #ffffff;
      border: 1px solid #e2e8f0;
      border-radius: 10px;
      padding: 8px 12px;
      font-size: 11px;
    }

    .ih-comment-bubble strong {
      color: #334155;
      display: block;
      margin-bottom: 2px;
    }

    .ih-comment-bubble p {
      margin: 0;
      color: #475569;
      font-weight: 300;
    }

    .ih-comment-form {
      display: flex;
      gap: 8px;
    }

    .ih-comment-input {
      flex-grow: 1;
      border: 1px solid #cbd5e1;
      background: #ffffff;
      border-radius: 8px;
      padding: 6px 10px;
      font-size: 11px;
      outline: none;
    }

    .ih-comment-btn {
      background: #0f172a;
      color: #ffffff;
      border: none;
      font-size: 11px;
      font-weight: 700;
      padding: 6px 12px;
      border-radius: 8px;
      cursor: pointer;
    }

    .animate-fadeIn {
      animation: fadeIn 0.2s ease-out forwards;
    }

    @keyframes fadeIn {
      from { opacity: 0; transform: translateY(4px); }
      to { opacity: 1; transform: translateY(0); }
    }
  `]
})
export class InfoHubComponent {
  contentService = inject(ContentService);
  router = inject(Router);

  expandedComments = signal<{ [key: number]: boolean }>({});
  newComments: { [key: number]: string } = {};

  activeShareModal = signal<Article | null>(null);
  shareLinkedIn = true;
  shareX = false;
  shareIntranet = true;

  toggleComments(id: number): void {
    this.expandedComments.update(prev => ({
      ...prev,
      [id]: !prev[id]
    }));
  }

  commentsExpanded(id: number): boolean {
    return !!this.expandedComments()[id];
  }

  submitComment(id: number): void {
    const com = this.newComments[id]?.trim();
    if (com) {
      this.contentService.addComment(id, com);
      this.newComments[id] = '';
    }
  }

  openShareModal(art: Article): void {
    this.activeShareModal.set(art);
    this.shareLinkedIn = art.shareTargets.includes('LinkedIn');
    this.shareX = art.shareTargets.includes('X');
    this.shareIntranet = art.shareTargets.includes('Intranet');
  }

  closeShareModal(): void {
    this.activeShareModal.set(null);
  }

  confirmShare(): void {
    const art = this.activeShareModal();
    if (art) {
      this.contentService.shareArticle(art.id);
      
      const newTargets: string[] = [];
      if (this.shareLinkedIn) newTargets.push('LinkedIn');
      if (this.shareX) newTargets.push('X');
      if (this.shareIntranet) newTargets.push('Intranet');
      
      art.shareTargets = newTargets;
      
      this.closeShareModal();
    }
  }
}
