/* global React */
/* ========================= WORK / REALISATIONS ========================= */
function Work() {
  const t = useI18n();
  const items = [
    { tag: 'E-commerce · Prestashop', title: 'Chaussons et petits pas', sz: 'sz-8', img: 'assets/img/project/work-1.jpg' },
    { tag: 'Vitrine · WordPress', title: 'Garage Peugeot Puyricard', sz: 'sz-4', img: 'assets/img/project/work-3.jpg' },
    { tag: 'Sur-mesure · PHP/JS', title: 'Jolicils — prise de RDV', sz: 'sz-4', img: 'assets/img/project/jolicils/thumb.jpg' },
    { tag: 'Vitrine responsive', title: 'Atelier des artisans', sz: 'sz-4', img: 'assets/img/project/dekhodesign/thumb.jpg' },
    { tag: 'Refonte · SEO', title: 'Cabinet dentaire Fuveau', sz: 'sz-4', img: 'assets/img/project/work-4.jpg' },
  ];
  return (
    <section className="work" id="work">
      <div className="container">
        <div className="services-header reveal">
          <div>
            <div className="section-label">{t('common.work.label', 'Réalisations')}</div>
            <h2 style={{ marginTop: 16 }}>{t('common.work.title', 'Quelques projets dont je suis')} <span style={{ fontFamily: 'Fraunces', fontStyle: 'italic', fontWeight: 400, color: 'var(--yo-orange)' }}>{t('common.work.title_accent', 'fier.')}</span></h2>
          </div>
          <a href="realisations.html" className="btn ghost">{t('common.work.cta', 'Voir toutes mes réalisations')}
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M5 12h14M13 6l6 6-6 6"/></svg>
          </a>
        </div>
        <div className="work-grid reveal">
          {items.map((w, i) => (
            <div key={i} className={"work-card " + w.sz}>
              <a href="#">
                <div className="ph"><img src={w.img} alt={w.title} style={{ width: '100%', height: '100%', objectFit: 'cover' }} /></div>
                <div className="overlay">
                  <div className="tag">{w.tag}</div>
                  <h3>{w.title}</h3>
                </div>
                <span className="go"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M5 12h14M13 6l6 6-6 6"/></svg></span>
              </a>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ========================= TESTIMONIALS ========================= */
function Testimonials() {
  const t = useI18n();
  const items = [
    { note: 5, text: "Yann est un webmaster talentueux, sérieux et efficace. Les délais d'exécution sont rapides. De plus, il assure un véritable suivi après réalisation et est toujours disponible. Une belle collaboration !", who: 'Juliette B.', role: 'Jolicils' },
    { note: 5, text: "Société sérieuse. Personne à l'écoute et très réactive. Je conseille vivement.", who: 'Anita Donsion', role: 'Chaussons et petits pas' },
    { note: 5, text: "Très compétent et très sérieux, je recommande vivement YouOnline pour tout projet web.", who: 'Hélène Loffredo', role: 'Garage Peugeot Puyricard' },
  ];
  return (
    <section className="testimonials" id="avis">
      <div className="container">
        <div className="testi-head reveal">
          <div>
            <div className="section-label">{t('common.testi.label', "Livre d'or")}</div>
            <h2 style={{ marginTop: 16 }}>{t('common.testi.title', "Ce qu'ils en disent.")}</h2>
          </div>
          <div className="rating-chip">
            <span className="stars">★★★★★</span>
            <div><strong>5/5</strong><br/><span>{t('common.testi.rating_count', 'sur 42 avis Google vérifiés')}</span></div>
          </div>
        </div>
        <div className="testi-grid reveal">
          {items.map((ti, i) => (
            <div key={i} className="testi-card">
              <div className="stars">{'★'.repeat(ti.note)}</div>
              <blockquote>« {ti.text} »</blockquote>
              <div className="who">
                <div className="av">{ti.who[0]}</div>
                <div><strong>{ti.who}</strong><em>{ti.role}</em></div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ========================= BLOG ========================= */
function Blog() {
  const t = useI18n();
  const { useState: useSB, useEffect: useEB } = React;
  const [posts, setPosts] = useSB([]);
  const [loaded, setLoaded] = useSB(false);

  useEB(() => {
    fetch('/blog-api.php?action=latest&limit=6')
      .then(r => r.json())
      .then(data => {
        if (data.success && data.articles) setPosts(data.articles);
        setLoaded(true);
      })
      .catch(() => setLoaded(true));
  }, []);

  const fmtDate = (iso) => {
    if (!iso) return '';
    const d = new Date(iso);
    const lang = (typeof _i18nLang !== 'undefined') ? _i18nLang : 'fr';
    return d.toLocaleDateString(lang === 'fr' ? 'fr-FR' : lang, { day: 'numeric', month: 'long', year: 'numeric' });
  };

  const fallbackPosts = [
    { categorie_nom: 'Conseils', date_publication: '2026-04-18', titre: 'Site vitrine ou e-commerce : lequel choisir en 2026 ?', chapeau: "Vendre, présenter, informer : on fait le point sur ce qui change votre choix de site web.", slug: 'site-vitrine-ou-ecommerce-lequel-choisir', categorie_couleur: '#407696', temps_lecture: 5 },
    { categorie_nom: 'Tech', date_publication: '2026-04-02', titre: 'WordPress en 2026 : encore la meilleure option ?', chapeau: "On fait le tri entre les nouvelles solutions no-code et le bon vieux CMS qui fait tourner 40% du web.", slug: 'wordpress-en-2026-encore-la-meilleure-option', categorie_couleur: '#6F42C1', temps_lecture: 6 },
    { categorie_nom: 'SEO', date_publication: '2026-03-21', titre: '5 erreurs SEO qui plombent votre site (et comment les corriger)', chapeau: "Les bases que je vois défaillantes sur 9 sites sur 10 en audit. Simples à corriger, gros impact.", slug: '5-erreurs-seo-qui-plombent-votre-site', categorie_couleur: '#EB9222', temps_lecture: 7 },
    { categorie_nom: 'Cybersécurité', date_publication: '2026-03-10', titre: 'Protéger votre nom de domaine : les menaces méconnues', chapeau: "Votre nom de domaine est votre identité numérique. Voici les risques que la plupart des entreprises ignorent.", slug: 'proteger-nom-de-domaine-menaces-meconnues', categorie_couleur: '#DC3545', temps_lecture: 6 },
    { categorie_nom: 'Intelligence Artificielle', date_publication: '2026-02-25', titre: "RAG et bases vectorielles : l'IA au service de vos données", chapeau: "Le RAG permet à l'IA d'accéder à vos données spécifiques. Découvrez cette technologie clé.", slug: 'rag-bases-vectorielles-ia-donnees', categorie_couleur: '#20C997', temps_lecture: 9 },
    { categorie_nom: 'Développement Web', date_publication: '2026-02-12', titre: 'Google SGE et l\'avenir du SEO en 2025', chapeau: "Google intègre l'IA dans ses résultats de recherche. Quel impact pour votre référencement ?", slug: 'google-sge-avenir-seo-2025', categorie_couleur: '#407696', temps_lecture: 7 },
  ];

  const articles = posts.length > 0 ? posts : (loaded ? fallbackPosts : []);

  return (
    <section className="blog" id="blog">
      <div className="container">
        <div className="services-header reveal">
          <div>
            <div className="section-label">{t('home.blog.label', 'Le blog')}</div>
            <h2 style={{ marginTop: 16 }}>{t('home.blog.title', 'Mes derniers articles.')}</h2>
          </div>
          <a href="blog.html" className="btn ghost">{t('home.blog.cta', 'Tout le blog')}
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M5 12h14M13 6l6 6-6 6"/></svg>
          </a>
        </div>
        <div className="blog-grid reveal">
          {articles.map((p, i) => (
            <article key={i} className="post">
              <a href={'article.html?slug=' + p.slug} style={{ textDecoration: 'none', color: 'inherit' }}>
                <div className="thumb" style={{ background: p.image_path ? undefined : 'linear-gradient(135deg, ' + (p.categorie_couleur || '#407696') + '22, ' + (p.categorie_couleur || '#407696') + '66)', display: 'flex', alignItems: 'center', justifyContent: 'center', minHeight: 220 }}>
                  {p.image_path ? <img src={p.image_path} alt={p.image_alt || p.titre} style={{ width: '100%', height: '100%', objectFit: 'cover' }} /> : <span style={{ fontSize: 40, opacity: 0.3 }}>✍</span>}
                </div>
                <div className="meta">
                  <span className="cat" style={{ color: p.categorie_couleur || 'var(--yo-orange)' }}>{p.categorie_nom}</span>
                  <span>·</span>
                  <span>{fmtDate(p.date_publication)}</span>
                  <span>·</span>
                  <span>{p.temps_lecture || 5} {t('home.blog.min_read', 'min de lecture')}</span>
                </div>
                <h3>{p.titre}</h3>
                <p>{p.chapeau}</p>
              </a>
            </article>
          ))}
          {!loaded && articles.length === 0 && (
            <div style={{ gridColumn: '1 / -1', textAlign: 'center', padding: '40px 0', color: 'var(--ink-3)' }}>...</div>
          )}
        </div>
      </div>
    </section>
  );
}

/* ========================= PARTNERS ========================= */
function Partners() {
  const t = useI18n();
  const techs = ['WordPress', 'Prestashop', 'PHP', 'MySQL', 'JavaScript', 'React', 'Docker', 'Stripe', 'Google Workspace', 'SSL · Let\'s Encrypt'];
  return (
    <section className="partners">
      <div className="container">
        <div className="label section-label" style={{ justifyContent: 'center', display: 'flex' }}>{t('common.partners.label', "Les outils que j'utilise au quotidien")}</div>
        <div className="marquee">
          <div className="marquee-track">
            {techs.map((te, i) => <div key={i} className="partner-item"><span className="dot"></span>{te}</div>)}
          </div>
          <div className="marquee-track" aria-hidden="true">
            {techs.map((te, i) => <div key={i+100} className="partner-item"><span className="dot"></span>{te}</div>)}
          </div>
        </div>
      </div>
    </section>
  );
}

/* ========================= CTA ========================= */
function CTA() {
  const t = useI18n();
  return (
    <section className="cta" id="contact">
      <div className="cta-bg"></div>
      <div className="cta-circle"></div>
      <div className="cta-circle"></div>
      <div className="container" style={{ position: 'relative', zIndex: 2 }}>
        <div className="chip reveal" style={{ background: 'rgba(235,146,34,0.15)', borderColor: 'rgba(235,146,34,0.3)', color: 'var(--yo-orange-soft)' }}><span className="dot"></span>{t('common.cta.chip', 'Prêt à démarrer ?')}</div>
        <h2 className="reveal" style={{ marginTop: 24 }}>{t('common.cta.title', 'Parlons de votre projet')}<br/><span className="it">{t('common.cta.title_italic', "autour d'un café.")}</span></h2>
        <p className="reveal">{t('common.cta.body', "Devis gratuit sous 24h, engagement zéro. Par téléphone, email ou en personne à Fuveau — à vous de choisir.")}</p>
        <div className="reveal" style={{ display: 'flex', gap: 12, justifyContent: 'center', flexWrap: 'wrap' }}>
          <a href="contact.html" className="btn accent">{t('common.cta.btn_devis', 'Demander un devis')}
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M5 12h14M13 6l6 6-6 6"/></svg>
          </a>
          <a href="tel:+33624997171" className="btn" style={{ background: 'transparent', color: 'var(--bg)', border: '1px solid rgba(244,241,236,0.25)' }}>{t('common.cta.btn_phone', "Ou m'appeler directement")}</a>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { Work, Testimonials, Blog, Partners, CTA });
