export async function POST(request: Request) {
  try {
    const { email } = await request.json()

    if (!email || !email.includes('@')) {
      return Response.json({
        success: false,
        error: 'Please provide a valid email address'
      }, { status: 400 })
    }

    const MAILCHIMP_API_KEY = process.env.MAILCHIMP_API_KEY || '6951b8172cace4f040d8717c2ff9d77d-us4'
    const AUDIENCE_ID = process.env.MAILCHIMP_AUDIENCE_ID || '28f1945bb4'
    const DATACENTER = MAILCHIMP_API_KEY.split('-')[1] // Extract 'us4' from API key

    if (!MAILCHIMP_API_KEY || !AUDIENCE_ID) {
      console.error('Missing Mailchimp configuration')
      return Response.json({
        success: false,
        error: 'Mailing list service is not configured'
      }, { status: 500 })
    }

    const url = `https://${DATACENTER}.api.mailchimp.com/3.0/lists/${AUDIENCE_ID}/members`

    console.log('Subscribing email to Mailchimp:', email)

    const response = await fetch(url, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${MAILCHIMP_API_KEY}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        email_address: email,
        status: 'subscribed',
        tags: ['website-footer'],
        merge_fields: {
          SOURCE: 'Website Footer'
        }
      }),
    })

    const data = await response.json()

    if (response.ok) {
      console.log('Successfully subscribed:', email)
      return Response.json({
        success: true,
        message: 'Successfully subscribed to mailing list!'
      })
    } else {
      console.error('Mailchimp API error:', data)
      
      // Handle specific Mailchimp errors
      if (data.title === 'Member Exists') {
        return Response.json({
          success: false,
          error: 'This email is already subscribed to our mailing list!'
        })
      } else if (data.title === 'Invalid Resource') {
        return Response.json({
          success: false,
          error: 'Please provide a valid email address.'
        })
      } else if (data.title === 'Forbidden') {
        return Response.json({
          success: false,
          error: 'Invalid API credentials. Please contact support.'
        })
      } else {
        return Response.json({
          success: false,
          error: data.detail || 'Failed to subscribe. Please try again.'
        })
      }
    }

  } catch (error) {
    console.error('Mailchimp subscription error:', error)
    return Response.json({
      success: false,
      error: 'Something went wrong. Please try again later.'
    }, { status: 500 })
  }
}
