/* global React */
const { useEffect: useEffectSc } = React;

/* ========================= SERVICES ========================= */
function Services() {
  const t = useI18n();
  const items = [
    { icon: 'code', title: t('home.services.creation_title', 'Création de sites'), text: t('home.services.creation_text', 'Sites vitrine, e-commerce, blogs et applications sur mesure. WordPress, Prestashop ou code custom.'), cta: t('home.services.creation_cta', 'Voir les tarifs') },
    { icon: 'server', title: t('home.services.hebergement_title', 'Hébergement web'), text: t('home.services.hebergement_text', 'Serveurs rapides et sécurisés. Mutualisé, VPS ou dédié, selon vos besoins et votre trafic.'), cta: t('home.services.hebergement_cta', 'Découvrir') },
    { icon: 'tools', title: t('home.services.maintenance_title', 'Maintenance'), text: t('home.services.maintenance_text', 'Mises à jour, corrections, améliorations. Votre site reste performant et sécurisé.'), cta: t('home.services.maintenance_cta', 'Nos formules') },
    { icon: 'globe', title: t('home.services.domaines_title', 'Noms de domaine'), text: t('home.services.domaines_text', 'Enregistrement et gestion de vos .fr, .com, .eu et autres. Disponibilité en temps réel.'), cta: t('home.services.domaines_cta', 'Vérifier') },
    { icon: 'search', title: t('home.services.seo_title', 'Référencement SEO'), text: t('home.services.seo_text', 'Audit, optimisation technique et contenu. On fait remonter votre site dans Google.'), cta: t('home.services.seo_cta', 'En savoir plus') },
    { icon: 'shield', title: t('home.services.ssl_title', 'Sécurité & SSL'), text: t('home.services.ssl_text', 'Certificats SSL, sauvegardes automatiques, monitoring 24/7 et protection WAF.'), cta: t('home.services.ssl_cta', 'Protéger mon site') },
    { icon: 'spark', title: t('home.services.surmesure_title', 'Sur-mesure & IA'), text: t('home.services.surmesure_text', 'Applications métier, outils de gestion, chatbots IA et automatisations. Du 100% adapté à votre activité.'), cta: t('home.services.surmesure_cta', 'Découvrir'), href: 'surmesure.html', featured: true },
    { icon: 'mail', title: t('home.services.emailing_title', 'Emailing & Newsletter'), text: t('home.services.emailing_text', 'Campagnes email, newsletters automatisées et templates sur-mesure. Fidélisez vos clients avec le bon message, au bon moment.'), cta: t('home.services.emailing_cta', 'En savoir plus') },
    { icon: 'graduation', title: t('home.services.formation_title', 'Formation & Conseil'), text: t('home.services.formation_text', 'Formations WordPress, SEO et prise en main de vos outils. Je vous rends autonome sur votre site, à votre rythme.'), cta: t('home.services.formation_cta', 'Me former') },
  ];
  const svg = {
    code: <path d="M8 6l-6 6 6 6M16 6l6 6-6 6M14 4l-4 16"/>,
    server: <><rect x="3" y="4" width="18" height="7" rx="1.5"/><rect x="3" y="13" width="18" height="7" rx="1.5"/><path d="M7 8h.01M7 17h.01"/></>,
    tools: <><path d="M14 7l6 6M3 21l8-8M14 7a4 4 0 1 0-4-4l3 3-2 2 3 3 2-2 3 3a4 4 0 0 0 1-3 4 4 0 0 0-3-3"/></>,
    globe: <><circle cx="12" cy="12" r="9"/><path d="M3 12h18M12 3c3 3 3 15 0 18M12 3c-3 3-3 15 0 18"/></>,
    search: <><circle cx="11" cy="11" r="7"/><path d="M21 21l-5-5"/></>,
    shield: <path d="M12 2l8 3v7c0 5-3.5 8.5-8 10-4.5-1.5-8-5-8-10V5l8-3z"/>,
    spark: <><path d="M12 2v4M12 18v4M4.93 4.93l2.83 2.83M16.24 16.24l2.83 2.83M2 12h4M18 12h4M4.93 19.07l2.83-2.83M16.24 7.76l2.83-2.83"/></>,
    mail: <><rect x="2" y="4" width="20" height="16" rx="2"/><path d="M22 4l-10 8L2 4"/></>,
    graduation: <><path d="M22 10v6M2 10l10 5 10-5-10-5-10 5z"/><path d="M6 12v5c0 2 3 3 6 3s6-1 6-3v-5"/></>,
  };
  return (
    <section className="services" id="services">
      <div className="container">
        <div className="services-header reveal">
          <div>
            <div className="section-label">{t('home.services.label', 'Mes services')}</div>
            <h2 style={{ marginTop: 16 }}>{t('home.services.title_line1', "Tout ce qu'il faut")}<br/>{t('home.services.title_line2', 'pour que votre site')} <span style={{ fontFamily: 'Fraunces', fontStyle: 'italic', fontWeight: 400, color: 'var(--yo-orange)' }}>{t('home.services.title_line2_accent', 'vive bien.')}</span></h2>
          </div>
          <p className="lead">{t('home.services.lead', "De la première idée à la mise en ligne, puis de la mise à jour quotidienne au support : je m'occupe de tout, avec un interlocuteur unique — moi.")}</p>
        </div>
        <div className="services-grid reveal">
          {items.map((it, i) => (
            <a key={i} href={it.href || '#'} className={"service-card" + (it.featured ? ' featured' : '')}>
              <div className="icon-wrap">
                <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">{svg[it.icon]}</svg>
              </div>
              <h3>{it.title}{it.featured && <span style={{ display: 'inline-block', marginLeft: 8, padding: '2px 8px', background: 'var(--yo-orange)', color: '#fff', fontSize: 10, fontWeight: 600, borderRadius: 99, verticalAlign: 'middle', letterSpacing: '0.06em', textTransform: 'uppercase' }}>{t('home.services.surmesure_badge', 'Nouveau')}</span>}</h3>
              <p>{it.text}</p>
              <span className="arrow">{it.cta}
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M5 12h14M13 6l6 6-6 6"/></svg>
              </span>
            </a>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ========================= ABOUT ========================= */
function About() {
  const t = useI18n();
  return (
    <section className="about" id="about">
      <div className="container">
        <div className="about-grid">
          <div className="about-images reveal">
            <div className="ph ph1"><img src="assets/img/about-1.jpg" alt="Création de sites web responsive" style={{ width: '100%', height: '100%', objectFit: 'cover' }} /></div>
            <div className="ph ph2"><img src="assets/img/about-2.jpg" alt="Designer web au travail" style={{ width: '100%', height: '100%', objectFit: 'cover' }} /></div>
            <div className="ph ph3"><span>{t('common.about.years_num', '14 ans')}<br/>{t('common.about.years_label', 'à vos côtés')}</span></div>
          </div>
          <div className="about-content reveal">
            <div className="section-label">{t('common.about.label', 'À propos')}</div>
            <h2 style={{ marginTop: 16 }}>{t('common.about.title', 'Une agence')} <span className="it">{t('common.about.title_accent', 'à taille humaine,')}</span> <span style={{ color: 'var(--yo-blue)' }}>{t('common.about.title_end', 'juste à côté de chez vous.')}</span></h2>
            <p>{t('common.about.p1', "Installé à Fuveau, à 15 minutes d'Aix-en-Provence, j'accompagne depuis 2012 les entrepreneurs, artisans et TPE qui veulent une présence web sérieuse sans passer par une grosse agence.")}</p>
            <p>{t('common.about.p2', "Chez nous, pas d'intermédiaires, pas de commerciaux. Vous nous appelez, on discute, on chiffre, on réalise. C'est aussi simple que ça — et c'est ce qui fait que nos clients restent depuis parfois plus de 14 ans.")}</p>
            <p>{t('common.about.p3', "Nous travaillons avec les mêmes outils que les grosses agences (WordPress, Prestashop, PHP, JS, SEO) mais avec la réactivité et la clarté d'un artisan.")}</p>
            <div className="about-sig">
              <div className="avatar">Y</div>
              <div className="text"><strong>{t('common.about.sig_name', 'Yann · Fondateur')}</strong>{t('common.about.sig_role', 'Artisan du web depuis 2012')}</div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ========================= STATS ========================= */
function StatNum({ target, suffix = '+' }) {
  const [v, setV] = React.useState(0);
  const ref = React.useRef(null);
  useEffectSc(() => {
    const io = new IntersectionObserver(entries => {
      entries.forEach(e => {
        if (e.isIntersecting) {
          let start = null;
          const dur = 1800;
          const step = (t) => {
            if (!start) start = t;
            const p = Math.min(1, (t - start) / dur);
            const eased = 1 - Math.pow(1-p, 3);
            setV(Math.floor(target * eased));
            if (p < 1) requestAnimationFrame(step);
          };
          requestAnimationFrame(step);
          io.disconnect();
        }
      });
    }, { threshold: 0.3 });
    if (ref.current) io.observe(ref.current);
    return () => io.disconnect();
  }, []);
  return <span ref={ref}>{v.toLocaleString('fr-FR')}<em>{suffix}</em></span>;
}

function Stats() {
  const t = useI18n();
  return (
    <section className="stats" id="stats">
      <div className="container">
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', flexWrap: 'wrap', gap: 24, marginBottom: 60 }}>
          <div>
            <div className="section-label" style={{ color: 'var(--yo-orange-soft)' }}>{t('common.stats.label', 'En chiffres')}</div>
            <h2 style={{ color: 'var(--bg)', marginTop: 16, maxWidth: '20ch' }}>{t('common.stats.title', 'Quatorze ans, et toujours cette même énergie.')}</h2>
          </div>
          <p style={{ color: 'rgba(244,241,236,0.7)', maxWidth: '36ch' }}>{t('common.stats.body', 'Derrière chaque site, il y a une histoire et beaucoup de cafés. Voici les chiffres.')}</p>
        </div>
        <div className="stats-grid reveal">
          <div className="stat"><div className="num"><StatNum target={250}/></div><div className="label">{t('common.stats.clients_label', 'Clients accompagnés')}</div></div>
          <div className="stat"><div className="num"><StatNum target={200}/></div><div className="label">{t('common.stats.sites_label', 'Sites créés depuis 2012')}</div></div>
          <div className="stat"><div className="num"><StatNum target={5000}/></div><div className="label">{t('common.stats.coffees_label', 'Cafés avalés')}</div></div>
          <div className="stat"><div className="num"><StatNum target={35000}/></div><div className="label">{t('common.stats.hours_label', 'Heures à vos côtés')}</div></div>
        </div>
      </div>
    </section>
  );
}

/* ========================= WHY ========================= */
function Why() {
  const t = useI18n();
  const items = [
    t('home.why.item1', 'Un interlocuteur unique, disponible et réactif'),
    t('home.why.item2', 'Communication rapide, claire et transparente'),
    t('home.why.item3', 'Aide à la prise en main de votre site'),
    t('home.why.item4', 'Prix attractifs, sans surprise ni frais cachés'),
    t('home.why.item5', 'Solutions adaptées à votre budget réel'),
    t('home.why.item6', 'Devis gratuit sous 24h, engagement zéro'),
  ];
  return (
    <section className="why">
      <div className="container">
        <div className="why-inner">
          <div className="reveal">
            <div className="section-label">{t('home.why.label', 'Pourquoi moi ?')}</div>
            <h2 style={{ marginTop: 16 }}>{t('home.why.title', 'Six bonnes raisons')} <span style={{ fontFamily: 'Fraunces', fontStyle: 'italic', fontWeight: 400, color: 'var(--yo-orange)' }}>{t('home.why.title_accent', 'de choisir')}</span> <span style={{ color: 'var(--yo-blue)' }}>{t('home.why.title_end', 'un artisan du web.')}</span></h2>
            <p style={{ marginTop: 20, color: 'var(--ink-2)', maxWidth: '36ch' }}>{t('home.why.body', "Parce qu'on n'a pas envie de parler à un commercial, et encore moins d'attendre trois semaines qu'on réponde à son email.")}</p>
          </div>
          <div className="why-list reveal">
            {items.map((txt, i) => (
              <div key={i} className="why-item">
                <span className="idx">{String(i+1).padStart(2,'0')}</span>
                <h3>{txt}</h3>
                <span className="plus"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M12 5v14M5 12h14"/></svg></span>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

/* ========================= PRICING ========================= */
function Pricing() {
  const t = useI18n();
  const [plans, setPlans] = React.useState(null);

  // Fallback hardcodes (utilises uniquement si l'API ne repond pas)
  const fallbackPlans = [
    { name: 'Starter', price: '35€', unit: 'HT / mois', feat: ["1h d'intervention/mois", 'Corrections de bugs', 'Mises à jour mineures', 'Support par email'], featured: false, cta: 'Choisir Starter' },
    { name: 'Professionnel', price: '90€', unit: 'HT / mois', feat: ["3h d'intervention/mois", 'Corrections et évolutions', 'Optimisation SEO', 'Support prioritaire'], featured: true, cta: 'Choisir Professionnel' },
    { name: 'Business', price: '200€', unit: 'HT / mois', feat: ['1 journée/mois', 'Développement sur mesure', 'Rapports mensuels', 'Support dédié'], featured: false, cta: 'Choisir Business' },
    { name: 'Ponctuel', price: '50€', unit: 'HT / heure', feat: ['Sans engagement', 'À la demande', 'Devis en 24h', 'Intervention en 48h'], featured: false, cta: 'Choisir Ponctuel' },
  ];

  React.useEffect(() => {
    fetch('/api-tarifs.php?cat=maintenance')
      .then(r => r.json())
      .then(data => {
        if (data.success && data.tarifs && data.tarifs.length > 0) {
          const mapped = data.tarifs.map(tarif => {
            const isPonctuel = tarif.cle === 'maintenance_ponctuel';
            const prix = tarif.prix_ht !== null ? tarif.prix_ht + '€' : t('home.pricing.devis', 'Sur devis');
            const unit = tarif.prix_ht !== null
              ? (isPonctuel ? t('home.pricing.unit_hourly', 'HT / heure') : t('home.pricing.unit_monthly', 'HT / mois'))
              : '';
            return {
              name: tarif.nom,
              price: prix,
              unit: unit,
              feat: tarif.features && tarif.features.length > 0 ? tarif.features : [tarif.description],
              featured: tarif.populaire || false,
              cta: t('home.pricing.cta_prefix', 'Choisir') + ' ' + tarif.nom,
            };
          });
          setPlans(mapped);
        } else {
          setPlans(fallbackPlans);
        }
      })
      .catch(() => setPlans(fallbackPlans));
  }, []);

  const displayPlans = plans || fallbackPlans;

  return (
    <section className="pricing" id="pricing">
      <div className="container">
        <div className="reveal" style={{ textAlign: 'center', maxWidth: 720, margin: '0 auto' }}>
          <div className="section-label" style={{ justifyContent: 'center', display: 'inline-flex' }}>{t('home.pricing.label', 'Maintenance')}</div>
          <h2 style={{ marginTop: 16 }}>{t('home.pricing.title', 'Gardez votre site')}<br/><span style={{ fontFamily: 'Fraunces', fontStyle: 'italic', fontWeight: 400, color: 'var(--yo-orange)' }}>{t('home.pricing.title_accent', 'en pleine forme.')}</span></h2>
          <p style={{ marginTop: 20, color: 'var(--ink-2)' }}>{t('home.pricing.body', 'Un site, ça se bichonne. Choisissez la formule adaptée à votre rythme, changez quand vous voulez.')}</p>
        </div>
        <div className="pricing-grid reveal">
          {displayPlans.map((p, i) => (
            <div key={i} className={"plan" + (p.featured ? ' featured' : '')}>
              <div className="name">{p.name}</div>
              <div className="price">{p.price}<span className="unit">{p.unit}</span></div>
              <ul>{p.feat.map((f, j) => <li key={j}>{f}</li>)}</ul>
              <a href="contact.html" className={"btn " + (p.featured ? 'accent' : 'ghost')}>{p.cta}</a>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { Services, About, Stats, Why, Pricing });
