function Clients({ accent }) {
  const clients = [
    { name: 'OPIIEC',      src: 'assets/clients/opiiec.png' },
    { name: 'OPCO Atlas',  src: 'assets/atlas-logo.png' },
    { name: 'MEDEF',       src: 'assets/clients/logo-medef.svg' },
    { name: 'Galiléo',     src: 'assets/clients/logo-galileo.svg' },
    { name: 'FNTP',        src: 'assets/clients/logo-fntp.png' },
    { name: 'AKTO',        src: 'assets/clients/akto.png' },
  ];

  return (
    <section id="clients" className="section clients-section">
      <div className="container">
        <div className="clients-kicker">Ils ont choisi Komète</div>
        <div className="clients-row">
          {clients.map((c) =>
            <div key={c.name} className="client-tile" aria-label={c.name}>
              <img src={c.src} alt={c.name} style={{ height: 56, objectFit: 'contain', maxWidth: '100%' }} />
            </div>
          )}
        </div>
        <div className="client-quote">
          <KometeStar size={26} color={accent.accent} />
          <blockquote>
            « Komète nous permet de partager, en temps quasi-réel, une lecture homogène
            des dynamiques emploi-formation avec l'ensemble de nos délégations régionales. »
            <cite>— Observatoire de branche</cite>
          </blockquote>
        </div>
      </div>
    </section>
  );
}

function Audiences({ accent }) {
  const items = [
    { t: 'OPCO & branches', d: 'Observatoires prospectifs, tableaux de bord partagés, panoramas territoriaux.' },
    { t: 'Observatoires métiers', d: 'Indicateurs paritaires, data-visualisation harmonisée, publications grand public.' },
    { t: 'Régions & acteurs publics', d: 'Panoramas territoriaux, pilotage des politiques emploi-formation.' },
    { t: 'Entreprises & fédérations', d: 'Benchmarks sectoriels, GPEC, tensions au recrutement, intelligence de marché.' },
    { t: 'Organismes de formation', d: "Connaissance de l'économie des territoires, calibrage de l'offre." },
    { t: 'Experts data', d: 'Data Explorer : générateur de graphiques ad hoc, filtres combinatoires sans limite.' },
  ];

  return (
    <section className="section audiences-section">
      <div className="container">
        <SectionHead
          kicker="Pour qui"
          title={<>Six profils, <em>une même plateforme</em> modulable.</>}
        />
        <div className="aud-grid">
          {items.map((it, i) =>
            <div key={i} className="aud-card">
              <div className="aud-n" style={{ color: accent.accent }}>0{i + 1}</div>
              <h4 className="aud-t">{it.t}</h4>
              <p className="aud-d">{it.d}</p>
            </div>
          )}
        </div>
      </div>
    </section>
  );
}

function Products({ accent }) {
  const prods = [
    { n: '01', t: 'Graphiques iFrame', d: 'Encapsuler des graphiques Komète dans votre site existant.', icon: 'iframe' },
    { n: '02', t: 'API de données', d: 'Pousser les données traitées vers votre plateforme tierce.', icon: 'api' },
    { n: '03', t: 'Dashboards préconfigurés', d: "Tableaux de bord simples, autoportés, prêts à l'usage.", icon: 'dash' },
    { n: '04', t: 'Data Explorer', d: 'Générateur de graphiques ad hoc avec filtres combinatoires.', icon: 'explore' },
  ];

  return (
    <section id="products" className="section products-section">
      <div className="container">
        <SectionHead
          kicker="Quatre produits"
          title={<>De l'<em>encapsulé</em> au <em>sur-mesure</em>.</>}
          lede="Choisissez le niveau d'intégration qui correspond à votre contexte — ou combinez-les."
        />
        <div className="prod-grid">
          {prods.map((p) =>
            <div key={p.n} className="prod-card">
              <div className="prod-head">
                <span className="prod-n">{p.n}</span>
                <ProdIcon kind={p.icon} color={accent.accent} />
              </div>
              <h4 className="prod-t">{p.t}</h4>
              <p className="prod-d">{p.d}</p>
            </div>
          )}
        </div>
      </div>
    </section>
  );
}

function ProdIcon({ kind, color }) {
  const common = { width: 28, height: 28, fill: 'none', stroke: color, strokeWidth: 1.6 };
  if (kind === 'iframe') return <svg {...common}><rect x="4" y="6" width="20" height="16" rx="1" /><path d="M8 11l-2 3 2 3M20 11l2 3-2 3" /></svg>;
  if (kind === 'api') return <svg {...common}><circle cx="7" cy="14" r="2.5" /><circle cx="21" cy="14" r="2.5" /><path d="M9.5 14h9" /><path d="M14 7v3M14 18v3" /></svg>;
  if (kind === 'dash') return <svg {...common}><rect x="4" y="5" width="9" height="9" rx="1" /><rect x="15" y="5" width="9" height="6" rx="1" /><rect x="4" y="16" width="9" height="7" rx="1" /><rect x="15" y="13" width="9" height="10" rx="1" /></svg>;
  return <svg {...common}><circle cx="12" cy="12" r="6" /><path d="M17 17l5 5" /><path d="M12 9v6M9 12h6" /></svg>;
}

const CONTACT_FUNCTION_URL = 'https://europe-west1-komete-371419.cloudfunctions.net/contactForm';

function Contact({ accent }) {
  const formRef = React.useRef(null);
  const [modal, setModal] = React.useState(null);
  const [sending, setSending] = React.useState(false);
  const [error, setError] = React.useState(null);
  const [values, setValues] = React.useState({ org: '', prenom: '', nom: '', email: '', contexte: '' });

  function update(k, v) { setValues(s => ({ ...s, [k]: v })); }

  async function trySubmit(mode) {
    const form = formRef.current;
    if (!form) return;
    if (!form.checkValidity()) { form.reportValidity(); return; }
    setError(null);
    setSending(true);
    try {
      const res = await fetch(CONTACT_FUNCTION_URL, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ ...values, mode }),
      });
      if (!res.ok) throw new Error('server');
      setModal(mode);
    } catch (_) {
      setError('Une erreur est survenue. Veuillez réessayer ou écrire à contact-it@kyu.fr.');
    } finally {
      setSending(false);
    }
  }

  return (
    <section id="contact" className="section contact-section">
      <div className="container contact-inner">
        <div className="contact-copy">
          <div className="kicker"><span className="kdot" />Discuter de votre projet</div>
          <h2 className="sec-title">Parlons de vos données, <em>de vos enjeux.</em></h2>
          <p className="sec-lede">
            Un expert KYU vous rappelle sous 48h pour cadrer votre besoin et, si vous le souhaitez,
            vous ouvrir un accès Freemium à une version bridée de Komète.
          </p>
          <div className="contact-bullets">
            <div><Check color={accent.accent} /> Cadrage gratuit du besoin</div>
            <div><Check color={accent.accent} /> Démo personnalisée</div>
            <div><Check color={accent.accent} /> Accès Freemium sans engagement</div>
          </div>
        </div>
        <form ref={formRef} className="contact-form" onSubmit={(e) => { e.preventDefault(); trySubmit('expert'); }}>
          <div className="field">
            <label>Organisation</label>
            <input required placeholder="Nom de votre structure" value={values.org} onChange={e => update('org', e.target.value)} />
          </div>
          <div className="row-2">
            <div className="field"><label>Prénom</label><input required value={values.prenom} onChange={e => update('prenom', e.target.value)} /></div>
            <div className="field"><label>Nom</label><input required value={values.nom} onChange={e => update('nom', e.target.value)} /></div>
          </div>
          <div className="field">
            <label>Email professionnel</label>
            <input type="email" required placeholder="vous@organisation.fr" value={values.email} onChange={e => update('email', e.target.value)} />
          </div>
          <div className="field">
            <label>Votre contexte</label>
            <textarea rows={3} placeholder="Observatoire, branche, besoins, volumétrie…" value={values.contexte} onChange={e => update('contexte', e.target.value)} />
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginTop: 8 }}>
            <button type="submit" className="btn btn-primary" disabled={sending}
              style={{ background: accent.accent, borderColor: accent.accent, opacity: sending ? 0.7 : 1 }}>
              {sending ? 'Envoi en cours…' : 'Être contacté par un expert →'}
            </button>
            <button type="button" className="btn btn-ghost" disabled={sending}
              style={{ opacity: sending ? 0.7 : 1 }}
              onClick={() => trySubmit('freemium')}>
              Accéder à une version gratuite
            </button>
          </div>
          {error && <p style={{ color: '#c0392b', marginTop: 8, fontSize: 14 }}>{error}</p>}
        </form>
      </div>
      {modal && <ContactModal mode={modal} accent={accent} values={values} onClose={() => setModal(null)} />}
    </section>
  );
}

function ContactModal({ mode, accent, values, onClose }) {
  React.useEffect(() => {
    function onKey(e) { if (e.key === 'Escape') onClose(); }
    document.addEventListener('keydown', onKey);
    document.body.style.overflow = 'hidden';
    return () => {
      document.removeEventListener('keydown', onKey);
      document.body.style.overflow = '';
    };
  }, [onClose]);

  const isExpert = mode === 'expert';
  const firstName = values.prenom || '';

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal-card" onClick={e => e.stopPropagation()} role="dialog" aria-modal="true">
        <button className="modal-close" onClick={onClose} aria-label="Fermer">×</button>

        <div className="modal-icon-wrap" style={{ background: accent.accentSoft }}>
          {isExpert
            ? <svg width="32" height="32" viewBox="0 0 32 32" fill="none">
                <rect x="4" y="7" width="24" height="20" rx="2" stroke={accent.accent} strokeWidth="1.8" />
                <path d="M4 13h24" stroke={accent.accent} strokeWidth="1.8" />
                <path d="M10 4v5M22 4v5" stroke={accent.accent} strokeWidth="1.8" strokeLinecap="round" />
                <path d="M11 19l3 3 6-7" stroke={accent.accent} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
              </svg>
            : <svg width="32" height="32" viewBox="0 0 32 32" fill="none">
                <path d="M20 4l8 8-14 14H6v-8L20 4z" stroke={accent.accent} strokeWidth="1.8" strokeLinejoin="round" />
                <path d="M16 8l8 8" stroke={accent.accent} strokeWidth="1.8" />
                <circle cx="22" cy="10" r="1.5" fill={accent.accent} />
              </svg>
          }
        </div>

        <div className="modal-kicker" style={{ color: accent.accent }}>
          {isExpert ? '✓ Demande enregistrée' : '✓ Accès en préparation'}
        </div>
        <h3 className="modal-title">
          {isExpert
            ? <>Merci{firstName ? `, ${firstName}` : ''}.<br />Un expert KYU vous rappelle.</>
            : <>Bienvenue{firstName ? `, ${firstName}` : ''} dans Komète.</>}
        </h3>
        <p className="modal-lede">
          {isExpert
            ? <>Nous avons bien reçu votre demande. Un expert KYU vous recontactera
                <strong> dans les plus brefs délais</strong> — sous 48 h ouvrées —
                à l'adresse <strong>{values.email || 'votre email professionnel'}</strong> pour cadrer vos besoins
                et organiser une démonstration personnalisée.</>
            : <>Un <strong>lien d'accès personnalisé</strong> à la version Freemium de Komète vient de
                vous être envoyé à <strong>{values.email || 'votre email professionnel'}</strong>.
                Vous pourrez explorer la plateforme sans engagement et basculer en version
                complète quand vous le souhaitez.</>
          }
        </p>

        <div className="modal-meta">
          <div className="modal-meta-row">
            <span className="modal-meta-l">Organisation</span>
            <span className="modal-meta-v">{values.org || '—'}</span>
          </div>
          <div className="modal-meta-row">
            <span className="modal-meta-l">Contact</span>
            <span className="modal-meta-v">{[values.prenom, values.nom].filter(Boolean).join(' ') || '—'}</span>
          </div>
          <div className="modal-meta-row">
            <span className="modal-meta-l">Prochaine étape</span>
            <span className="modal-meta-v">
              {isExpert ? 'Email + appel sous 48h ouvrées' : "Email avec lien d'accès (immédiat)"}
            </span>
          </div>
        </div>

        <div className="modal-actions">
          <button className="btn btn-primary"
            style={{ background: accent.accent, borderColor: accent.accent }}
            onClick={onClose}>
            Parfait, merci
          </button>
          {isExpert
            ? <a className="btn btn-ghost" href="#komete-ai" onClick={onClose}>
                En attendant, découvrir KoMètA
              </a>
            : <a className="btn btn-ghost" href="mailto:contact@kyu.fr" onClick={onClose}>
                Une question ? contact@kyu.fr
              </a>
          }
        </div>

        <div className="modal-foot">
          <KometeStar size={14} color={accent.accent} />
          <span>Komète by KYU Lab · Vos données ne sont jamais partagées.</span>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Clients, Audiences, Products, Contact, ContactModal });
