/**
 * Status.jsx — Progression du pipeline d'agents
 * Design: timeline verticale avec animations
 */

const { useState, useEffect, useRef } = React;

const PIPELINE_STEPS = [
  {
    key: 'paid',
    label: 'Paiement confirme',
    desc: 'Votre paiement a ete recu',
    icon: '\u2713',
    statuts: ['paid']
  },
  {
    key: 'analysing',
    label: 'Analyse des documents',
    desc: 'L\'IA examine chaque document en detail',
    icon: '1',
    statuts: ['analysing']
  },
  {
    key: 'reviewing',
    label: 'Verification juridique',
    desc: 'Croisement avec la jurisprudence et le Code des assurances',
    icon: '2',
    statuts: ['reviewing']
  },
  {
    key: 'challenging',
    label: 'Controle qualite',
    desc: 'Un second agent IA conteste et renforce les arguments',
    icon: '3',
    statuts: ['challenging']
  },
  {
    key: 'drafting',
    label: 'Redaction du rapport',
    desc: 'Generation du PDF avec courrier type',
    icon: '4',
    statuts: ['drafting']
  },
  {
    key: 'delivered',
    label: 'Rapport envoye',
    desc: 'Consultez votre boite mail',
    icon: '\u2713',
    statuts: ['delivered']
  }
];

function getActiveStepIndex(statut) {
  for (let i = 0; i < PIPELINE_STEPS.length; i++) {
    if (PIPELINE_STEPS[i].statuts.includes(statut)) return i;
  }
  return -1;
}

function Status({ dossierId }) {
  const [statut, setStatut] = useState('paid');
  const [email, setEmail] = useState('');
  const intervalRef = useRef(null);

  useEffect(() => {
    if (!dossierId) return;

    async function poll() {
      try {
        const res = await fetch(`/api/session/${dossierId}`);
        if (!res.ok) return;
        const data = await res.json();
        if (data.statut) setStatut(data.statut);
        if (data.email) setEmail(data.email);
        if (data.statut === 'delivered' || data.statut === 'error') {
          clearInterval(intervalRef.current);
        }
      } catch (err) { /* retry next tick */ }
    }

    poll();
    intervalRef.current = setInterval(poll, 10000);
    return () => clearInterval(intervalRef.current);
  }, [dossierId]);

  const activeIndex = getActiveStepIndex(statut);
  const isError = statut === 'error';
  const isDelivered = statut === 'delivered';

  function maskEmail(email) {
    if (!email) return '';
    const [local, domain] = email.split('@');
    if (!domain) return '***';
    return `${local.charAt(0)}***@${domain}`;
  }

  return (
    <div className="max-w-lg mx-auto px-6 py-16">
      {/* Header */}
      <div className="text-center mb-12 animate-fade-in">
        {!isDelivered && !isError && (
          <div className="w-16 h-16 rounded-2xl mx-auto mb-5 flex items-center justify-center animate-spin-slow" style={{ background: '#fef3c7' }}>
            <svg xmlns="http://www.w3.org/2000/svg" width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="#d97706" strokeWidth="2">
              <path d="m12 3-1.912 5.813a2 2 0 0 1-1.275 1.275L3 12l5.813 1.912a2 2 0 0 1 1.275 1.275L12 21l1.912-5.813a2 2 0 0 1 1.275-1.275L21 12l-5.813-1.912a2 2 0 0 1-1.275-1.275L12 3Z"/>
            </svg>
          </div>
        )}
        {isDelivered && (
          <div className="w-16 h-16 rounded-2xl mx-auto mb-5 flex items-center justify-center" style={{ background: '#ecfdf5' }}>
            <svg xmlns="http://www.w3.org/2000/svg" width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="#059669" strokeWidth="2.5">
              <path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><path d="m9 11 3 3L22 4"/>
            </svg>
          </div>
        )}
        <h2 className="font-display font-bold text-2xl mb-2" style={{ color: 'var(--text)' }}>
          {isDelivered ? 'Rapport livre' : isError ? 'Erreur de traitement' : 'Analyse en cours'}
        </h2>
        <p className="text-sm" style={{ color: 'var(--text-muted)' }}>
          Dossier {dossierId?.slice(0, 8).toUpperCase()}
        </p>
      </div>

      {/* Timeline */}
      <div className="relative">
        {PIPELINE_STEPS.map((step, index) => {
          const isDone = index < activeIndex || isDelivered;
          const isActive = index === activeIndex && !isDelivered && !isError;
          const isFuture = index > activeIndex && !isDelivered;

          return (
            <div key={step.key} className="flex gap-4 mb-0" style={{ opacity: isFuture ? 0.4 : 1, transition: 'opacity 0.5s' }}>
              {/* Timeline column */}
              <div className="flex flex-col items-center flex-shrink-0">
                {/* Circle */}
                <div
                  className={`w-9 h-9 rounded-full flex items-center justify-center text-sm font-bold border-2 transition-all duration-500 ${
                    isActive ? 'pulse-ring' : ''
                  }`}
                  style={{
                    background: isDone ? 'var(--accent-green)' : isActive ? 'var(--brand)' : 'var(--bg)',
                    borderColor: isDone ? 'var(--accent-green)' : isActive ? 'var(--brand)' : 'var(--border)',
                    color: isDone || isActive ? 'white' : 'var(--text-muted)'
                  }}
                >
                  {isDone ? '\u2713' : step.icon}
                </div>
                {/* Line */}
                {index < PIPELINE_STEPS.length - 1 && (
                  <div
                    className="w-0.5 transition-all duration-500"
                    style={{
                      height: '44px',
                      background: isDone ? 'var(--accent-green)' : 'var(--border)'
                    }}
                  />
                )}
              </div>

              {/* Content */}
              <div className="pt-1.5 pb-6">
                <p className="text-sm font-semibold" style={{ color: isDone ? 'var(--accent-green)' : isActive ? 'var(--brand)' : 'var(--text-muted)' }}>
                  {step.label}
                  {isActive && (
                    <span className="ml-2 text-xs font-normal" style={{ color: 'var(--brand)' }}>en cours...</span>
                  )}
                </p>
                <p className="text-xs mt-0.5" style={{ color: 'var(--text-muted)' }}>
                  {step.desc}
                </p>
              </div>
            </div>
          );
        })}
      </div>

      {/* Message final — Livre */}
      {isDelivered && (
        <div className="mt-8 p-6 rounded-2xl border-2 text-center animate-fade-in" style={{ borderColor: 'var(--accent-green)', background: '#ecfdf5' }}>
          <p className="font-semibold text-lg mb-1" style={{ color: '#065f46' }}>
            Votre rapport a ete envoye
          </p>
          <p className="text-sm" style={{ color: '#047857' }}>
            Consultez votre boite mail ({maskEmail(email)})
          </p>
          <p className="text-xs mt-4" style={{ color: '#6ee7b7' }}>
            Document produit par un assistant IA. Ne constitue pas un avis juridique.
          </p>
        </div>
      )}

      {/* Message erreur */}
      {isError && (
        <div className="mt-8 p-6 rounded-2xl border-2 text-center animate-fade-in" style={{ borderColor: 'var(--accent-red)', background: '#fef2f2' }}>
          <p className="font-semibold text-lg mb-1" style={{ color: '#991b1b' }}>
            Une erreur est survenue
          </p>
          <p className="text-sm" style={{ color: '#dc2626' }}>
            Notre equipe a ete alertee et vous contactera sous 24h a {maskEmail(email)}.
          </p>
        </div>
      )}

      {/* Footer info */}
      {!isDelivered && !isError && (
        <div className="mt-10 p-4 rounded-xl text-center" style={{ background: '#f5f5f4' }}>
          <p className="text-xs" style={{ color: 'var(--text-muted)' }}>
            Le traitement prend generalement entre 5 et 15 minutes.
            Vous pouvez fermer cette page — le rapport sera envoye par email.
          </p>
        </div>
      )}
    </div>
  );
}
