//
//  custlayout.swift
//  wallpaper_project



import Foundation
import UIKit


//class CustomLayout: UICollectionViewLayout {
//    private var cache: [UICollectionViewLayoutAttributes] = []
//    private var contentHeight: CGFloat = 0
//    
//    override var collectionViewContentSize: CGSize {
//        return CGSize(width: collectionView?.bounds.width ?? 0, height: contentHeight)
//    }
//    
//    override func prepare() {
//        guard let collectionView = collectionView else { return }
//        cache.removeAll()
//        
//        let width = collectionView.bounds.width
//        var yOffset: CGFloat = 0
//        
//        for item in 0..<collectionView.numberOfItems(inSection: 0) {
//            let indexPath = IndexPath(item: item, section: 0)
//            let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
//            
//            let frame = CGRect(x: 0, y: yOffset, width: width, height: collectionView.bounds.height * 2.5 / 3)
//            yOffset += collectionView.bounds.height * 2.5 / 3
//            
//            attributes.frame = frame
//            cache.append(attributes)
//        }
//        
//        contentHeight = yOffset
//    }
//    
//    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
//        return cache.filter { $0.frame.intersects(rect) }
//    }
//    
//    override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
//        return cache[indexPath.item]
//    }
//}

class CustomLayout: UICollectionViewLayout {
    private var cache: [UICollectionViewLayoutAttributes] = []
    private var contentHeight: CGFloat = 0
    
    override var collectionViewContentSize: CGSize {
        return CGSize(width: collectionView?.bounds.width ?? 0, height: contentHeight)
    }
    
    override func prepare() {
        guard let collectionView = collectionView else { return }
        cache.removeAll()
        
        let width = collectionView.bounds.width
        var yOffset: CGFloat = 0
        
        for item in 0..<collectionView.numberOfItems(inSection: 0) {
            let indexPath = IndexPath(item: item, section: 0)
            let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
            
            let frame = CGRect(x: 0, y: yOffset, width: width, height: collectionView.bounds.height * 2.5 / 3)
            yOffset += collectionView.bounds.height * 2.5 / 3
            
            attributes.frame = frame
            cache.append(attributes)
        }
        
        contentHeight = yOffset
    }
    
    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        return cache.filter { $0.frame.intersects(rect) }
    }
    
    override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
        return cache[indexPath.item]
    }
}
