// avatar.jsx — Hola Portrait Avatar
// Sin D-ID key  → foto estática (Ryan) + animaciones CSS
// Con D-ID key  → video WebRTC en tiempo real con lip-sync (DIDAvatar)

function Avatar({ mode = 'idle', size = 'hero', name = 'Leo', role = 'tu asesor de viaje' }) {
  // Leer la API key desde el estado React (no desde window directamente)
  // Escucha el evento 'tweakchange' que TweaksPanel dispara al guardar
  const [apiKey, setApiKey] = React.useState(() => window.__DID_API_KEY || '');

  React.useEffect(() => {
    const onTweak = (e) => {
      if (e.detail && 'didApiKey' in e.detail) {
        const k = (e.detail.didApiKey || '').trim();
        window.__DID_API_KEY = k;
        setApiKey(k);
      }
    };
    window.addEventListener('tweakchange', onTweak);
    return () => window.removeEventListener('tweakchange', onTweak);
  }, []);

  // También revisar si la key ya estaba guardada en window al montar
  React.useEffect(() => {
    const k = (window.__DID_API_KEY || '').trim();
    if (k && k !== apiKey) setApiKey(k);
  }, []); // eslint-disable-line

  if (apiKey) {
    const sourceUrl = (window.__DID_SOURCE_URL || '').trim() || DID_DEFAULT_IMAGE;
    return (
      <DIDAvatar
        apiKey={apiKey}
        sourceUrl={sourceUrl}
        mode={mode}
        size={size}
        name={name}
        role={role}
      />
    );
  }

  // ── Avatar animado SVG (sin D-ID) ────────────────────────────────────────
  return (
    <AnimatedAvatar mode={mode} size={size} name={name} role={role} />
  );
}

Object.assign(window, { Avatar });
