<div class="container">
  <div class="profile-layout">
    <!-- Sidebar del perfil -->
    <aside class="profile-sidebar">
      <section class="card profile-card">
        <div class="profile-avatar">
          <?php if(!empty($profile['avatar_url'])): ?>
            <img src="<?php echo htmlspecialchars($profile['avatar_url']); ?>" alt="avatar" class="avatar-image">
          <?php else: ?>
            <div class="avatar-placeholder">
              <?php echo htmlspecialchars(strtoupper(substr($profile['nick'],0,1))); ?>
            </div>
          <?php endif; ?>
        </div>
        
        <div class="profile-info">
        <?php if(isset($state) && $state === 'self'): ?>
          <form method="post" action="<?php echo htmlspecialchars(base_url('/profile/avatar')); ?>" enctype="multipart/form-data" class="avatar-form" style="margin-top:12px;">
            <input type="hidden" name="_csrf" value="<?php echo htmlspecialchars(csrf_token()); ?>">
            <label class="btn btn-secondary" style="display:inline-block;cursor:pointer;">
              Cambiar avatar
              <input type="file" name="avatar" accept="image/*" style="display:none;" onchange="openAvatarCropper(this.files[0])">
            </label>
            <small style="display:block;color:#666;margin-top:6px;">JPG, PNG, WEBP o GIF · máx 2MB</small>
          </form>
        <div id="avatarCropModal" style="display:none; position:fixed; inset:0; background:rgba(0,0,0,.7); backdrop-filter:blur(2px); -webkit-backdrop-filter:blur(2px); z-index:2147483647; align-items:center; justify-content:center;">
          <div style="background:#fff; width:560px; max-width:90vw; border-radius:12px; box-shadow:0 10px 30px rgba(0,0,0,.35); overflow:hidden; position:relative; z-index:2147483646; pointer-events:auto;">
            <div style="padding:14px 18px; border-bottom:1px solid #eee; display:flex; justify-content:space-between; align-items:center;">
              <strong>Recortar avatar</strong>
              <button type="button" onclick="closeAvatarCropper()" class="btn ghost" style="font-size:20px; line-height:1;">×</button>
            </div>
            <div style="padding:16px;">
              <div id="avatarStage" style="width:400px; height:400px; margin:0 auto; position:relative; overflow:hidden; background:#0b0f19; border-radius:8px; border:1px solid rgba(255,255,255,0.08);">
                <img id="avatarImg" style="position:absolute; top:0; left:0; user-select:none; -webkit-user-drag:none; display:none;">
                <!-- Circular mask -->
                <div style="position:absolute; inset:0; pointer-events:none; border-radius:0;">
                  <div style="position:absolute; left:50%; top:50%; width:360px; height:360px; transform:translate(-50%,-50%); border-radius:50%; box-shadow:0 0 0 200px rgba(0,0,0,.6) inset;"></div>
                </div>
              </div>
              <div style="display:flex; align-items:center; gap:12px; margin-top:12px;">
                <label>Zoom</label>
                <input id="avatarZoom" type="range" min="0.5" max="3" step="0.01" value="1" style="flex:1;">
                <button type="button" id="avatarSaveBtn" class="btn btn-primary" disabled>Guardar</button>
                <button type="button" class="btn ghost" onclick="closeAvatarCropper()">Cancelar</button>
              </div>
              <canvas id="avatarCanvas" width="256" height="256" style="display:none;"></canvas>
            </div>
          </div>
        </div>
        <script>
        (function(){
          const modal = document.getElementById('avatarCropModal');
          const img = document.getElementById('avatarImg');
          const stage = document.getElementById('avatarStage');
          const zoom = document.getElementById('avatarZoom');
          const save = document.getElementById('avatarSaveBtn');
          const canvas = document.getElementById('avatarCanvas');
          const ctx = canvas.getContext('2d');
          let naturalW=0, naturalH=0, scale=1, imgX=0, imgY=0, isDown=false, startX=0, startY=0;

          window.openAvatarCropper = (file)=>{ try { if (!document.body.contains(modal)) { /*noop*/ } else { /*noop*/ } } catch(e){}
            if (!file) return;
            const url = URL.createObjectURL(file);
            img.onload = ()=>{
              naturalW = img.naturalWidth; naturalH = img.naturalHeight;
              img.style.display='block';
              scale = 1; imgX = 0; imgY = 0; applyTransform(); fitImage();
              save.disabled = false;
              if (modal.parentNode !== document.body) { modal.__prevParent = modal.parentNode; modal.__prevNext = modal.nextSibling; document.body.appendChild(modal); }
            modal.style.display='flex'; document.body.dataset.prevOverflow = document.body.style.overflow || ''; document.body.style.overflow = 'hidden';
            };
            img.src = url;
          };

          window.closeAvatarCropper = ()=>{
            img.src=''; img.style.display='none';
            modal.style.display='none'; document.body.style.overflow = document.body.dataset.prevOverflow || ''; if (modal.__prevParent) { try { if (modal.__prevNext) { modal.__prevParent.insertBefore(modal, modal.__prevNext); } else { modal.__prevParent.appendChild(modal); } } catch(e){} } 
          };

          function fitImage(){
            const box = 400;
            const k = Math.max(360/naturalW, 360/naturalH); // ensure circular area is covered
            scale = k; zoom.value = Math.max(0.5, Math.min(3, k));
            const viewW = naturalW * scale, viewH = naturalH * scale;
            imgX = (box - viewW)/2; imgY = (box - viewH)/2;
            applyTransform();
          }

          function applyTransform(){
            img.style.transform = `translate(${imgX}px, ${imgY}px) scale(${scale})`;
            img.style.transformOrigin = 'top left';
          }

          function clampPosition(){
            const box = 400;
            const viewW = naturalW * scale, viewH = naturalH * scale;
            // ensure 360 circle (inscribed in 400) is covered -> equivalent to covering 400 square is safe
            if (viewW <= box) imgX = (box - viewW)/2; else { if (imgX > 0) imgX = 0; if (imgX + viewW < box) imgX = box - viewW; }
            if (viewH <= box) imgY = (box - viewH)/2; else { if (imgY > 0) imgY = 0; if (imgY + viewH < box) imgY = box - viewH; }
          }

          zoom.addEventListener('input', ()=>{
            scale = parseFloat(zoom.value);
            clampPosition(); applyTransform();
          });

          stage.addEventListener('mousedown', (e)=>{ isDown = true; startX = e.clientX - imgX; startY = e.clientY - imgY; });
          window.addEventListener('mouseup', ()=> isDown = false);
          window.addEventListener('mousemove', (e)=>{
            if (!isDown) return;
            imgX = e.clientX - startX; imgY = e.clientY - startY;
            clampPosition(); applyTransform();
          });

          save.addEventListener('click', async ()=>{
            if (!naturalW || !naturalH) return;
            // render to 256x256 square, but draw a circular crop onto transparent background
            ctx.clearRect(0,0,256,256);
            ctx.save();
            ctx.beginPath();
            ctx.arc(128,128,128,0,Math.PI*2);
            ctx.closePath();
            ctx.clip();
            // compute source rect relative to image
            // map 400px box to 256px canvas
            const box = 400;
            const sx = (0 - imgX) / scale;
            const sy = (0 - imgY) / scale;
            const sSize = box / scale;
            ctx.imageSmoothingQuality = 'high';
            ctx.drawImage(img, sx, sy, sSize, sSize, 0, 0, 256, 256);
            ctx.restore();
            // export PNG (keeps circular transparency)
            const dataUrl = canvas.toDataURL('image/png');
            // POST to /profile/avatar
            const fd = new FormData();
            fd.append('_csrf', '<?php echo htmlspecialchars(csrf_token()); ?>');
            fd.append('avatar_data', dataUrl);
            const resp = await fetch('<?php echo htmlspecialchars(base_url('/profile/avatar')); ?>', {
              method: 'POST',
              body: fd,
              credentials: 'same-origin'
            });
            if (resp.redirected) window.location.href = resp.url;
            else window.location.reload();
          });
        })();
        </script>
      
          <div style="margin-top:6px;">
            
          </div>
        <?php endif; ?>
      
          <h1 class="profile-nick">@<?php echo htmlspecialchars($profile['nick']); ?></h1>
          
          <?php if(!empty($profile['first_name']) || !empty($profile['last_name'])): ?>
            <p class="profile-name">
              <?php echo htmlspecialchars($profile['first_name'] . ' ' . $profile['last_name']); ?>
            </p>
          <?php endif; ?>
          
          <?php if(!empty($profile['bio'])): ?>
            <p class="profile-bio"><?php echo htmlspecialchars($profile['bio']); ?></p>
          <?php endif; ?>
          
          <div class="profile-stats">
            <div class="stat">
              <strong><?php echo $stats['photos_count'] ?? 0; ?></strong>
              <span>Fotos</span>
            </div>
            <div class="stat">
              <strong><?php echo $stats['friends_count'] ?? 0; ?></strong>
              <span>Amigos</span>
            </div>
          </div>
          
          <div class="profile-actions">
            <?php if($state==='self'): ?>
              <a href="<?php echo htmlspecialchars(base_url('/photos/upload')); ?>" class="btn btn-primary">
                Subir foto
              </a>
              <a href="<?php echo htmlspecialchars(base_url('/profile/edit')); ?>" class="btn btn-secondary">
                Editar perfil
              </a>
            <?php elseif($state==='friend'): ?>
              <div class="friend-status">
                <span class="status-badge success">✅ Sois amigos</span>
                <form method="post" action="<?php echo htmlspecialchars(base_url('/friends/unfriend')); ?>" style="margin-top:8px;">
                  <input type="hidden" name="_csrf" value="<?php echo htmlspecialchars(csrf_token()); ?>">
                  <input type="hidden" name="friend_id" value="<?php echo (int)$profile['id']; ?>">
                  <button type="submit" class="btn btn-ghost" onclick="return confirm('¿Eliminar amistad?')">
                    Eliminar amigo
                  </button>
                </form>
              </div>
            <?php elseif($state==='incoming'): ?>
              <div class="friend-status">
                <span class="status-badge warning">📥 Solicitud recibida</span>
                <div style="display:flex;gap:8px;margin-top:8px;">
                  <form method="post" action="<?php echo htmlspecialchars(base_url('/friends/accept')); ?>">
                    <input type="hidden" name="_csrf" value="<?php echo htmlspecialchars(csrf_token()); ?>">
                    <input type="hidden" name="request_id" value="<?php echo (int)$friend_request_id; ?>">
                    <button type="submit" class="btn btn-success">Aceptar</button>
                  </form>
                  <form method="post" action="<?php echo htmlspecialchars(base_url('/friends/reject')); ?>">
                    <input type="hidden" name="_csrf" value="<?php echo htmlspecialchars(csrf_token()); ?>">
                    <input type="hidden" name="request_id" value="<?php echo (int)$friend_request_id; ?>">
                    <button type="submit" class="btn btn-danger">Rechazar</button>
                  </form>
                </div>
              </div>
            <?php elseif($state==='outgoing'): ?>
              <div class="friend-status">
                <span class="status-badge info">📤 Solicitud enviada</span>
                <form method="post" action="<?php echo htmlspecialchars(base_url('/friends/cancel')); ?>" style="margin-top:8px;">
                  <input type="hidden" name="_csrf" value="<?php echo htmlspecialchars(csrf_token()); ?>">
                  <input type="hidden" name="request_id" value="<?php echo (int)$friend_request_id; ?>">
                  <button type="submit" class="btn btn-ghost">Cancelar solicitud</button>
                </form>
              </div>
            <?php else: ?>
              <form method="post" action="<?php echo htmlspecialchars(base_url('/friends/request')); ?>">
                <input type="hidden" name="_csrf" value="<?php echo htmlspecialchars(csrf_token()); ?>">
                <input type="hidden" name="user_id" value="<?php echo (int)$profile['id']; ?>">
                <button class="btn btn-primary">Agregar amigo</button>
              </form>
            <?php endif; ?>
          </div>
        </div>
      </section>

      <!-- Información adicional -->
      <?php if($state==='self' || $state==='friend'): ?>
        <section class="card">
          <h3>📍 Información</h3>
          <!-- Mostrar provincia y municipio -->
          <?php if(!empty($profile['province_name']) || !empty($profile['municipality_name'])): ?>
            <p><strong>Ubicación:</strong> 
              <?php 
              if (!empty($profile['municipality_name']) && !empty($profile['province_name'])) {
                  echo htmlspecialchars($profile['municipality_name']) . ', ' . htmlspecialchars($profile['province_name']);
              } elseif (!empty($profile['province_name'])) {
                  echo htmlspecialchars($profile['province_name']);
              } else {
                  echo 'Ubicación no especificada';
              }
              ?>
            </p>
          <?php endif; ?>
          <?php if(!empty($profile['dob'])): ?>
            <p><strong>Edad:</strong> <?php echo calculateAge($profile['dob']); ?> años</p>
          <?php endif; ?>
          <p><strong>Miembro desde:</strong> <?php echo date('Y', strtotime($profile['created_at'])); ?></p>
        </section>
      <?php endif; ?>
    </aside>

    <!-- Contenido principal - Fotos -->
    <main class="profile-main">
      <section class="card">
        <div class="section-header">
          <h2>📸 Fotos</h2>
          <?php if($state==='self'): ?>
            <a href="<?php echo htmlspecialchars(base_url('/photos/upload')); ?>" class="btn btn-primary">
              Subir nueva foto
            </a>
          <?php endif; ?>
        </div>

        <?php if ($state !== 'self' && $state !== 'friend'): ?>
          <!-- No son amigos - Mostrar mensaje privado -->
          <div class="empty-state">
            <div class="empty-icon">🔒</div>
            <h3>Perfil privado</h3>
            <p>Agrega a <?php echo htmlspecialchars($profile['nick']); ?> como amigo/a para ver sus fotos.</p>
            <?php if($state === 'none'): ?>
              <form method="post" action="<?php echo htmlspecialchars(base_url('/friends/request')); ?>" style="margin-top: 16px;">
                <input type="hidden" name="_csrf" value="<?php echo htmlspecialchars(csrf_token()); ?>">
                <input type="hidden" name="user_id" value="<?php echo (int)$profile['id']; ?>">
                <button class="btn btn-primary">Enviar solicitud de amistad</button>
              </form>
            <?php elseif($state === 'outgoing'): ?>
              <p class="text-muted">Solicitud de amistad pendiente</p>
            <?php endif; ?>
          </div>
        <?php elseif (empty($photos)): ?>
          <!-- Son amigos pero no hay fotos -->
          <div class="empty-state">
            <div class="empty-icon">📷</div>
            <h3>No hay fotos todavía</h3>
            <p>
              <?php if($state==='self'): ?>
                Comparte tus momentos especiales subiendo tu primera foto.
              <?php else: ?>
                <?php echo htmlspecialchars($profile['nick']); ?> aún no ha compartido fotos.
              <?php endif; ?>
            </p>
            <?php if($state==='self'): ?>
              <a href="<?php echo htmlspecialchars(base_url('/photos/upload')); ?>" class="btn btn-primary">
                Subir mi primera foto
              </a>
            <?php endif; ?>
          </div>
        <?php else: ?>
          <!-- Son amigos y hay fotos - Mostrar galería -->
          <div class="photos-grid">
            <?php foreach ($photos as $photo): ?>
              <div class="photo-card">
                <div class="photo-image">
                  <!-- Imagen como enlace para ver la foto -->
                  <a href="<?php echo htmlspecialchars(base_url('/photo?id=' . $photo['id'])); ?>">
                    <img 
                      src="<?php echo htmlspecialchars(asset_url($photo['storage_rel_path'])); ?>" 
                      alt="Foto" 
                      loading="lazy"
                    >
                  </a>
                  <div class="photo-overlay">
                    <div class="photo-actions">
                      <!-- Botón para ver foto en grande -->
                      <a href="<?php echo htmlspecialchars(base_url('/photo?id=' . $photo['id'])); ?>" class="btn-icon" title="Ver foto">
                        👁️
                      </a>
                      
                      <?php if($state==='self'): ?>
                        <button 
                          class="btn-icon" 
                          title="Editar"
                          onclick="openEditModal(
                            <?php echo (int)$photo['id']; ?>,
                            '<?php echo htmlspecialchars($photo['text'] ?? '', ENT_QUOTES); ?>',
                            '<?php echo htmlspecialchars($photo['visibility']); ?>'
                          )"
                        >
                          ✏️
                        </button>
                        <button 
                          class="btn-icon" 
                          title="Eliminar"
                          onclick="openDeleteModal(<?php echo (int)$photo['id']; ?>)"
                        >
                          🗑️
                        </button>
                      <?php endif; ?>
                    </div>
                  </div>
                </div>
                <div class="photo-info">
                  <?php if (!empty($photo['text'])): ?>
                    <p class="photo-caption"><?php echo htmlspecialchars($photo['text']); ?></p>
                  <?php endif; ?>
                  <div class="photo-meta">
                    <span class="visibility-badge <?php echo $photo['visibility']; ?>">
                      <?php echo $photo['visibility'] === 'friends' ? '👥 Amigos' : '🔒 Privado'; ?>
                    </span>
                    <span class="photo-date"><?php echo formatDate($photo['created_at']); ?></span>
                  </div>
                  <?php if(isset($photo['like_count']) || isset($photo['comment_count'])): ?>
                    <div class="photo-stats">
                      <?php if(isset($photo['like_count'])): ?>
                        <span>❤️ <?php echo (int)$photo['like_count']; ?></span>
                      <?php endif; ?>
                      <?php if(isset($photo['comment_count'])): ?>
                        <span>💬 <?php echo (int)$photo['comment_count']; ?></span>
                      <?php endif; ?>
                    </div>
                  <?php endif; ?>
                </div>
              </div>
            <?php endforeach; ?>
          </div>
        <?php endif; ?>
      </section>
    </main>
  </div>
</div>

<style>
/* CORRECCIÓN DEL CENTRADO - AGREGADO */
.container {
  max-width: 1100px;
  margin: 0 auto;
  padding: 16px;
  display: flex;
  justify-content: center;
}

.profile-layout {
  display: grid;
  grid-template-columns: 350px 1fr;
  gap: 24px;
  align-items: start;
  margin-top: 20px;
  width: 100%;
}

.profile-sidebar {
  position: sticky;
  top: 100px;
}

.profile-card {
  text-align: center;
  padding: 24px;
}

.profile-avatar {
  margin-bottom: 16px;
}

.avatar-image {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  object-fit: cover;
  border: 4px solid #6366f1;
}

.avatar-placeholder {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  background: linear-gradient(135deg, #6366f1, #8b5cf6);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 2rem;
  font-weight: bold;
  margin: 0 auto;
  border: 4px solid #6366f1;
}

.profile-nick {
  font-size: 1.5rem;
  font-weight: 700;
  margin-bottom: 8px;
  color: #f8fafc;
}

.profile-name {
  color: #94a3b8;
  margin-bottom: 12px;
  font-size: 1.1rem;
}

.profile-bio {
  color: #cbd5e1;
  line-height: 1.5;
  margin-bottom: 20px;
  font-style: italic;
}

.profile-stats {
  display: flex;
  justify-content: center;
  gap: 24px;
  margin-bottom: 20px;
  padding: 16px 0;
  border-top: 1px solid #2b3138;
  border-bottom: 1px solid #2b3138;
}

.stat {
  text-align: center;
}

.stat strong {
  display: block;
  font-size: 1.5rem;
  color: #f8fafc;
}

.stat span {
  font-size: 0.85rem;
  color: #94a3b8;
}

.profile-actions {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.friend-status {
  text-align: center;
}

.status-badge {
  display: inline-block;
  padding: 6px 12px;
  border-radius: 20px;
  font-size: 0.85rem;
  font-weight: 500;
}

.status-badge.success {
  background: #10b98120;
  color: #10b981;
  border: 1px solid #10b98140;
}

.status-badge.warning {
  background: #f59e0b20;
  color: #f59e0b;
  border: 1px solid #f59e0b40;
}

.status-badge.info {
  background: #6366f120;
  color: #6366f1;
  border: 1px solid #6366f140;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-header h2 {
  margin: 0;
  color: #f8fafc;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: #94a3b8;
}

.empty-icon {
  font-size: 4rem;
  margin-bottom: 16px;
  opacity: 0.5;
}

.empty-state h3 {
  color: #cbd5e1;
  margin-bottom: 8px;
}

.text-muted {
  color: #64748b;
  font-style: italic;
}

/* Fotos más pequeñas */
.photos-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 15px;
}

.photo-card {
  background: #1a1d23;
  border: 1px solid #2b3138;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s ease;
}

.photo-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 25px rgba(0,0,0,0.15);
  border-color: #6366f1;
}

.photo-image {
  position: relative;
  overflow: hidden;
  aspect-ratio: 1;
  max-height: 200px;
}

.photo-image a {
  display: block;
  width: 100%;
  height: 100%;
}

.photo-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.photo-card:hover .photo-image img {
  transform: scale(1.05);
}

.photo-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.photo-card:hover .photo-overlay {
  opacity: 1;
}

.photo-actions {
  display: flex;
  gap: 8px;
}

.btn-icon {
  background: rgba(255,255,255,0.9);
  border: none;
  border-radius: 8px;
  padding: 8px;
  cursor: pointer;
  font-size: 1rem;
  transition: all 0.2s ease;
  text-decoration: none;
  color: #000;
  display: flex;
  align-items: center;
  justify-content: center;
  min-width: 36px;
  min-height: 36px;
}

.btn-icon:hover {
  background: white;
  transform: scale(1.1);
}

.photo-info {
  padding: 12px;
}

.photo-caption {
  color: #f8fafc;
  margin-bottom: 8px;
  line-height: 1.4;
  word-break: break-word;
  font-size: 0.9rem;
}

.photo-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
  font-size: 0.75rem;
}

.visibility-badge {
  padding: 4px 8px;
  border-radius: 6px;
  font-size: 0.75rem;
  font-weight: 500;
}

.visibility-badge.friends {
  background: #6366f120;
  color: #6366f1;
}

.visibility-badge.private {
  background: #64748b20;
  color: #64748b;
}

.photo-date {
  color: #94a3b8;
  font-size: 0.75rem;
}

.photo-stats {
  display: flex;
  gap: 12px;
  color: #94a3b8;
  font-size: 0.8rem;
}

/* Modales */
.modal {
  display: none;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0,0,0,0.8);
  z-index: 1000;
  align-items: center;
  justify-content: center;
}

.modal-content {
  background: #1a1d23;
  border-radius: 12px;
  padding: 20px;
  max-width: 500px;
  width: 90%;
  border: 1px solid #2b3138;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.modal-title {
  font-size: 1.2rem;
  font-weight: 600;
  color: #f8fafc;
}

.close-modal {
  background: none;
  border: none;
  color: #94a3b8;
  font-size: 1.5rem;
  cursor: pointer;
}

.close-modal:hover {
  color: #f8fafc;
}

.form-group {
  margin-bottom: 16px;
}

.form-label {
  display: block;
  margin-bottom: 8px;
  color: #cbd5e1;
  font-weight: 500;
}

.form-input, .form-textarea, .form-select {
  width: 100%;
  padding: 10px 12px;
  background: #2b3138;
  border: 1px solid #3f4752;
  border-radius: 6px;
  color: #f8fafc;
  font-size: 0.9rem;
}

.form-textarea {
  resize: vertical;
  min-height: 80px;
}

.form-actions {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
  margin-top: 20px;
}

.btn {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  padding: 10px 16px;
  border-radius: 8px;
  font-weight: 500;
  text-decoration: none;
  border: none;
  cursor: pointer;
  transition: all 0.2s ease;
  font-size: 0.9rem;
}

.btn-primary {
  background: #6366f1;
  color: white;
}

.btn-primary:hover {
  background: #4f46e5;
  transform: translateY(-1px);
}

.btn-secondary {
  background: rgba(255,255,255,0.1);
  color: #f8fafc;
  border: 1px solid rgba(255,255,255,0.2);
}

.btn-secondary:hover {
  background: rgba(255,255,255,0.15);
}

.btn-ghost {
  background: transparent;
  color: #94a3b8;
  border: 1px solid #2b3138;
}

.btn-ghost:hover {
  background: rgba(255,255,255,0.05);
  color: #f8fafc;
}

.btn-success {
  background: #10b981;
  color: white;
}

.btn-success:hover {
  background: #059669;
}

.btn-danger {
  background: #ef4444;
  color: white;
}

.btn-danger:hover {
  background: #dc2626;
}

.card {
  background: #1a1d23;
  border: 1px solid #2b3138;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

@media (max-width: 968px) {
  .profile-layout {
    grid-template-columns: 1fr;
    gap: 16px;
  }
  
  .profile-sidebar {
    position: static;
  }
  
  .photos-grid {
    grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
  }
}

@media (max-width: 640px) {
  .photos-grid {
    grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  }
  
  .profile-stats {
    gap: 16px;
  }
  
  .section-header {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }
}
</style>

<?php
// Funciones helper (deberían estar en tu archivo de helpers)
function calculateAge($dob) {
  $birthdate = new DateTime($dob);
  $today = new DateTime();
  $age = $today->diff($birthdate);
  return $age->y;
}

function formatDate($date) {
  $datetime = new DateTime($date);
  $now = new DateTime();
  $diff = $now->diff($datetime);
  
  if ($diff->days == 0) return 'Hoy';
  if ($diff->days == 1) return 'Ayer';
  if ($diff->days < 7) return "Hace {$diff->days} días";
  if ($diff->days < 30) return "Hace " . floor($diff->days / 7) . " semanas";
  if ($diff->days < 365) return "Hace " . floor($diff->days / 30) . " meses";
  
  return "Hace " . floor($diff->days / 365) . " años";
}
?>

<!-- Modales para editar y eliminar fotos -->
<?php if($state==='self' && !empty($photos)): ?>
<!-- Modal Editar Foto -->
<div id="editPhotoModal" class="modal">
  <div class="modal-content">
    <div class="modal-header">
      <h3 class="modal-title">Editar Foto</h3>
      <button class="close-modal" onclick="closeEditModal()">&times;</button>
    </div>
    <form id="editPhotoForm" method="post" action="<?php echo htmlspecialchars(base_url('/photos/update')); ?>">
      <input type="hidden" name="_csrf" value="<?php echo htmlspecialchars(csrf_token()); ?>">
      <input type="hidden" name="photo_id" id="edit_photo_id">
      
      <div class="form-group">
        <label class="form-label" for="edit_photo_text">Descripción</label>
        <textarea class="form-textarea" id="edit_photo_text" name="text" maxlength="500" placeholder="Añade una descripción..."></textarea>
      </div>
      
      <div class="form-group">
        <label class="form-label" for="edit_photo_visibility">Visibilidad</label>
        <select class="form-select" id="edit_photo_visibility" name="visibility">
          <option value="friends">👥 Amigos</option>
          <option value="private">🔒 Privado</option>
        </select>
      </div>
      
      <div class="form-actions">
        <button type="button" class="btn btn-ghost" onclick="closeEditModal()">Cancelar</button>
        <button type="submit" class="btn btn-primary">Guardar Cambios</button>
      </div>
    </form>
  </div>
</div>

<!-- Modal Eliminar Foto -->
<div id="deletePhotoModal" class="modal">
  <div class="modal-content">
    <div class="modal-header">
      <h3 class="modal-title">Eliminar Foto</h3>
      <button class="close-modal" onclick="closeDeleteModal()">&times;</button>
    </div>
    <p>¿Estás seguro de que quieres eliminar esta foto? Esta acción no se puede deshacer.</p>
    <form id="deletePhotoForm" method="post" action="<?php echo htmlspecialchars(base_url('/photos/delete')); ?>">
      <input type="hidden" name="_csrf" value="<?php echo htmlspecialchars(csrf_token()); ?>">
      <input type="hidden" name="photo_id" id="delete_photo_id">
      
      <div class="form-actions">
        <button type="button" class="btn btn-ghost" onclick="closeDeleteModal()">Cancelar</button>
        <button type="submit" class="btn btn-danger">Eliminar Foto</button>
      </div>
    </form>
  </div>
</div>

<script>
// Variables para almacenar datos de la foto
let currentPhotoData = {};

// Abrir modal de edición
function openEditModal(photoId, text, visibility) {
  currentPhotoData = {
    id: photoId,
    text: text || '',
    visibility: visibility
  };
  
  document.getElementById('edit_photo_id').value = photoId;
  document.getElementById('edit_photo_text').value = text || '';
  document.getElementById('edit_photo_visibility').value = visibility;
  
  document.getElementById('editPhotoModal').style.display = 'flex';
}

// Cerrar modal de edición
function closeEditModal() {
  document.getElementById('editPhotoModal').style.display = 'none';
  currentPhotoData = {};
}

// Abrir modal de eliminación
function openDeleteModal(photoId) {
  document.getElementById('delete_photo_id').value = photoId;
  document.getElementById('deletePhotoModal').style.display = 'flex';
}

// Cerrar modal de eliminación
function closeDeleteModal() {
  document.getElementById('deletePhotoModal').style.display = 'none';
}

// Cerrar modales al hacer clic fuera
window.onclick = function(event) {
  const editModal = document.getElementById('editPhotoModal');
  const deleteModal = document.getElementById('deletePhotoModal');
  
  if (event.target === editModal) {
    closeEditModal();
  }
  if (event.target === deleteModal) {
    closeDeleteModal();
  }
}

// Manejar envío del formulario de edición
document.getElementById('editPhotoForm').addEventListener('submit', function(e) {
  // Aquí puedes agregar validaciones adicionales si es necesario
  console.log('Editando foto:', currentPhotoData.id);
});

// Manejar envío del formulario de eliminación
document.getElementById('deletePhotoForm').addEventListener('submit', function(e) {
  if (!confirm('¿Estás completamente seguro de que quieres eliminar esta foto?')) {
    e.preventDefault();
  }
});
</script>
<?php endif; ?>