/* Registration Form — Visiteurs uniquement · Supabase · Badge */

function FormField({ label, children, error }) {
  return (
    <div className={`form-field ${error ? 'has-error' : ''}`}>
      <label className="form-label">{label}</label>
      {children}
      {error && <span className="form-error">{error}</span>}
    </div>
  );
}

/* ── Badge Visiteur — Format A6 (105×148mm), style vintage premium ── */
function BadgeVisiteur({ prenom, nom, badgeNum }) {
  /* Palette vintage — valeurs hex brutes (pas de var() pour compatibilité impression) */
  const cream   = '#fbf9f6';
  const brown   = '#5c4033';
  const darkRed = '#7a1a1a';
  const gold    = '#b5891e';
  const dark    = '#2c1a0e';
  const muted   = '#8c7060';
  /* Polices explicites (pas de var() en inline style) */
  const serif   = "'Cormorant Garamond', Georgia, serif";
  const sans    = "'Plus Jakarta Sans', system-ui, sans-serif";

  return (
    <div id="badge-print-area" style={{ display: 'flex', justifyContent: 'center', margin: '32px 0' }}>

      {/* ── RECTO A6 ── */}
      <div id="badge-recto" style={{
        width: '105mm',
        height: '148mm',
        background: cream,
        border: `3px solid ${brown}`,
        borderRadius: 12,
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        overflow: 'hidden',
        boxSizing: 'border-box',
        boxShadow: '0 16px 56px rgba(92,64,51,0.3), 0 6px 20px rgba(0,0,0,0.18)',
        fontFamily: sans,
        position: 'relative',
      }}>

        {/* Bordure intérieure ornementale */}
        <div style={{
          position: 'absolute', inset: 6,
          border: `1px solid ${gold}`,
          borderRadius: 8,
          opacity: 0.45,
          pointerEvents: 'none',
          zIndex: 0,
        }} />

        {/* ── EN-TÊTE ── */}
        <div style={{
          width: '100%', padding: '22px 24px 18px',
          display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 10,
          borderBottom: `2px solid ${brown}`,
          background: `linear-gradient(180deg, #f3e8d8 0%, ${cream} 100%)`,
          position: 'relative', zIndex: 1,
        }}>
          <img src="/uploads/logo.png" alt="" style={{
            width: 100, height: 100, borderRadius: '50%', objectFit: 'cover',
            border: `3px solid ${brown}`,
            boxShadow: `0 0 0 2px ${gold}, 0 4px 16px rgba(92,64,51,0.25)`,
          }} />
          <div style={{ textAlign: 'center' }}>
            <p style={{
              fontFamily: serif, fontSize: 22, fontWeight: 700,
              color: brown, letterSpacing: 2, textTransform: 'uppercase',
              margin: 0, lineHeight: 1.2,
            }}>
              Fête de la Fraise
            </p>
            <p style={{
              fontSize: 11, letterSpacing: 3, textTransform: 'uppercase',
              color: muted, margin: '5px 0 0', fontWeight: 500,
            }}>
              Ville de Skikda · Édition 2026
            </p>
          </div>
        </div>

        {/* ── BANDEAU BADGE VISITEUR ── */}
        <div style={{
          width: '100%', padding: '14px 0',
          background: darkRed,
          display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 3,
          position: 'relative', zIndex: 1,
        }}>
          <p style={{
            fontSize: 10, letterSpacing: 5, textTransform: 'uppercase',
            color: 'rgba(245,239,227,0.65)', margin: 0, fontWeight: 500,
          }}>
            ❦ accès festival ❦
          </p>
          <p style={{
            fontFamily: serif, fontSize: 32, fontWeight: 700,
            color: '#f5efe3', letterSpacing: 5, textTransform: 'uppercase',
            margin: 0, lineHeight: 1.1,
          }}>
            BADGE VISITEUR
          </p>
        </div>

        {/* ── NOM / PRÉNOM ── */}
        <div style={{
          width: '100%', flex: 1,
          padding: '20px 28px',
          display: 'flex', flexDirection: 'column', justifyContent: 'center', gap: 18,
          borderBottom: `1px solid rgba(92,64,51,0.2)`,
          position: 'relative', zIndex: 1,
        }}>
          {[
            { libelle: 'Prénom', valeur: prenom },
            { libelle: 'Nom',    valeur: nom    },
          ].map(({ libelle, valeur }) => (
            <div key={libelle}>
              <p style={{
                fontSize: 10, letterSpacing: 2.5, textTransform: 'uppercase',
                color: muted, margin: '0 0 4px', fontWeight: 600,
              }}>
                {libelle}
              </p>
              <p style={{
                fontFamily: serif, fontSize: 28, fontWeight: 700,
                color: dark, margin: 0, lineHeight: 1.2,
              }}>
                {valeur}
              </p>
            </div>
          ))}
        </div>

        {/* ── NUMÉRO DE BILLET ── */}
        <div style={{
          width: '100%', padding: '16px 28px',
          background: `linear-gradient(90deg, rgba(181,137,30,0.07), rgba(181,137,30,0.14), rgba(181,137,30,0.07))`,
          borderTop: `1px solid rgba(181,137,30,0.4)`,
          display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 5,
          position: 'relative', zIndex: 1,
        }}>
          <p style={{
            fontSize: 9, letterSpacing: 3, textTransform: 'uppercase',
            color: gold, margin: 0, fontWeight: 700,
          }}>
            N° Billet
          </p>
          <p style={{
            fontFamily: serif, fontSize: 24, fontWeight: 700,
            color: brown, letterSpacing: 4, margin: 0,
          }}>
            {badgeNum}
          </p>
          <p style={{
            fontSize: 9, color: muted, margin: 0, letterSpacing: 1.5,
            textTransform: 'uppercase',
          }}>
            Billet personnel · non cessible
          </p>
        </div>

      </div>
    </div>
  );
}

/* ── Section principale ── */
function RegistrationSection() {
  const [ref, vis] = useReveal();
  const [form, setForm] = React.useState({ prenom: '', nom: '', email: '' });
  const [errors, setErrors] = React.useState({});
  const [submitting, setSubmitting] = React.useState(false);
  const [submitError, setSubmitError] = React.useState(null);
  const [badge, setBadge] = React.useState(null);

  const update = (key, val) => {
    setForm(prev => ({ ...prev, [key]: val }));
    if (errors[key]) setErrors(prev => ({ ...prev, [key]: null }));
    if (submitError) setSubmitError(null);
  };

  const validate = () => {
    const e = {};
    if (!form.prenom.trim()) e.prenom = 'Veuillez entrer votre prénom';
    if (!form.nom.trim())    e.nom    = 'Veuillez entrer votre nom';
    if (!form.email.trim())  e.email  = 'Veuillez entrer votre email';
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)) e.email = 'Email invalide';
    return e;
  };

  const generateBadgeNum = () => {
    const n = Math.floor(Math.random() * 100000);
    return `#FFS-${String(n).padStart(5, '0')}-26`;
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    const errs = validate();
    if (Object.keys(errs).length) { setErrors(errs); return; }

    setSubmitting(true);
    setSubmitError(null);

    const badgeNum = generateBadgeNum();

    try {
      const { error } = await window.supabaseClient
        .from('visiteurs')
        .insert([{
          prenom:       form.prenom.trim(),
          nom:          form.nom.trim(),
          email:        form.email.trim().toLowerCase(),
          numero_badge: badgeNum,
        }]);

      if (error) {
        if (error.code === '23505') {
          setSubmitError('Cet email est déjà inscrit. Utilisez un autre email.');
        } else {
          setSubmitError(`Erreur : ${error.message}`);
        }
        setSubmitting(false);
        return;
      }

      setBadge({
        prenom:   form.prenom.trim(),
        nom:      form.nom.trim(),
        email:    form.email.trim(),
        badgeNum,
      });
    } catch (err) {
      setSubmitError('Erreur réseau. Vérifiez votre connexion et réessayez.');
    }

    setSubmitting(false);
  };

  /* ── Vue succès / badge ── */
  if (badge) {
    return (
      <section id="inscription" className="section form-section" ref={ref}>
        <div className="section-inner">
          <div style={{ textAlign: 'center', marginBottom: 8 }}>
            <div className="success-icon" style={{ margin: '0 auto 16px' }}>✓</div>
            <h2 className="success-title">Inscription Confirmée !</h2>
            <p style={{ color: 'var(--text-secondary)', fontSize: 15, marginTop: 8, lineHeight: 1.6 }}>
              Bienvenue <strong style={{ color: 'var(--gold)' }}>{badge.prenom} {badge.nom}</strong> —
              voici votre badge visiteur.
            </p>
          </div>

          <BadgeVisiteur prenom={badge.prenom} nom={badge.nom} badgeNum={badge.badgeNum} />

          <div style={{ display: 'flex', gap: 16, justifyContent: 'center', flexWrap: 'wrap', marginTop: 16 }}>
            <button className="cta-btn" onClick={() => window.print()}>
              <span className="cta-label">Imprimer mon Badge</span>
              <span className="cta-shimmer" aria-hidden="true"></span>
            </button>
            <button
              className="cta-btn"
              style={{ borderColor: 'rgba(255,255,255,0.12)', color: 'var(--text-secondary)' }}
              onClick={() => { setBadge(null); setForm({ prenom: '', nom: '', email: '' }); }}
            >
              <span className="cta-label">Nouvelle inscription</span>
            </button>
          </div>
        </div>
      </section>
    );
  }

  /* ── Vue formulaire ── */
  return (
    <section id="inscription" className="section form-section" ref={ref}>
      <div className={`section-inner reveal ${vis ? 'visible' : ''}`}>
        <div className="section-header">
          <p className="section-overline">Rejoignez-nous</p>
          <h2 className="section-title">Inscription Visiteur</h2>
          <Divider />
        </div>

        <form className="glass-card form-card" onSubmit={handleSubmit} noValidate>
          <div className="form-grid">

            <FormField label="Prénom" error={errors.prenom}>
              <input
                type="text" className="form-input"
                placeholder="Votre prénom"
                value={form.prenom}
                onChange={e => update('prenom', e.target.value)}
              />
            </FormField>

            <FormField label="Nom" error={errors.nom}>
              <input
                type="text" className="form-input"
                placeholder="Votre nom de famille"
                value={form.nom}
                onChange={e => update('nom', e.target.value)}
              />
            </FormField>

            <FormField label="Adresse email" error={errors.email}>
              <input
                type="email" className="form-input"
                placeholder="votre@email.com"
                value={form.email}
                onChange={e => update('email', e.target.value)}
              />
            </FormField>

          </div>

          {submitError && (
            <p style={{
              color: 'var(--accent)', fontSize: 13, marginBottom: 20,
              padding: '10px 14px',
              background: 'rgba(230,57,70,0.06)',
              border: '1px solid rgba(230,57,70,0.2)',
              borderRadius: 8,
            }}>
              {submitError}
            </p>
          )}

          <button type="submit" className="cta-btn form-submit" disabled={submitting}>
            <span className="cta-label">
              {submitting ? 'Inscription en cours…' : 'Obtenir mon Badge Visiteur'}
            </span>
            <span className="cta-shimmer" aria-hidden="true"></span>
          </button>
        </form>
      </div>
    </section>
  );
}

Object.assign(window, { RegistrationSection, FormField });
