const express = require('express');
const router = express.Router();
const nodemailer = require('nodemailer');
const store = require('../store');

const CATS = {
  residences: 'residence', residence: 'residence',
  villas: 'villa', villa: 'villa'
};
const CAT_LABEL = { residence: 'Résidences', villa: 'Villas' };

// URL absolue du site (pour SEO : canonical, sitemap, partages sociaux)
function baseUrl(req) {
  if (process.env.SITE_URL) return process.env.SITE_URL.replace(/\/$/, '');
  const proto = req.headers['x-forwarded-proto'] || req.protocol || 'https';
  return proto + '://' + req.get('host');
}

// ---------- API (consommée par le JS du site) ----------
router.get('/api/biens', (req, res) => res.json(store.activeBiens()));
router.get('/api/avantages', (req, res) => res.json(store.activeAvantages()));
router.get('/api/content', (req, res) => {
  const all = store.getContent(); const out = {};
  for (const k of Object.keys(all)) if (k[0] !== '_') out[k] = all[k];
  res.json(out);
});

// ---------- Pages projets (rendu serveur, bon pour le SEO) ----------
router.get('/projets/:cat', (req, res, next) => {
  const cat = CATS[(req.params.cat || '').toLowerCase()];
  if (!cat) return next();
  const content = store.getContent();
  res.render('public/projet', {
    cat, catLabel: CAT_LABEL[cat],
    biens: store.activeBiensByCat(cat),
    content,
    base: baseUrl(req), canonical: baseUrl(req) + '/projets/' + (cat === 'villa' ? 'villas' : 'residences')
  });
});

router.get('/bien/:slug', (req, res, next) => {
  const bien = store.getBien(req.params.slug);
  if (!bien || !bien.actif) return next();
  res.render('public/bien', {
    bien,
    content: store.getContent(),
    autres: store.activeBiensByCat(bien.categorie).filter(b => b.id !== bien.id).slice(0, 3),
    base: baseUrl(req), canonical: baseUrl(req) + '/bien/' + bien.slug,
    typoSlug: typoSlug
  });
});

function typoSlug(nom) {
  return String(nom || '').toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g, '')
    .replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '') || 'type';
}

router.get('/bien/:slug/:typo', (req, res, next) => {
  const bien = store.getBien(req.params.slug);
  if (!bien || !bien.actif) return next();
  const typos = bien.typologies || [];
  const idx = typos.findIndex(t => typoSlug(t.nom) === req.params.typo);
  if (idx === -1) return next();
  res.render('public/typologie', {
    bien, typo: typos[idx], typoSlug: typoSlug,
    content: store.getContent(),
    base: baseUrl(req), canonical: baseUrl(req) + '/bien/' + bien.slug + '/' + req.params.typo
  });
});

// ---------- SEO : plan du site + robots ----------
router.get('/sitemap.xml', (req, res) => {
  const base = baseUrl(req);
  const urls = [
    { loc: base + '/', priority: '1.0' },
    { loc: base + '/projets/residences', priority: '0.8' },
    { loc: base + '/projets/villas', priority: '0.8' }
  ];
  store.activeBiens().forEach(b => urls.push({ loc: base + '/bien/' + b.slug, priority: '0.7' }));
  const today = new Date().toISOString().slice(0, 10);
  const xml = '<?xml version="1.0" encoding="UTF-8"?>\n' +
    '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n' +
    urls.map(u => `  <url><loc>${u.loc}</loc><lastmod>${today}</lastmod><priority>${u.priority}</priority></url>`).join('\n') +
    '\n</urlset>\n';
  res.type('application/xml').send(xml);
});

router.get('/robots.txt', (req, res) => {
  const base = baseUrl(req);
  res.type('text/plain').send(`User-agent: *\nAllow: /\n\nSitemap: ${base}/sitemap.xml\n`);
});

// ---------- Réception du formulaire de contact ----------
router.post('/api/contact', async (req, res) => {
  const { nom, email, telephone, message, type_bien, sujet, creneau } = req.body || {};
  if (!nom || (!email && !telephone)) {
    return res.status(400).json({ ok: false, error: 'Merci d\'indiquer au moins un nom et un moyen de contact.' });
  }

  store.addMessage({
    sujet: String(sujet || 'Contact').trim(),
    nom: String(nom).trim(),
    email: String(email || '').trim(),
    telephone: String(telephone || '').trim(),
    type_bien: String(type_bien || '').trim(),
    creneau: String(creneau || '').trim(),
    message: String(message || '').trim()
  });

  if (process.env.SMTP_HOST) {
    try {
      const transporter = nodemailer.createTransport({
        host: process.env.SMTP_HOST,
        port: Number(process.env.SMTP_PORT || 587),
        secure: Number(process.env.SMTP_PORT) === 465,
        auth: { user: process.env.SMTP_USER, pass: process.env.SMTP_PASS }
      });
      await transporter.sendMail({
        from: process.env.SMTP_USER,
        to: process.env.CONTACT_TO || process.env.SMTP_USER,
        replyTo: email || undefined,
        subject: `${sujet || 'Contact'} — ${nom}`,
        text: `Sujet : ${sujet || 'Contact'}\nNom : ${nom}\nEmail : ${email || '-'}\nTéléphone : ${telephone || '-'}\nType de bien : ${type_bien || '-'}\nCréneau souhaité : ${creneau || '-'}\n\n${message || '-'}`
      });
    } catch (e) {
      console.error('Email non envoyé :', e.message);
    }
  }

  res.json({ ok: true });
});

module.exports = router;
