/**
 * Status.jsx — Progression du pipeline d'agents
 * Design V3: header card + timeline cards + progress bar
 */

const { useState, useEffect, useRef, useMemo } = React;

const PIPELINE_STEPS = [
  {
    key: 'paid',
    label: 'Paiement confirme',
    desc: 'Votre paiement a ete recu',
    agent: null,
    statuts: ['paid']
  },
  {
    key: 'analysing',
    label: 'Analyse documentaire',
    desc: "L'agent ANALYSTE examine chaque document en detail",
    agent: 'Analyste',
    statuts: ['analysing']
  },
  {
    key: 'building_expert',
    label: 'Expertise technique',
    desc: "L'agent EXPERT BATIMENT evalue les dommages et la conformite des travaux",
    agent: 'Expert',
    statuts: ['building_expert']
  },
  {
    key: 'costing',
    label: 'Chiffrage independant',
    desc: "L'agent EXPERT REGLEUR recalcule les montants avec les indices de reference",
    agent: 'Regleur',
    statuts: ['costing']
  },
  {
    key: 'reviewing',
    label: 'Verification juridique',
    desc: "L'agent JURISTE croise avec la jurisprudence et le Code des assurances",
    agent: 'Juriste',
    statuts: ['reviewing']
  },
  {
    key: 'challenging',
    label: 'Controle qualite',
    desc: "L'agent CHALLENGER conteste et renforce les arguments",
    agent: 'Challenger',
    statuts: ['challenging']
  },
  {
    key: 'drafting',
    label: 'Redaction du rapport',
    desc: 'Generation du PDF avec rapport complet et courrier de contestation',
    agent: 'Redacteur',
    statuts: ['drafting']
  },
  {
    key: 'delivered',
    label: 'Rapport envoye',
    desc: 'Votre rapport est disponible par email',
    agent: null,
    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 [typeSinistre, setTypeSinistre] = useState('');
  const [startTime] = useState(Date.now());
  const [elapsed, setElapsed] = useState(0);
  const intervalRef = useRef(null);
  const timerRef = useRef(null);

  // Poll for status updates
  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.type_sinistre) setTypeSinistre(data.type_sinistre);
        if (data.statut === 'delivered' || data.statut === 'error') {
          clearInterval(intervalRef.current);
          clearInterval(timerRef.current);
        }
      } catch (err) { /* retry next tick */ }
    }

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

  // Elapsed time counter
  useEffect(() => {
    timerRef.current = setInterval(() => {
      setElapsed(Math.floor((Date.now() - startTime) / 1000));
    }, 1000);
    return () => clearInterval(timerRef.current);
  }, [startTime]);

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

  const progressPercent = useMemo(() => {
    if (isDelivered) return 100;
    if (activeIndex < 0) return 0;
    return Math.round(((activeIndex + 0.5) / PIPELINE_STEPS.length) * 100);
  }, [activeIndex, isDelivered]);

  const estimatedRemaining = useMemo(() => {
    const totalEstimate = 15 * 60;
    const perStep = totalEstimate / PIPELINE_STEPS.length;
    const remaining = Math.max(0, (PIPELINE_STEPS.length - activeIndex - 1) * perStep);
    const mins = Math.ceil(remaining / 60);
    return mins > 0 ? `~${mins} min restantes` : 'Bientot termine';
  }, [activeIndex]);

  function formatElapsed(seconds) {
    const m = Math.floor(seconds / 60);
    const s = seconds % 60;
    return `${m}:${s.toString().padStart(2, '0')}`;
  }

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

  return (
    <div style={{ maxWidth: 540, margin: '0 auto', padding: '2rem 1.5rem' }}>

      {/* ── Header card ────────────────────────────────── */}
      <div className="anim-fade-up"
           style={{ background: '#fff', border: '1px solid #e7e5e4', borderRadius: 20, padding: '1.5rem', marginBottom: '2rem' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: '1rem' }}>
          <div style={{ fontSize: '.75rem', color: '#a8a29e', fontWeight: 500 }}>
            Dossier {dossierId?.slice(0, 8).toUpperCase()}
          </div>
          {!isDelivered && !isError && (
            <div style={{
              display: 'inline-flex', alignItems: 'center', gap: 6,
              fontSize: '.75rem', fontWeight: 600, color: '#f59e0b',
              background: 'rgba(245,158,11,.1)', padding: '4px 12px', borderRadius: 20
            }}>
              <span style={{ width: 6, height: 6, borderRadius: '50%', background: '#f59e0b' }} className="anim-pulse"></span>
              Analyse en cours
            </div>
          )}
          {isDelivered && (
            <div style={{
              display: 'inline-flex', alignItems: 'center', gap: 6,
              fontSize: '.75rem', fontWeight: 600, color: '#10b981',
              background: 'rgba(16,185,129,.1)', padding: '4px 12px', borderRadius: 20
            }}>
              &#10003; Termine
            </div>
          )}
          {isError && (
            <div style={{
              display: 'inline-flex', alignItems: 'center', gap: 6,
              fontSize: '.75rem', fontWeight: 600, color: '#ef4444',
              background: 'rgba(239,68,68,.1)', padding: '4px 12px', borderRadius: 20
            }}>
              Erreur
            </div>
          )}
        </div>

        <h2 style={{ fontSize: '1.25rem', fontWeight: 700, color: '#1c1917', marginBottom: '.25rem' }}>
          {isDelivered ? 'Rapport livre !' : isError ? 'Erreur de traitement' : 'Analyse en cours...'}
        </h2>
        <div style={{ fontSize: '.8rem', color: '#78716c' }}>
          {typeSinistre && `${typeSinistre} — `}
          {!isDelivered && !isError && (
            <span>Temps ecoule : {formatElapsed(elapsed)}</span>
          )}
        </div>

        {/* Progress bar */}
        {!isDelivered && !isError && (
          <>
            <div style={{ background: '#fafaf9', borderRadius: 6, height: 6, marginTop: '1rem', overflow: 'hidden' }}>
              <div style={{
                height: '100%', borderRadius: 6,
                background: 'linear-gradient(90deg, #f59e0b, #f97316)',
                transition: 'width 1s ease',
                width: `${progressPercent}%`
              }}></div>
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 6, fontSize: '.7rem', color: '#a8a29e' }}>
              <span>Etape {activeIndex + 1} sur {PIPELINE_STEPS.length}</span>
              <span>{estimatedRemaining}</span>
            </div>
          </>
        )}
      </div>

      {/* ── Timeline ────────────────────────────────────── */}
      <div style={{ position: 'relative', paddingLeft: '2rem' }}>
        <div style={{ position: 'absolute', left: 11, top: 0, bottom: 0, width: 2, background: '#e7e5e4' }}></div>

        {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="anim-fade-up" style={{ position: 'relative', paddingBottom: index < PIPELINE_STEPS.length - 1 ? '1.5rem' : 0, animationDelay: `${index * 0.08}s` }}>
              {/* Dot */}
              <div style={{
                position: 'absolute', left: '-2rem', width: 24, height: 24, borderRadius: '50%',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontSize: '.6rem', fontWeight: 700, zIndex: 1,
                ...(isDone
                  ? { background: '#10b981', color: '#fff' }
                  : isActive
                    ? { background: '#f59e0b', color: '#fff' }
                    : { background: '#fafaf9', border: '2px solid #e7e5e4', color: '#a8a29e' })
              }} className={isActive ? 'anim-pulse-glow' : ''}>
                {isDone ? '✓' : isActive ? (
                  <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" className="anim-spinner">
                    <path d="M21 12a9 9 0 1 1-6.219-8.56"/>
                  </svg>
                ) : index + 1}
              </div>

              {/* Card */}
              <div style={{
                background: '#fff', border: `1px solid ${isActive ? '#f59e0b' : '#e7e5e4'}`,
                borderRadius: 14, padding: '1rem 1.25rem', marginLeft: '.5rem',
                opacity: isFuture ? 0.5 : 1,
                transition: 'all .3s',
                ...(isActive ? { boxShadow: '0 4px 20px rgba(245,158,11,.1)' } : {})
              }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                  <span style={{ fontSize: '.85rem', fontWeight: 600, color: '#1c1917' }}>{step.label}</span>
                  {step.agent && isActive && (
                    <span style={{
                      fontSize: '.65rem', fontWeight: 600, color: '#f59e0b',
                      background: 'rgba(245,158,11,.1)', padding: '2px 8px', borderRadius: 10
                    }}>
                      {step.agent}
                    </span>
                  )}
                </div>
                <p style={{ fontSize: '.8rem', color: '#78716c', marginTop: 4, lineHeight: 1.5 }}>{step.desc}</p>

                {isActive && (
                  <div style={{
                    display: 'inline-flex', alignItems: 'center', gap: 4,
                    fontSize: '.65rem', fontWeight: 600, color: '#f59e0b',
                    background: 'rgba(245,158,11,.1)', padding: '2px 8px', borderRadius: 10, marginTop: 6
                  }}>
                    <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" style={{ animation: 'spin .8s linear infinite' }}>
                      <path d="M21 12a9 9 0 1 1-6.219-8.56"/>
                    </svg>
                    En cours
                  </div>
                )}

                {isDone && (
                  <div style={{
                    display: 'inline-flex', alignItems: 'center', gap: 4,
                    fontSize: '.65rem', fontWeight: 600, color: '#10b981',
                    background: 'rgba(16,185,129,.1)', padding: '2px 8px', borderRadius: 10, marginTop: 6
                  }}>
                    &#10003; Termine
                  </div>
                )}
              </div>
            </div>
          );
        })}
      </div>

      {/* ── Delivered ────────────────────────────────────── */}
      {isDelivered && (
        <div className="anim-fade-up" style={{ marginTop: '2rem' }}>
          <div style={{
            padding: '1.5rem', borderRadius: 16, border: '2px solid #a7f3d0',
            textAlign: 'center', background: 'rgba(16,185,129,.04)',
            boxShadow: '0 4px 20px rgba(16,185,129,.1)'
          }}>
            <div style={{
              width: 56, height: 56, borderRadius: '50%', background: '#10b981', color: '#fff',
              fontSize: '1.5rem', display: 'flex', alignItems: 'center', justifyContent: 'center',
              margin: '0 auto 1rem'
            }} className="anim-check-bounce">
              &#10003;
            </div>
            <p style={{ fontWeight: 700, fontSize: '1.1rem', color: '#065f46', marginBottom: '.25rem' }}>
              Votre rapport a ete envoye
            </p>
            <p style={{ fontSize: '.85rem', color: '#059669' }}>
              Consultez votre boite mail ({maskEmail(email)})
            </p>
          </div>

          {/* Next steps */}
          <div style={{ marginTop: '1.5rem', background: '#fff', border: '1px solid #e7e5e4', borderRadius: 16, padding: '1.5rem' }}>
            <p style={{ fontSize: '.9rem', fontWeight: 700, color: '#1c1917', marginBottom: '1rem' }}>Prochaines etapes</p>
            <div style={{ display: 'flex', flexDirection: 'column', gap: '.75rem' }}>
              {[
                { n: '1', title: 'Relisez votre rapport', desc: 'Verifiez que les informations correspondent a votre situation.' },
                { n: '2', title: 'Envoyez le courrier en LRAR', desc: 'Lettre recommandee avec accuse de reception. Le courrier est dans le PDF.' },
                { n: '3', title: 'Attendez la reponse (30 jours)', desc: "L'assureur a l'obligation legale de repondre sous 30 jours." },
                { n: '4', title: 'En cas de refus', desc: "Saisissez le mediateur de l'assurance (gratuit) ou consultez un avocat." }
              ].map((s, i) => (
                <div key={i} style={{ display: 'flex', gap: '1rem', alignItems: 'flex-start' }}>
                  <span style={{
                    width: 28, height: 28, borderRadius: 8,
                    background: 'rgba(245,158,11,.1)', color: '#f59e0b',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    fontSize: '.75rem', fontWeight: 700, flexShrink: 0
                  }}>{s.n}</span>
                  <div>
                    <p style={{ fontSize: '.85rem', fontWeight: 600, color: '#1c1917' }}>{s.title}</p>
                    <p style={{ fontSize: '.75rem', color: '#78716c', marginTop: 2, lineHeight: 1.4 }}>{s.desc}</p>
                  </div>
                </div>
              ))}
            </div>
          </div>

          {/* Premium upsell */}
          <div style={{
            marginTop: '1.5rem', padding: '1.5rem', borderRadius: 16,
            background: 'linear-gradient(135deg, rgba(245,158,11,.06), rgba(249,115,22,.06))',
            border: '1px solid rgba(245,158,11,.2)'
          }}>
            <p style={{ fontSize: '.85rem', fontWeight: 700, color: '#f59e0b', marginBottom: 4 }}>
              Besoin d'un expert terrain ?
            </p>
            <p style={{ fontSize: '.8rem', color: '#78716c', lineHeight: 1.5, marginBottom: '.75rem' }}>
              Un expert d'assure humain peut prendre en charge votre dossier de A a Z :
              negociation, suivi, obtention de l'indemnisation juste.
              Honoraires : 10% de l'indemnisation finale. Parfois pris en charge par votre assurance.
            </p>
            <a href="/#premium" style={{
              display: 'inline-block', background: 'transparent',
              border: '1px solid #f59e0b', color: '#f59e0b',
              padding: '8px 20px', borderRadius: 10, fontSize: '.8rem',
              fontWeight: 600, textDecoration: 'none', transition: 'all .2s'
            }}>
              Demander un expert terrain
            </a>
          </div>
        </div>
      )}

      {/* ── Error ────────────────────────────────────────── */}
      {isError && (
        <div className="anim-fade-up" style={{
          marginTop: '2rem', padding: '1.5rem', borderRadius: 16,
          border: '2px solid #fca5a5', textAlign: 'center', background: 'rgba(239,68,68,.04)'
        }}>
          <p style={{ fontWeight: 700, fontSize: '1.1rem', color: '#991b1b', marginBottom: '.25rem' }}>
            Une erreur est survenue
          </p>
          <p style={{ fontSize: '.85rem', color: '#dc2626' }}>
            Notre equipe a ete alertee et vous contactera sous 24h a {maskEmail(email)}.
          </p>
        </div>
      )}

      {/* ── Info card ────────────────────────────────────── */}
      {!isDelivered && !isError && (
        <div className="anim-fade-up" style={{
          marginTop: '2rem', padding: '1rem 1.25rem', borderRadius: 14,
          background: 'rgba(245,158,11,.04)', border: '1px solid rgba(245,158,11,.15)'
        }}>
          <p style={{ fontSize: '.8rem', fontWeight: 600, color: '#f59e0b', marginBottom: 4 }}>
            Vous pouvez fermer cette page
          </p>
          <p style={{ fontSize: '.8rem', color: '#78716c', lineHeight: 1.5 }}>
            Votre rapport sera envoye par email des qu'il sera pret (environ {estimatedRemaining.replace('~', '')}).
            Vous pouvez aussi rester ici pour suivre la progression en temps reel.
          </p>
        </div>
      )}
    </div>
  );
}
