import SwiftUI

struct ViewANeumorphicStyle2: ButtonStyle {
    var isPressedStyle: Bool = false
    
    func makeBody(configuration: Self.Configuration) -> some View {
        configuration.label
            .padding(20)
            .foregroundColor(.white) 
            .background(
                Group {
                    if configuration.isPressed || isPressedStyle {
                        Capsule()
                            .fill(Color(.systemGray5))
                            .overlay(
                                Capsule()
                                    .stroke(Color.white, lineWidth: 4)
                                    .shadow(color: Color.white.opacity(0.7), radius: 10, x: -5, y: -5)
                                    .shadow(color: Color.black.opacity(0.2), radius: 10, x: 5, y: 5)
                            )
                    } else {
                        Capsule()
                            .fill(Color(.systemGray6))
                            .shadow(color: Color.black.opacity(0.2), radius: 10, x: 5, y: 5)
                            .shadow(color: Color.white.opacity(0.7), radius: 10, x: -5, y: -5)
                    }
                }
            )
            .scaleEffect(configuration.isPressed ? 0.95 : 1)
            .animation(.spring(), value: configuration.isPressed)
    }
}

struct ViewANeumorphicButton2: View {
    var title: String
    var imageName: String? = nil
    var action: () -> Void
    var isPressedStyle: Bool = false
    
    var body: some View {
        Button(action: action) {
            if let imageName = imageName {
                Label(title, systemImage: imageName)
                    .foregroundColor(.gray)
            } else {
                Text(title)
                    .foregroundColor(.gray)
            }
        }
        .buttonStyle(ViewANeumorphicStyle2(isPressedStyle: isPressedStyle))
    }
}

struct DrawingLine2 {
    var points: [CGPoint]
    var color: Color
}

struct CanvasDrawingExample: View {
    @State private var lines: [DrawingLine2] = []
    @State private var selectedColor = Color.orange
    @State private var showPopup: Bool = false
    @State private var fullscreenImageIndex: Int? = nil
    @State private var selectedButton: String? = "Standard Canvas"
    @State private var iPhoneScaleFactor: CGFloat = 0.70
    @State private var iPadScaleFactor: CGFloat = 0.7
    @State private var squaresScaleFactor: CGFloat = 0.95
    @State private var showClearConfirmationAlert = false 
    

    
    let images = [
        "draw1", "draw2", "draw3", "draw4", "draw5"
    ]
    
    @State private var imageTexts = [
        "1.    Penneetui/nØverst på siden finder du dit penneetui. Det indeholder et udvalg af farver—klik på den farve, du ønsker, og brug derefter din finger eller Apple Pencil til at tegne på skærmen. Skal du slette noget? Vælg viskelæderet til venstre og svej med din finger for at fjerne det, du vil. Vil du starte forfra? Klik på blyanten med et minus-tegn for at slette alle dine tegninger.",
        "2.    Idégenerering/nPå denne side skal du udvikle dine indledende ideer til din app. I hver af de 8 felter kan du tegne, illustrere og nedskrive nøgleord for at støtte din tekst. Når du har illustreret dine 8 ideer, skal du tage et skærmbillede og indsætte det i din portfolio, som findes nederst til højre i menuen i denne app.",
        "3.    Lærred/nHer har du mulighed for at tegne og illustrere på et blankt lærred for at vise og visualisere dine ideer til layout, indhold og funktioner af din app.",
        "4.    iPhone/nHer kan du tegne og illustrere din app-idé inden for iPhone-rammer for at demonstrere og give indsigt i dine ideer til layout, indhold og funktioner af din app.",
        "5.    iPad/nHer kan du tegne og illustrere din app-idé inden for iPad-rammer for at demonstrere og give indsigt i dine ideer til layout, indhold og funktioner af din app."
    ]
    
    enum CanvasMode {
        case standard, iPhone, iPad, squares
    }
    
    var body: some View {
        ZStack {
            Color.white.edgesIgnoringSafeArea(.all)
            
            VStack {
                HStack {
                    ForEach([Color.green, .orange, .blue, .red, .pink, .black, .purple], id: \.self) { color in
                        colorButton(color: color)
                    }
                    eraserButton()
                    clearButton()
                }
                
                Canvas { ctx, size in
                    switch selectedButton {
                    case "iPhone":
                        drawIPhoneScaffold(ctx: ctx, size: size, scaleFactor: iPhoneScaleFactor)
                    case "iPad":
                        drawIPadScaffold(ctx: ctx, size: size, scaleFactor: iPadScaleFactor)
                    case "8 Squares":
                        drawSquaresScaffold(ctx: ctx, size: size, scaleFactor: squaresScaleFactor)
                    default:
                        break
                    }
                    
                    for line in lines {
                        var path = Path()
                        path.addLines(line.points)
                        
                        ctx.stroke(path, with: .color(line.color), style: StrokeStyle(lineWidth: 5, lineCap: .round, lineJoin: .round))
                    }
                }
                .gesture(
                    DragGesture(minimumDistance: 0, coordinateSpace: .local)
                        .onChanged({ value in
                            let position = value.location
                            
                            if value.translation == .zero {
                                lines.append(DrawingLine2(points: [position], color: selectedColor))
                            } else {
                                guard let lastIdx = lines.indices.last else {
                                    return
                                }
                                
                                lines[lastIdx].points.append(position)
                            }
                        })
                )
                .padding(.bottom, 60)
            }
            
            VStack {
                Spacer()
                
                HStack {
                    Spacer()
                    
                    Button(action: {
                        showPopup.toggle()
                    }) {
                        Image(systemName: "info.circle")
                            .font(.largeTitle)
                            .padding()
                            .foregroundColor(.black)
                            .clipShape(Circle())
                    }
                    .padding(.trailing, 20)
                    .padding(.bottom, 20)
                }
            }
            
            VStack {
                Spacer()
                
                HStack(spacing: 10) {
                    
                    ViewANeumorphicButton2(title: "Idegenerering", isPressedStyle: selectedButton == "8 Squares") {
                        selectedButton = "8 Squares"}
                    .frame(width: 160, height: 50)
                    .background(Color.white) 
                    
                    ViewANeumorphicButton2(title: "         Blank           ", isPressedStyle: selectedButton == "Blank") {
                        selectedButton = "Blank"
                        
                    }
                    .frame(width: 160, height: 50)
                    .background(Color.white) 
                    
                  
                    ViewANeumorphicButton2(title: "        iPhone        ", isPressedStyle: selectedButton == "iPhone") {
                        selectedButton = "iPhone"
                    }
                    .frame(width: 160, height: 50)
                    .background(Color.white) 
                    
                    
                    ViewANeumorphicButton2(title: "           iPad           ", isPressedStyle: selectedButton == "iPad") {
                        selectedButton = "iPad"
                    }
                    .frame(width: 160, height: 50)
                    .background(Color.white) 
                }
                .padding(.bottom, 20)
            }
            
            if showPopup {
                PopupView4(showPopup: $showPopup, images: images, imageTexts: $imageTexts, fullscreenImageIndex: $fullscreenImageIndex)
                    .transition(.scale)
                    .zIndex(1)
            }
            
            if let fullscreenImageIndex = fullscreenImageIndex {
                FullscreenImageView3(images: images, descriptions: imageTexts, currentIndex: fullscreenImageIndex, fullscreenImageIndex: $fullscreenImageIndex)
                    .zIndex(2)
            }
        }
    }
    
    @ViewBuilder
    func colorButton(color: Color) -> some View {
        Button {
            selectedColor = color
        } label: {
            Image(systemName: "circle.fill")
                .font(.largeTitle)
                .foregroundColor(color)
                .mask {
                    Image(systemName: "pencil.tip")
                        .font(.largeTitle)
                }
        }
    }
    
    @ViewBuilder
    func eraserButton() -> some View {
        Button {
            selectedColor = .white
        } label: {
            Image(systemName: "eraser")
                .font(.largeTitle)
                .foregroundColor(.gray)
        }
    }
    
    @ViewBuilder
    func clearButton() -> some View {
        Button {
            showClearConfirmationAlert = true
        } label: {
            Image(systemName: "pencil.tip.crop.circle.badge.minus")
                .font(.largeTitle)
                .foregroundColor(.gray)
        }
        .alert(isPresented: $showClearConfirmationAlert) {
            Alert(
                title: Text("Er du sikker?"),
                message: Text("Er du sikker på at du vil slette alt det du har lavet?"),
                primaryButton: .destructive(Text("D")) {
                    lines = []
                },
                secondaryButton: .cancel()
            )
        }
    }
    
    func drawIPhoneScaffold(ctx: GraphicsContext, size: CGSize, scaleFactor: CGFloat) {
        let aspectRatio: CGFloat = 9 / 19.5
        let scaffoldWidth = min(size.width * scaleFactor, size.height * aspectRatio * scaleFactor)
        let scaffoldHeight = scaffoldWidth / aspectRatio
        
        let scaffoldRect1 = CGRect(x: (size.width - scaffoldWidth * 2 - 20) / 2, y: (size.height - scaffoldHeight) / 2, width: scaffoldWidth, height: scaffoldHeight)
        let scaffoldRect2 = CGRect(x: scaffoldRect1.maxX + 20, y: scaffoldRect1.minY, width: scaffoldWidth, height: scaffoldHeight)
        
        ctx.stroke(Path(roundedRect: scaffoldRect1, cornerRadius: 20), with: .color(.gray), style: StrokeStyle(lineWidth: 2))
        ctx.stroke(Path(roundedRect: scaffoldRect2, cornerRadius: 20), with: .color(.gray), style: StrokeStyle(lineWidth: 2))
    }
    
    func drawIPadScaffold(ctx: GraphicsContext, size: CGSize, scaleFactor: CGFloat) {
        let aspectRatio: CGFloat = 4 / 3
        let scaffoldWidth = min(size.width * scaleFactor, size.height * aspectRatio * scaleFactor)
        let scaffoldHeight = scaffoldWidth / aspectRatio
        
        let scaffoldRect1 = CGRect(x: (size.width - scaffoldWidth) / 2, y: (size.height - scaffoldHeight) / 2, width: scaffoldWidth, height: scaffoldHeight)
        
        ctx.stroke(Path(roundedRect: scaffoldRect1, cornerRadius: 20), with: .color(.gray), style: StrokeStyle(lineWidth: 2))
    }
    
    func drawSquaresScaffold(ctx: GraphicsContext, size: CGSize, scaleFactor: CGFloat) {
        let rows = 2
        let cols = 4
        let padding: CGFloat = 10
        let totalPaddingH = padding * CGFloat(cols + 1)
        let totalPaddingV = padding * CGFloat(rows + 1)
        let squareSize = min((size.width * scaleFactor - totalPaddingH) / CGFloat(cols), (size.height * scaleFactor - totalPaddingV) / CGFloat(rows))
        
        for row in 0..<rows {
            for col in 0..<cols {
                let x = (size.width - squareSize * CGFloat(cols) - totalPaddingH) / 2 + CGFloat(col) * (squareSize + padding) + padding
                let y = (size.height - squareSize * CGFloat(rows) - totalPaddingV) / 2 + CGFloat(row) * (squareSize + padding) + padding
                let squareRect = CGRect(x: x, y: y, width: squareSize, height: squareSize)
                
                ctx.stroke(Path(roundedRect: squareRect, cornerRadius: 5), with: .color(.gray), style: StrokeStyle(lineWidth: 2))
            }
        }
    }
    

    
   
    }



struct FullscreenImageView3: View {
    let images: [String]
    let descriptions: [String]
    @State var currentIndex: Int
    @Binding var fullscreenImageIndex: Int?
    
    var body: some View {
        ZStack {
            Color.black.ignoresSafeArea()
            
            VStack {
                TabView(selection: $currentIndex) {
                    ForEach(0..<images.count, id: \.self) { index in
                        VStack {
                            Image(images[index])
                                .resizable()
                                .scaledToFit()
                                .frame(maxWidth: .infinity, maxHeight: .infinity)
                                .onTapGesture {
                                    withAnimation {
                                        fullscreenImageIndex = nil
                                    }
                                }
                                .padding()
                            
                            ScrollView {
                                Text(descriptions[index])
                                    .padding()
                                    .background(RoundedRectangle(cornerRadius: 10).fill(Color.white).overlay(RoundedRectangle(cornerRadius: 10).stroke(Color.black, lineWidth: 1)))
                                    .padding()
                                    .foregroundColor(.black) 
                                    .multilineTextAlignment(.center) 
                            }
                            .frame(maxHeight: 150)
                        }
                        .tag(index)
                    }
                }
                .tabViewStyle(PageTabViewStyle())
                .indexViewStyle(PageIndexViewStyle())
                
                Spacer()
            }
        }
    }
}


struct PopupView4: View {
    @Binding var showPopup: Bool
    let images: [String]
    @Binding var imageTexts: [String]
    @Binding var fullscreenImageIndex: Int?
    @State private var currentPage: Int = 0
    
    var body: some View {
        VStack(spacing: 20) {
            Text("Hvad er an app about apps?")
                .font(.headline)
                .foregroundColor(.black) 
                .padding()
            
            TabView(selection: $currentPage) {
                ForEach(0..<images.count, id: \.self) { index in
                    VStack {
                        Image(images[index])
                            .resizable()
                            .aspectRatio(contentMode: .fit)
                            .frame(width: 400, height: 300)
                            .onTapGesture {
                                withAnimation {
                                    fullscreenImageIndex = index
                                }
                            }
                        
                        ScrollView {
                            Text(imageTexts[index])
                                .font(.body)
                                .multilineTextAlignment(.center) 
                                .padding()
                                .background(Color.white)
                                .cornerRadius(10)
                                .frame(maxWidth: .infinity, alignment: .center) 
                                .foregroundColor(.black) 
                        }
                        .frame(height: 150)
                    }
                    .tag(index)
                }
            }
            .tabViewStyle(PageTabViewStyle())
            .frame(width: 600, height: 400)
            
            VStack {
                Text("\(currentPage + 1) of \(images.count)")
                    .font(.footnote)
                    .padding(5)
                
                Button(action: {
                    showPopup = false
                }) {
                    Image(systemName: "xmark.circle")
                        .font(.title2)
                        .padding()
                        .foregroundColor(.black)
                        .cornerRadius(10)
                }
                .padding(.top, 5)
            }
        }
        .frame(width: 600, height: 600)
        .background(Color.white)
        .cornerRadius(20)
        .shadow(radius: 20)
        .padding()
    }
}

struct ViewA: View {
    var body: some View {
        CanvasDrawingExample()
    }
}

struct ViewA_Previews: PreviewProvider {
    static var previews: some View {
        ViewA()
    }
}

