import express from 'express';
import api from '../config/api.js';

const router = express.Router();

router.get('/', async (req, res) => {
  try {
    const [toursRes, testimonialsRes, blogsRes, destRes] = await Promise.all([
      api.get('/public/tours', { params: { limit: 8 } }),
      api.get('/public/testimonials'),
      api.get('/public/blogs', { params: { limit: 3 } }),
      api.get('/public/destinations')
    ]);
    res.render('pages/home', {
      title: 'Home',
      tours: toursRes.data.tours,
      testimonials: testimonialsRes.data,
      blogs: blogsRes.data.blogs,
      destinations: destRes.data.slice(0, 6)
    });
  } catch (err) {
    console.error('Home page error:', err.message);
    res.render('pages/home', { title: 'Home', tours: [], testimonials: [], blogs: [], destinations: [] });
  }
});

router.get('/about', async (req, res) => {
  try {
    const [pageRes, testimonialsRes] = await Promise.all([
      api.get('/public/pages/about'),
      api.get('/public/testimonials')
    ]);
    res.render('pages/about', { title: 'About Us', page: pageRes.data, testimonials: testimonialsRes.data });
  } catch (err) {
    console.error('About page error:', err.message);
    res.render('pages/about', { title: 'About Us', page: { title: 'About Us', content: '' }, testimonials: [] });
  }
});

router.get('/destinations', async (req, res) => {
  try {
    const { data } = await api.get('/public/destinations');
    res.render('pages/destinations', { title: 'Destinations', destinations: data });
  } catch (err) {
    console.error('Destinations page error:', err.message);
    res.render('pages/destinations', { title: 'Destinations', destinations: [] });
  }
});

router.get('/destinations/:slug', async (req, res) => {
  try {
    const { data } = await api.get(`/public/destinations/${req.params.slug}`);
    res.render('pages/destination-detail', { title: data.name, destination: data, tours: data.tours });
  } catch (err) {
    if (err.response?.status === 404) {
      return res.status(404).render('pages/404', { title: 'Destination Not Found' });
    }
    console.error('Destination detail error:', err.message);
    res.status(500).render('pages/404', { title: 'Something Went Wrong' });
  }
});

router.get('/faq', async (req, res) => {
  try {
    const { data } = await api.get('/public/faqs');
    const grouped = data.reduce((acc, faq) => {
      acc[faq.category] = acc[faq.category] || [];
      acc[faq.category].push(faq);
      return acc;
    }, {});
    res.render('pages/faq', { title: 'FAQs', grouped });
  } catch (err) {
    console.error('FAQ page error:', err.message);
    res.render('pages/faq', { title: 'FAQs', grouped: {} });
  }
});

router.get('/contact', async (req, res) => {
  try {
    const { data } = await api.get('/public/pages/contact-intro');
    res.render('pages/contact', { title: 'Contact Us', page: data, sent: req.query.sent === '1', formError: null });
  } catch (err) {
    res.render('pages/contact', { title: 'Contact Us', page: { title: 'Get In Touch', content: '' }, sent: req.query.sent === '1', formError: null });
  }
});

router.post('/contact', async (req, res) => {
  const { name, email, subject, message } = req.body;
  try {
    await api.post('/public/contact', { name, email, subject, message });
    res.redirect('/contact?sent=1');
  } catch (err) {
    console.error('Contact submit error:', err.message);
    let page = { title: 'Get In Touch', content: '' };
    try {
      const { data } = await api.get('/public/pages/contact-intro');
      page = data;
    } catch (_) {}
    res.render('pages/contact', {
      title: 'Contact Us',
      page,
      sent: false,
      formError: err.response?.data?.message || 'Failed to send your message. Please try again.'
    });
  }
});

const renderLegalPage = (slug, title) => async (req, res) => {
  try {
    const { data } = await api.get(`/public/pages/${slug}`);
    res.render('pages/legal', { title: data.title || title, page: data });
  } catch (err) {
    res.render('pages/legal', { title, page: { title, content: '<p>Content coming soon.</p>' } });
  }
};

router.get('/privacy-policy', renderLegalPage('privacy-policy', 'Privacy Policy'));
router.get('/terms-conditions', renderLegalPage('terms-conditions', 'Terms & Conditions'));
router.get('/cancellation-policy', renderLegalPage('cancellation-policy', 'Cancellation Policy'));

export default router;
